Remap CraftBukkit to Mojang+Yarn Mappings

By: Initial Source <noreply+automated@papermc.io>
This commit is contained in:
CraftBukkit/Spigot
2024-12-11 22:26:55 +01:00
parent a265d64138
commit 30e4583dbe
1780 changed files with 44628 additions and 41274 deletions

View File

@@ -2,7 +2,6 @@ package org.bukkit;
import static org.junit.jupiter.api.Assertions.*;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.level.biome.BiomeBase;
import org.bukkit.block.Biome;
import org.bukkit.craftbukkit.CraftRegistry;
import org.bukkit.craftbukkit.block.CraftBiome;
@@ -25,7 +24,7 @@ public class BiomeTest {
@Test
public void testMinecraftToBukkit() {
for (BiomeBase biomeBase : CraftRegistry.getMinecraftRegistry(Registries.BIOME)) {
for (net.minecraft.world.level.biome.Biome biomeBase : CraftRegistry.getMinecraftRegistry(Registries.BIOME)) {
Biome biome = CraftBiome.minecraftToBukkit(biomeBase);
assertTrue(biome != null && biome != Biome.CUSTOM, "No Bukkit mapping for " + biomeBase);
}

View File

@@ -4,7 +4,7 @@ import static org.junit.jupiter.api.Assertions.*;
import java.util.stream.Stream;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.IBlockData;
import net.minecraft.world.level.block.state.BlockState;
import org.bukkit.craftbukkit.block.data.CraftBlockData;
import org.bukkit.support.environment.AllFeatures;
import org.junit.jupiter.params.ParameterizedTest;
@@ -24,7 +24,7 @@ public class BlockDataConversionTest {
@ParameterizedTest
@MethodSource("data")
public void testNotNull(IBlockData data) {
public void testNotNull(BlockState data) {
assertNotNull(data);
assertNotNull(CraftBlockData.fromData(data));
}

View File

@@ -3,10 +3,11 @@ package org.bukkit;
import static org.bukkit.support.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
import net.minecraft.core.EnumDirection;
import net.minecraft.world.level.block.BlockCake;
import net.minecraft.world.level.block.BlockChest;
import net.minecraft.core.Direction;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.CakeBlock;
import net.minecraft.world.level.block.ChestBlock;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockType;
import org.bukkit.block.data.BlockData;
@@ -21,7 +22,7 @@ public class BlockDataTest {
@Test
public void testParsing() {
BlockData cakeTest = CraftBlockData.fromData(Blocks.CAKE.defaultBlockState().setValue(BlockCake.BITES, 3));
BlockData cakeTest = CraftBlockData.fromData(Blocks.CAKE.defaultBlockState().setValue(CakeBlock.BITES, 3));
BlockData materialString = CraftBlockData.newData(BlockType.CAKE, "[bites=3]");
assertThat(materialString, is(cakeTest));
@@ -53,7 +54,7 @@ public class BlockDataTest {
@Test
public void testMistake() {
BlockData cakeTest = CraftBlockData.fromData(Blocks.CAKE.defaultBlockState().setValue(BlockCake.BITES, 3));
BlockData cakeTest = CraftBlockData.fromData(Blocks.CAKE.defaultBlockState().setValue(CakeBlock.BITES, 3));
assertThrows(IllegalArgumentException.class, () -> CraftBlockData.newData(BlockType.CAKE, cakeTest.toString()));
}
@@ -65,7 +66,7 @@ public class BlockDataTest {
@Test
public void testClone() {
Cake cakeTest = (Cake) CraftBlockData.fromData(Blocks.CAKE.defaultBlockState().setValue(BlockCake.BITES, 3));
Cake cakeTest = (Cake) CraftBlockData.fromData(Blocks.CAKE.defaultBlockState().setValue(CakeBlock.BITES, 3));
Cake clone = (Cake) cakeTest.clone();
assertNotSame(cakeTest, clone, "Clone did not return new object");
@@ -144,7 +145,7 @@ public class BlockDataTest {
assertFalse(CraftBlockData.newData(null, "minecraft:trapped_chest[facing=east,waterlogged=false]").matches(CraftBlockData.newData(null, "minecraft:chest[waterlogged=true]")));
assertTrue(CraftBlockData.newData(null, "minecraft:chest[facing=east,waterlogged=true]").matches(CraftBlockData.newData(null, "minecraft:chest[waterlogged=true,facing=east]")));
Chest one = (Chest) CraftBlockData.fromData(Blocks.CHEST.defaultBlockState().setValue(BlockChest.FACING, EnumDirection.EAST));
Chest one = (Chest) CraftBlockData.fromData(Blocks.CHEST.defaultBlockState().setValue(ChestBlock.FACING, Direction.EAST));
Chest two = (Chest) CraftBlockData.newData(null, "minecraft:chest[waterlogged=false]");
assertTrue(one.matches(two));
@@ -162,7 +163,7 @@ public class BlockDataTest {
@Test
public void testGetAsString2() {
Chest data = (Chest) CraftBlockData.fromData(Blocks.CHEST.defaultBlockState().setValue(BlockChest.FACING, EnumDirection.EAST));
Chest data = (Chest) CraftBlockData.fromData(Blocks.CHEST.defaultBlockState().setValue(ChestBlock.FACING, Direction.EAST));
assertThat(data.getAsString(true), is("minecraft:chest[facing=east,type=single,waterlogged=false]"));
assertThat(data.getAsString(false), is("minecraft:chest[facing=east,type=single,waterlogged=false]"));

View File

@@ -1,8 +1,9 @@
package org.bukkit;
import static org.junit.jupiter.api.Assertions.*;
import net.minecraft.EnumChatFormat;
import net.minecraft.network.chat.IChatBaseComponent;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import org.bukkit.craftbukkit.util.CraftChatMessage;
import org.bukkit.support.environment.VanillaFeature;
import org.junit.jupiter.api.Test;
@@ -17,7 +18,7 @@ public class ChatTest {
assertEquals(color, CraftChatMessage.getColor(CraftChatMessage.getColor(color)));
}
for (EnumChatFormat format : EnumChatFormat.values()) {
for (ChatFormatting format : ChatFormatting.values()) {
assertNotNull(CraftChatMessage.getColor(format));
assertEquals(format, CraftChatMessage.getColor(CraftChatMessage.getColor(format)));
}
@@ -25,7 +26,7 @@ public class ChatTest {
@Test
public void testURLJsonConversion() {
IChatBaseComponent[] components;
Component[] components;
components = CraftChatMessage.fromString("https://spigotmc.org/test Test Message");
assertEquals("{\"text\":\"\",\"extra\":[{\"text\":\"https://spigotmc.org/test\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"https://spigotmc.org/test\"}},\" Test Message\"]}",
CraftChatMessage.toJSON(components[0]));

View File

@@ -2,7 +2,8 @@ package org.bukkit;
import static org.bukkit.support.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import net.minecraft.world.item.EnumColor;
import net.minecraft.world.item.DyeColor;
import org.bukkit.support.environment.Normal;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
@@ -14,16 +15,16 @@ public class DyeColorsTest {
@EnumSource(DyeColor.class)
public void checkColor(DyeColor dye) {
Color color = dye.getColor();
int nmsColorArray = EnumColor.byId(dye.getWoolData()).getTextureDiffuseColor();
int nmsColorArray = DyeColor.byId(dye.getWoolData()).getTextureDiffuseColor();
Color nmsColor = Color.fromARGB(nmsColorArray);
assertThat(color, is(nmsColor));
}
@ParameterizedTest
@EnumSource(DyeColor.class)
public void checkFireworkColor(DyeColor dye) {
@EnumSource(org.bukkit.DyeColor.class)
public void checkFireworkColor(org.bukkit.DyeColor dye) {
Color color = dye.getFireworkColor();
int nmsColor = EnumColor.byId(dye.getWoolData()).getFireworkColor();
int nmsColor = DyeColor.byId(dye.getWoolData()).getFireworkColor();
assertThat(color, is(Color.fromRGB(nmsColor)));
}
}

View File

@@ -2,7 +2,7 @@ package org.bukkit;
import static org.junit.jupiter.api.Assertions.*;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.resources.ResourceLocation;
import org.bukkit.craftbukkit.CraftRegistry;
import org.bukkit.craftbukkit.util.CraftNamespacedKey;
import org.bukkit.enchantments.Enchantment;
@@ -14,7 +14,7 @@ public class EnchantmentTest {
@Test
public void verifyMapping() {
for (MinecraftKey key : CraftRegistry.getMinecraftRegistry(Registries.ENCHANTMENT).keySet()) {
for (ResourceLocation key : CraftRegistry.getMinecraftRegistry(Registries.ENCHANTMENT).keySet()) {
net.minecraft.world.item.enchantment.Enchantment nms = CraftRegistry.getMinecraftRegistry(Registries.ENCHANTMENT).getValue(key);
Enchantment bukkitById = Enchantment.getByKey(CraftNamespacedKey.fromMinecraft(key));

View File

@@ -10,13 +10,13 @@ public class ExplosionResultTest {
@Test
public void testMatchingEnum() {
for (ExplosionResult result : ExplosionResult.values()) {
assertNotNull(Explosion.Effect.valueOf(result.name()), "No NMS enum for Bukkit result " + result);
assertNotNull(Explosion.BlockInteraction.valueOf(result.name()), "No NMS enum for Bukkit result " + result);
}
}
@Test
public void testToBukkit() {
for (Explosion.Effect effect : Explosion.Effect.values()) {
for (Explosion.BlockInteraction effect : Explosion.BlockInteraction.values()) {
assertNotNull(CraftExplosionResult.toBukkit(effect), "No Bukkit enum for NMS explosion effect " + effect);
}
}

View File

@@ -24,9 +24,9 @@ public class GameRuleTest {
@Test
public void testMinecraftRules() {
Map<String, GameRules.GameRuleKey<?>> minecraftRules = CraftWorld.getGameRulesNMS(new GameRules(FeatureFlags.REGISTRY.allFlags()));
Map<String, GameRules.Key<?>> minecraftRules = CraftWorld.getGameRulesNMS(new GameRules(FeatureFlags.REGISTRY.allFlags()));
for (Map.Entry<String, GameRules.GameRuleKey<?>> entry : minecraftRules.entrySet()) {
for (Map.Entry<String, GameRules.Key<?>> entry : minecraftRules.entrySet()) {
GameRule<?> bukkitRule = GameRule.getByName(entry.getKey());
assertNotNull(bukkitRule, "Missing " + entry.getKey());

View File

@@ -25,7 +25,7 @@ public class LootTablesTest {
@Test
public void testNMS() {
for (ResourceKey<net.minecraft.world.level.storage.loot.LootTable> key : net.minecraft.world.level.storage.loot.LootTables.all()) {
for (ResourceKey<net.minecraft.world.level.storage.loot.LootTable> key : net.minecraft.world.level.storage.loot.BuiltInLootTables.all()) {
NamespacedKey bukkitKey = CraftLootTable.minecraftToBukkitKey(key);
LootTables lootTable = Registry.LOOT_TABLES.get(bukkitKey);

View File

@@ -13,7 +13,7 @@ import java.util.List;
import java.util.Map;
import java.util.stream.StreamSupport;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import org.bukkit.craftbukkit.util.CraftMagicNumbers;
import org.bukkit.support.LegacyHelper;
@@ -25,7 +25,7 @@ public class MaterialTest {
@Test
public void verifyMapping() {
Map<MinecraftKey, Material> materials = Maps.newHashMap();
Map<ResourceLocation, Material> materials = Maps.newHashMap();
for (Material material : Material.values()) {
if (LegacyHelper.getInvalidatedMaterials().contains(material)) {
continue;
@@ -40,7 +40,7 @@ public class MaterialTest {
Item item = items.next();
if (item == null) continue;
MinecraftKey id = BuiltInRegistries.ITEM.getKey(item);
ResourceLocation id = BuiltInRegistries.ITEM.getKey(item);
String name = item.getDescriptionId();
Material material = materials.remove(id);

View File

@@ -4,22 +4,22 @@ import static org.junit.jupiter.api.Assertions.*;
import com.mojang.serialization.DataResult;
import java.util.Optional;
import java.util.stream.Stream;
import net.minecraft.core.particles.BlockParticleOption;
import net.minecraft.core.particles.ColorParticleOption;
import net.minecraft.core.particles.DustColorTransitionOptions;
import net.minecraft.core.particles.ParticleParam;
import net.minecraft.core.particles.ParticleParamBlock;
import net.minecraft.core.particles.ParticleParamItem;
import net.minecraft.core.particles.ParticleParamRedstone;
import net.minecraft.core.particles.ParticleType;
import net.minecraft.core.particles.DustParticleOptions;
import net.minecraft.core.particles.ItemParticleOption;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.core.particles.SculkChargeParticleOptions;
import net.minecraft.core.particles.ShriekParticleOption;
import net.minecraft.core.particles.SimpleParticleType;
import net.minecraft.core.particles.TrailParticleOption;
import net.minecraft.core.particles.VibrationParticleOption;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.DynamicOpsNBT;
import net.minecraft.nbt.NBTBase;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.world.phys.Vec3D;
import net.minecraft.nbt.NbtOps;
import net.minecraft.nbt.Tag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.phys.Vec3;
import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.CraftParticle;
import org.bukkit.craftbukkit.CraftRegistry;
@@ -44,7 +44,7 @@ public class ParticleTest {
@ParameterizedTest
@MethodSource("data")
public void testBukkitValuesPresent(MinecraftKey minecraft) {
public void testBukkitValuesPresent(ResourceLocation minecraft) {
// TODO: 10/19/23 Remove with enum PR, it is then no longer needed, since the enum PR has a extra test for this
assertNotNull(Registry.PARTICLE_TYPE.get(CraftNamespacedKey.fromMinecraft(minecraft)), String.format("""
No bukkit particle found for minecraft particle %s.
@@ -66,55 +66,55 @@ public class ParticleTest {
@ParameterizedTest
@EnumSource(Particle.class)
public void testRightParticleParamCreation(Particle bukkit) {
net.minecraft.core.particles.Particle<?> minecraft = CraftParticle.bukkitToMinecraft(bukkit);
net.minecraft.core.particles.ParticleType<?> minecraft = CraftParticle.bukkitToMinecraft(bukkit);
if (bukkit.getDataType().equals(Void.class)) {
testEmptyData(bukkit, minecraft);
this.testEmptyData(bukkit, minecraft);
return;
}
if (bukkit.getDataType().equals(Particle.DustOptions.class)) {
testDustOption(bukkit, minecraft);
this.testDustOption(bukkit, minecraft);
return;
}
if (bukkit.getDataType().equals(ItemStack.class)) {
testItemStack(bukkit, minecraft);
this.testItemStack(bukkit, minecraft);
return;
}
if (bukkit.getDataType().equals(BlockData.class)) {
testBlockData(bukkit, minecraft);
this.testBlockData(bukkit, minecraft);
return;
}
if (bukkit.getDataType().equals(Particle.DustTransition.class)) {
testDustTransition(bukkit, minecraft);
this.testDustTransition(bukkit, minecraft);
return;
}
if (bukkit.getDataType().equals(Vibration.class)) {
testVibration(bukkit, minecraft);
this.testVibration(bukkit, minecraft);
return;
}
if (bukkit.getDataType().equals(Float.class)) {
testFloat(bukkit, minecraft);
this.testFloat(bukkit, minecraft);
return;
}
if (bukkit.getDataType().equals(Integer.class)) {
testInteger(bukkit, minecraft);
this.testInteger(bukkit, minecraft);
return;
}
if (bukkit.getDataType().equals(Color.class)) {
testColor(bukkit, minecraft);
this.testColor(bukkit, minecraft);
return;
}
if (bukkit.getDataType().equals(Particle.Trail.class)) {
testTrail(bukkit, minecraft);
this.testTrail(bukkit, minecraft);
return;
}
@@ -124,13 +124,13 @@ public class ParticleTest {
""", bukkit.getKey()));
}
private <T extends ParticleParam> void testEmptyData(Particle bukkit, net.minecraft.core.particles.Particle<T> minecraft) {
createAndTest(bukkit, minecraft, null, ParticleType.class);
private <T extends ParticleOptions> void testEmptyData(Particle bukkit, net.minecraft.core.particles.ParticleType<T> minecraft) {
this.createAndTest(bukkit, minecraft, null, SimpleParticleType.class);
}
private <T extends ParticleParam> void testDustOption(Particle bukkit, net.minecraft.core.particles.Particle<T> minecraft) {
private <T extends ParticleOptions> void testDustOption(Particle bukkit, net.minecraft.core.particles.ParticleType<T> minecraft) {
Particle.DustOptions dustOptions = new Particle.DustOptions(Color.fromRGB(236, 28, 36), 0.1205f);
ParticleParamRedstone param = createAndTest(bukkit, minecraft, dustOptions, ParticleParamRedstone.class);
DustParticleOptions param = this.createAndTest(bukkit, minecraft, dustOptions, DustParticleOptions.class);
assertEquals(0.1205f, param.getScale(), 0.001, String.format("""
Dust option scale for particle %s do not match.
@@ -146,9 +146,9 @@ public class ParticleTest {
""", bukkit.getKey(), expectedColor, param.getColor())); // Print expected and got since we use assert true
}
private <T extends ParticleParam> void testItemStack(Particle bukkit, net.minecraft.core.particles.Particle<T> minecraft) {
private <T extends ParticleOptions> void testItemStack(Particle bukkit, net.minecraft.core.particles.ParticleType<T> minecraft) {
ItemStack itemStack = new ItemStack(Material.STONE);
ParticleParamItem param = createAndTest(bukkit, minecraft, itemStack, ParticleParamItem.class);
ItemParticleOption param = this.createAndTest(bukkit, minecraft, itemStack, ItemParticleOption.class);
assertEquals(itemStack, CraftItemStack.asBukkitCopy(param.getItem()), String.format("""
ItemStack for particle %s do not match.
@@ -156,9 +156,9 @@ public class ParticleTest {
""", bukkit.getKey()));
}
private <T extends ParticleParam> void testBlockData(Particle bukkit, net.minecraft.core.particles.Particle<T> minecraft) {
private <T extends ParticleOptions> void testBlockData(Particle bukkit, net.minecraft.core.particles.ParticleType<T> minecraft) {
BlockData blockData = Bukkit.createBlockData(Material.STONE);
ParticleParamBlock param = createAndTest(bukkit, minecraft, blockData, ParticleParamBlock.class);
BlockParticleOption param = this.createAndTest(bukkit, minecraft, blockData, BlockParticleOption.class);
assertEquals(blockData, CraftBlockData.fromData(param.getState()), String.format("""
Block data for particle %s do not match.
@@ -166,9 +166,9 @@ public class ParticleTest {
""", bukkit.getKey()));
}
private <T extends ParticleParam> void testDustTransition(Particle bukkit, net.minecraft.core.particles.Particle<T> minecraft) {
private <T extends ParticleOptions> void testDustTransition(Particle bukkit, net.minecraft.core.particles.ParticleType<T> minecraft) {
Particle.DustTransition dustTransition = new Particle.DustTransition(Color.fromRGB(236, 28, 36), Color.fromRGB(107, 159, 181), 0.1205f);
DustColorTransitionOptions param = createAndTest(bukkit, minecraft, dustTransition, DustColorTransitionOptions.class);
DustColorTransitionOptions param = this.createAndTest(bukkit, minecraft, dustTransition, DustColorTransitionOptions.class);
assertEquals(0.1205f, param.getScale(), 0.001, String.format("""
Dust transition scale for particle %s do not match.
@@ -192,31 +192,31 @@ public class ParticleTest {
""", bukkit.getKey(), expectedTo, param.getToColor())); // Print expected and got since we use assert true
}
private <T extends ParticleParam> void testVibration(Particle bukkit, net.minecraft.core.particles.Particle<T> minecraft) {
private <T extends ParticleOptions> void testVibration(Particle bukkit, net.minecraft.core.particles.ParticleType<T> minecraft) {
Vibration vibration = new Vibration(new Location(null, 3, 1, 4), new Vibration.Destination.BlockDestination(new Location(null, 1, 5, 9)), 265);
VibrationParticleOption param = createAndTest(bukkit, minecraft, vibration, VibrationParticleOption.class);
VibrationParticleOption param = this.createAndTest(bukkit, minecraft, vibration, VibrationParticleOption.class);
assertEquals(265, param.getArrivalInTicks(), String.format("""
Vibration ticks for particle %s do not match.
Did something change in the implementation or minecraft?
""", bukkit.getKey()));
Optional<Vec3D> pos = param.getDestination().getPosition(null);
Optional<Vec3> pos = param.getDestination().getPosition(null);
assertTrue(pos.isPresent(), String.format("""
Vibration position for particle %s is not present.
Did something change in the implementation or minecraft?
""", bukkit.getKey()));
// Add 0.5 since it gets centered to the block
assertEquals(new Vec3D(1.5, 5.5, 9.5), pos.get(), String.format("""
assertEquals(new Vec3(1.5, 5.5, 9.5), pos.get(), String.format("""
Vibration position for particle %s do not match.
Did something change in the implementation or minecraft?
""", bukkit.getKey()));
}
private <T extends ParticleParam> void testFloat(Particle bukkit, net.minecraft.core.particles.Particle<T> minecraft) {
private <T extends ParticleOptions> void testFloat(Particle bukkit, net.minecraft.core.particles.ParticleType<T> minecraft) {
float role = 0.1205f;
SculkChargeParticleOptions param = createAndTest(bukkit, minecraft, role, SculkChargeParticleOptions.class);
SculkChargeParticleOptions param = this.createAndTest(bukkit, minecraft, role, SculkChargeParticleOptions.class);
assertEquals(role, param.roll(), 0.001, String.format("""
Float role for particle %s do not match.
@@ -224,9 +224,9 @@ public class ParticleTest {
""", bukkit.getKey()));
}
private <T extends ParticleParam> void testInteger(Particle bukkit, net.minecraft.core.particles.Particle<T> minecraft) {
private <T extends ParticleOptions> void testInteger(Particle bukkit, net.minecraft.core.particles.ParticleType<T> minecraft) {
int delay = 1205;
ShriekParticleOption param = createAndTest(bukkit, minecraft, delay, ShriekParticleOption.class);
ShriekParticleOption param = this.createAndTest(bukkit, minecraft, delay, ShriekParticleOption.class);
assertEquals(delay, param.getDelay(), String.format("""
Integer delay for particle %s do not match.
@@ -234,9 +234,9 @@ public class ParticleTest {
""", bukkit.getKey()));
}
private <T extends ParticleParam> void testColor(Particle bukkit, net.minecraft.core.particles.Particle<T> minecraft) {
private <T extends ParticleOptions> void testColor(Particle bukkit, net.minecraft.core.particles.ParticleType<T> minecraft) {
Color color = Color.fromARGB(107, 236, 28, 36);
ColorParticleOption param = createAndTest(bukkit, minecraft, color, ColorParticleOption.class);
ColorParticleOption param = this.createAndTest(bukkit, minecraft, color, ColorParticleOption.class);
Vector4f actual = new Vector4f(param.getAlpha(), param.getRed(), param.getGreen(), param.getBlue());
Vector4f expected = new Vector4f(0.4196f, 0.92549f, 0.1098f, 0.14117647f);
@@ -248,14 +248,14 @@ public class ParticleTest {
""", bukkit.getKey(), expected, actual)); // Print expected and got since we use assert true
}
private <T extends ParticleParam> void testTrail(Particle bukkit, net.minecraft.core.particles.Particle<T> minecraft) {
private <T extends ParticleOptions> void testTrail(Particle bukkit, net.minecraft.core.particles.ParticleType<T> minecraft) {
Color color = Color.fromRGB(236, 28, 36);
Particle.Trail trail = new Particle.Trail(new Location(null, 1, 5, 9), color, 20);
TrailParticleOption param = createAndTest(bukkit, minecraft, trail, TrailParticleOption.class);
TrailParticleOption param = this.createAndTest(bukkit, minecraft, trail, TrailParticleOption.class);
Vec3D pos = param.target();
assertEquals(new Vec3D(1.0, 5.0, 9.0), pos, String.format("""
Vec3 pos = param.target();
assertEquals(new Vec3(1.0, 5.0, 9.0), pos, String.format("""
Vibration position for particle %s do not match.
Did something change in the implementation or minecraft?
""", bukkit.getKey()));
@@ -270,7 +270,7 @@ public class ParticleTest {
""", bukkit.getKey(), expected, actual)); // Print expected and got since we use assert true
}
private <D extends ParticleParam, T extends ParticleParam> D createAndTest(Particle bukkit, net.minecraft.core.particles.Particle<T> minecraft, Object data, Class<D> paramClass) {
private <D extends ParticleOptions, T extends ParticleOptions> D createAndTest(Particle bukkit, net.minecraft.core.particles.ParticleType<T> minecraft, Object data, Class<D> paramClass) {
@SuppressWarnings("unchecked")
T particleParam = (T) assertDoesNotThrow(() -> CraftParticle.createParticleParam(bukkit, data), String.format("""
Could not create particle param for particle %s.
@@ -279,14 +279,14 @@ public class ParticleTest {
Check in CraftParticle if the conversion is still correct.
""", bukkit.getKey()));
DataResult<NBTBase> encoded = assertDoesNotThrow(() -> minecraft.codec().codec().encodeStart(DynamicOpsNBT.INSTANCE, particleParam),
DataResult<Tag> encoded = assertDoesNotThrow(() -> minecraft.codec().codec().encodeStart(DynamicOpsNBT.INSTANCE, particleParam),
String.format("""
Could not encoded particle param for particle %s.
This can indicated, that the wrong particle param is created in CraftParticle.
Particle param is of type %s.
""", bukkit.getKey(), particleParam.getClass()));
Optional<DataResult.Error<NBTBase>> encodeError = encoded.error();
Optional<DataResult.Error<Tag>> encodeError = encoded.error();
assertTrue(encodeError.isEmpty(), () -> String.format("""
Could not encoded particle param for particle %s.
This is possible because the wrong particle param is created in CraftParticle.
@@ -294,14 +294,14 @@ public class ParticleTest {
Error message: %s.
""", bukkit.getKey(), particleParam.getClass(), encoded.error().get().message()));
Optional<NBTBase> encodeResult = encoded.result();
Optional<Tag> encodeResult = encoded.result();
assertTrue(encodeResult.isPresent(), String.format("""
Result is not present for particle %s.
Even though there is also no error, this should not happen.
Particle param is of type %s.
""", bukkit.getKey(), particleParam.getClass()));
DataResult<T> decoded = minecraft.codec().codec().parse(DynamicOpsNBT.INSTANCE, encodeResult.get());
DataResult<T> decoded = minecraft.codec().codec().parse(NbtOps.INSTANCE, encodeResult.get());
Optional<DataResult.Error<T>> decodeError = decoded.error();
assertTrue(decodeError.isEmpty(), () -> String.format("""

View File

@@ -4,21 +4,20 @@ import static org.bukkit.support.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Map;
import net.minecraft.core.BlockPosition;
import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponents;
import net.minecraft.world.EnumHand;
import net.minecraft.world.entity.EnumItemSlot;
import net.minecraft.world.entity.player.EntityHuman;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.equipment.Equippable;
import net.minecraft.world.level.BlockAccessAir;
import net.minecraft.world.level.EmptyBlockGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.BlockFire;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.Fallable;
import net.minecraft.world.level.block.state.BlockBase;
import net.minecraft.world.level.block.state.IBlockData;
import net.minecraft.world.phys.MovingObjectPositionBlock;
import net.minecraft.world.level.block.FireBlock;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.CraftEquipmentSlot;
import org.bukkit.craftbukkit.inventory.CraftItemStack;
@@ -39,7 +38,7 @@ public class PerMaterialTest {
@BeforeAll
public static void getFireValues() {
fireValues = ((BlockFire) Blocks.FIRE).igniteOdds;
PerMaterialTest.fireValues = ((FireBlock) Blocks.FIRE).igniteOdds;
}
@ParameterizedTest
@@ -142,7 +141,7 @@ public class PerMaterialTest {
public void isBurnable(Material material) {
if (material.isBlock()) {
Block block = CraftMagicNumbers.getBlock(material);
assertThat(material.isBurnable(), is(fireValues.containsKey(block) && fireValues.get(block) > 0));
assertThat(material.isBurnable(), is(PerMaterialTest.fireValues.containsKey(block) && PerMaterialTest.fireValues.get(block) > 0));
} else {
assertFalse(material.isBurnable());
}
@@ -152,7 +151,7 @@ public class PerMaterialTest {
@EnumSource(value = Material.class, names = "LEGACY_.*", mode = EnumSource.Mode.MATCH_NONE)
public void isOccluding(Material material) {
if (material.isBlock()) {
assertThat(material.isOccluding(), is(CraftMagicNumbers.getBlock(material).defaultBlockState().isRedstoneConductor(BlockAccessAir.INSTANCE, BlockPosition.ZERO)));
assertThat(material.isOccluding(), is(CraftMagicNumbers.getBlock(material).defaultBlockState().isRedstoneConductor(EmptyBlockGetter.INSTANCE, BlockPos.ZERO)));
} else {
assertFalse(material.isOccluding());
}
@@ -224,14 +223,14 @@ public class PerMaterialTest {
if (material.isBlock()) {
Class<?> clazz = CraftMagicNumbers.getBlock(material).getClass();
boolean hasMethod = hasMethod(clazz, "useWithoutItem", IBlockData.class, net.minecraft.world.level.World.class, BlockPosition.class, EntityHuman.class, MovingObjectPositionBlock.class)
|| hasMethod(clazz, "useItemOn", net.minecraft.world.item.ItemStack.class, IBlockData.class, net.minecraft.world.level.World.class, BlockPosition.class, EntityHuman.class, EnumHand.class, MovingObjectPositionBlock.class);
boolean hasMethod = this.hasMethod(clazz, "useWithoutItem", BlockState.class, net.minecraft.world.level.Level.class, BlockPos.class, Player.class, BlockHitResult.class)
|| this.hasMethod(clazz, "useItemOn", net.minecraft.world.item.ItemStack.class, BlockState.class, net.minecraft.world.level.Level.class, BlockPos.class, Player.class, InteractionHand.class, BlockHitResult.class);
if (!hasMethod && clazz.getSuperclass() != BlockBase.class) {
if (!hasMethod && clazz.getSuperclass() != BlockBehaviour.class) {
clazz = clazz.getSuperclass();
hasMethod = hasMethod(clazz, "useWithoutItem", IBlockData.class, net.minecraft.world.level.World.class, BlockPosition.class, EntityHuman.class, MovingObjectPositionBlock.class)
|| hasMethod(clazz, "useItemOn", net.minecraft.world.item.ItemStack.class, IBlockData.class, net.minecraft.world.level.World.class, BlockPosition.class, EntityHuman.class, EnumHand.class, MovingObjectPositionBlock.class);
hasMethod = this.hasMethod(clazz, "useWithoutItem", BlockState.class, net.minecraft.world.level.Level.class, BlockPos.class, Player.class, BlockHitResult.class)
|| this.hasMethod(clazz, "useItemOn", net.minecraft.world.item.ItemStack.class, BlockState.class, net.minecraft.world.level.Level.class, BlockPos.class, Player.class, InteractionHand.class, BlockHitResult.class);
}
assertThat(material.isInteractable(),
@@ -300,7 +299,7 @@ public class PerMaterialTest {
public void testEquipmentSlot(Material material) {
if (material.isItem()) {
Equippable equipable = CraftItemStack.asNMSCopy(new ItemStack(material)).get(DataComponents.EQUIPPABLE);
EquipmentSlot expected = CraftEquipmentSlot.getSlot(equipable != null ? equipable.slot() : EnumItemSlot.MAINHAND);
EquipmentSlot expected = CraftEquipmentSlot.getSlot(equipable != null ? equipable.slot() : net.minecraft.world.entity.EquipmentSlot.MAINHAND);
assertThat(material.getEquipmentSlot(), is(expected));
}
}

View File

@@ -7,8 +7,8 @@ import com.google.common.collect.Lists;
import java.util.Collections;
import java.util.List;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.world.effect.MobEffectInfo;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.effect.MobEffectCategory;
import org.bukkit.craftbukkit.potion.CraftPotionEffectTypeCategory;
import org.bukkit.craftbukkit.util.CraftNamespacedKey;
import org.bukkit.potion.PotionEffectType;
@@ -23,7 +23,7 @@ public class PotionEffectTypeTest {
public void verifyMapping() {
List<PotionEffectType> effects = Lists.newArrayList(PotionEffectType.values());
for (MinecraftKey key : BuiltInRegistries.MOB_EFFECT.keySet()) {
for (ResourceLocation key : BuiltInRegistries.MOB_EFFECT.keySet()) {
String name = key.getPath();
PotionEffectType effect = PotionEffectType.getByKey(CraftNamespacedKey.fromMinecraft(key));
@@ -43,7 +43,7 @@ public class PotionEffectTypeTest {
assertDoesNotThrow(() -> CraftPotionEffectTypeCategory.bukkitToMinecraft(category), "PotionEffectTypeCategory." + categoryName + " exists but MobEffectInfo." + categoryName + " does not!");
}
for (MobEffectInfo info : MobEffectInfo.values()) {
for (MobEffectCategory info : MobEffectCategory.values()) {
assertDoesNotThrow(() -> CraftPotionEffectTypeCategory.minecraftToBukkit(info), "Missing PotionEffectTypeCategory for MobEffectInfo." + info.name());
}
}

View File

@@ -5,7 +5,7 @@ import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Locale;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.resources.ResourceLocation;
import org.bukkit.craftbukkit.CraftSound;
import org.bukkit.support.environment.AllFeatures;
import org.junit.jupiter.api.Test;
@@ -22,7 +22,7 @@ public class SoundTest {
@Test
public void testReverse() {
for (MinecraftKey effect : BuiltInRegistries.SOUND_EVENT.keySet()) {
for (ResourceLocation effect : BuiltInRegistries.SOUND_EVENT.keySet()) {
assertNotNull(Sound.valueOf(effect.getPath().replace('.', '_').toUpperCase(Locale.ROOT)), effect + "");
}
}
@@ -30,13 +30,13 @@ public class SoundTest {
@Test
public void testCategory() {
for (SoundCategory category : SoundCategory.values()) {
assertNotNull(net.minecraft.sounds.SoundCategory.valueOf(category.name()), category + "");
assertNotNull(net.minecraft.sounds.SoundSource.valueOf(category.name()), category + "");
}
}
@Test
public void testCategoryReverse() {
for (net.minecraft.sounds.SoundCategory category : net.minecraft.sounds.SoundCategory.values()) {
for (net.minecraft.sounds.SoundSource category : net.minecraft.sounds.SoundSource.values()) {
assertNotNull(SoundCategory.valueOf(category.name()), category + "");
}
}

View File

@@ -5,8 +5,7 @@ import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
import com.google.common.collect.HashMultiset;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.stats.StatisticWrapper;
import net.minecraft.world.entity.EntityTypes;
import net.minecraft.stats.StatType;
import org.bukkit.craftbukkit.CraftStatistic;
import org.bukkit.entity.EntityType;
import org.bukkit.support.environment.AllFeatures;
@@ -33,9 +32,9 @@ public class StatisticsAndAchievementsTest {
@SuppressWarnings("unchecked")
public void verifyStatisticMapping() throws Throwable {
HashMultiset<Statistic> statistics = HashMultiset.create();
for (StatisticWrapper wrapper : BuiltInRegistries.STAT_TYPE) {
for (StatType wrapper : BuiltInRegistries.STAT_TYPE) {
for (Object child : wrapper.getRegistry()) {
net.minecraft.stats.Statistic<?> statistic = wrapper.get(child);
net.minecraft.stats.Stat<?> statistic = wrapper.get(child);
String message = String.format("org.bukkit.Statistic is missing: '%s'", statistic);
Statistic subject = CraftStatistic.getBukkitStatistic(statistic);
@@ -44,7 +43,7 @@ public class StatisticsAndAchievementsTest {
if (wrapper.getRegistry() == BuiltInRegistries.BLOCK || wrapper.getRegistry() == BuiltInRegistries.ITEM) {
assertNotNull(CraftStatistic.getMaterialFromStatistic(statistic), "Material type map missing for " + wrapper.getRegistry().getKey(child));
} else if (wrapper.getRegistry() == BuiltInRegistries.ENTITY_TYPE) {
assertNotNull(CraftStatistic.getEntityTypeFromStatistic((net.minecraft.stats.Statistic<EntityTypes<?>>) statistic), "Entity type map missing for " + EntityTypes.getKey((EntityTypes<?>) child));
assertNotNull(CraftStatistic.getEntityTypeFromStatistic((net.minecraft.stats.Stat<net.minecraft.world.entity.EntityType<?>>) statistic), "Entity type map missing for " + net.minecraft.world.entity.EntityType.getKey((net.minecraft.world.entity.EntityType<?>) child));
}
statistics.add(subject);

View File

@@ -1,10 +1,10 @@
package org.bukkit.block.banner;
import static org.junit.jupiter.api.Assertions.*;
import net.minecraft.core.IRegistry;
import net.minecraft.core.registries.Registries;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.block.entity.EnumBannerPatternType;
import net.minecraft.world.level.block.entity.BannerPattern;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.craftbukkit.util.CraftNamespacedKey;
@@ -16,7 +16,7 @@ public class PatternTypeTest {
@Test
public void testToBukkit() {
for (EnumBannerPatternType nms : MinecraftServer.getDefaultRegistryAccess().lookupOrThrow(Registries.BANNER_PATTERN)) {
for (BannerPattern nms : MinecraftServer.getDefaultRegistryAccess().lookupOrThrow(Registries.BANNER_PATTERN)) {
PatternType bukkit = Registry.BANNER_PATTERN.get(CraftNamespacedKey.fromMinecraft(nms.assetId()));
assertNotNull(bukkit, "No Bukkit banner pattern for " + nms + " " + nms);
@@ -25,10 +25,10 @@ public class PatternTypeTest {
@Test
public void testToNMS() {
IRegistry<EnumBannerPatternType> registry = MinecraftServer.getDefaultRegistryAccess().lookupOrThrow(Registries.BANNER_PATTERN);
net.minecraft.core.Registry<BannerPattern> registry = MinecraftServer.getDefaultRegistryAccess().lookupOrThrow(Registries.BANNER_PATTERN);
for (PatternType bukkit : PatternType.values()) {
EnumBannerPatternType found = null;
for (EnumBannerPatternType nms : registry) {
BannerPattern found = null;
for (BannerPattern nms : registry) {
NamespacedKey nmsKey = CraftNamespacedKey.fromMinecraft(registry.getKey(nms));
if (bukkit.getKey().equals(nmsKey)) {
found = nms;

View File

@@ -10,7 +10,7 @@ public class HeightMapTest {
@Test
public void heightMapConversionFromNMSToBukkitShouldNotThrowExceptio() {
for (net.minecraft.world.level.levelgen.HeightMap.Type nmsHeightMapType : net.minecraft.world.level.levelgen.HeightMap.Type.values()) {
for (net.minecraft.world.level.levelgen.Heightmap.Types nmsHeightMapType : net.minecraft.world.level.levelgen.Heightmap.Types.values()) {
assertNotNull(CraftHeightMap.fromNMS(nmsHeightMapType), "fromNMS");
}
}

View File

@@ -1,11 +1,12 @@
package org.bukkit.craftbukkit.block;
import static org.junit.jupiter.api.Assertions.*;
import net.minecraft.core.BlockPosition;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.ITileEntity;
import net.minecraft.world.level.block.entity.TileEntity;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import org.bukkit.Material;
import org.bukkit.support.environment.AllFeatures;
import org.junit.jupiter.api.Test;
@@ -20,12 +21,12 @@ public class BlockStateTest {
Class<?> blockStateType = CraftBlockStates.getBlockStateType(material);
boolean isCraftBlockEntityState = CraftBlockEntityState.class.isAssignableFrom(blockStateType);
if (block instanceof ITileEntity) {
if (block instanceof EntityBlock) {
assertTrue(isCraftBlockEntityState, material + " has BlockState of type " + blockStateType.getName() + ", but expected subtype of CraftBlockEntityState");
// check tile entity type
TileEntity tileEntity = ((ITileEntity) block).newBlockEntity(BlockPosition.ZERO, block.defaultBlockState());
TileEntity materialTileEntity = CraftBlockStates.createNewTileEntity(material);
BlockEntity tileEntity = ((EntityBlock) block).newBlockEntity(BlockPos.ZERO, block.defaultBlockState());
BlockEntity materialTileEntity = CraftBlockStates.createNewTileEntity(material);
if (tileEntity == null) {
if (CraftBlockStates.isTileEntityOptional(material)) {

View File

@@ -132,11 +132,11 @@ public class EntityTypesTest {
private static JarFile jarFile = null;
public static Stream<Arguments> excludedData() {
return EXCLUDE.stream().map(Arguments::arguments);
return EntityTypesTest.EXCLUDE.stream().map(Arguments::arguments);
}
public static Stream<Arguments> data() {
return jarFile
return EntityTypesTest.jarFile
.stream()
.map(ZipEntry::getName)
.filter(name -> name.endsWith(".class"))
@@ -151,13 +151,13 @@ public class EntityTypesTest {
}
})
.filter(Entity.class::isAssignableFrom)
.filter(clazz -> !EXCLUDE.contains(clazz))
.filter(clazz -> !EntityTypesTest.EXCLUDE.contains(clazz))
.map(Arguments::arguments);
}
@BeforeAll
public static void beforeAll() throws IOException {
jarFile = new JarFile(new File(BUKKIT_CLASSES));
EntityTypesTest.jarFile = new JarFile(new File(EntityTypesTest.BUKKIT_CLASSES));
}
@ParameterizedTest
@@ -183,8 +183,8 @@ public class EntityTypesTest {
@AfterAll
public static void clear() throws IOException {
if (jarFile != null) {
jarFile.close();
if (EntityTypesTest.jarFile != null) {
EntityTypesTest.jarFile.close();
}
}
}

View File

@@ -37,54 +37,54 @@ public class ChunkDataTest {
@Test
public void testMinHeight() {
OldCraftChunkData data = new OldCraftChunkData(-128, 128, RegistryHelper.getBiomes());
assertTrue(testSetBlock(data, 0, -256, 0, RED_WOOL, AIR), "Could not set block below min height");
assertTrue(testSetBlock(data, 0, -64, 0, RED_WOOL, RED_WOOL), "Could set block above min height");
assertTrue(this.testSetBlock(data, 0, -256, 0, ChunkDataTest.RED_WOOL, ChunkDataTest.AIR), "Could not set block below min height");
assertTrue(this.testSetBlock(data, 0, -64, 0, ChunkDataTest.RED_WOOL, ChunkDataTest.RED_WOOL), "Could set block above min height");
}
@Test
public void testMaxHeight() {
OldCraftChunkData data = new OldCraftChunkData(0, 128, RegistryHelper.getBiomes());
assertTrue(testSetBlock(data, 0, 128, 0, RED_WOOL, AIR), "Could not set block above max height");
assertTrue(testSetBlock(data, 0, 127, 0, RED_WOOL, RED_WOOL), "Could set block below max height");
assertTrue(this.testSetBlock(data, 0, 128, 0, ChunkDataTest.RED_WOOL, ChunkDataTest.AIR), "Could not set block above max height");
assertTrue(this.testSetBlock(data, 0, 127, 0, ChunkDataTest.RED_WOOL, ChunkDataTest.RED_WOOL), "Could set block below max height");
}
@Test
public void testBoundsCheckingSingle() {
OldCraftChunkData data = new OldCraftChunkData(0, 256, RegistryHelper.getBiomes());
assertTrue(testSetBlock(data, 0, 0, 0, RED_WOOL, RED_WOOL), "Can set block inside chunk bounds");
assertTrue(testSetBlock(data, 15, 255, 15, RED_WOOL, RED_WOOL), "Can set block inside chunk bounds");
assertTrue(testSetBlock(data, -1, 0, 0, RED_WOOL, AIR), "Can no set block outside chunk bounds");
assertTrue(testSetBlock(data, 0, -1, 0, RED_WOOL, AIR), "Can no set block outside chunk bounds");
assertTrue(testSetBlock(data, 0, 0, -1, RED_WOOL, AIR), "Can no set block outside chunk bounds");
assertTrue(testSetBlock(data, 16, 0, 0, RED_WOOL, AIR), "Can no set block outside chunk bounds");
assertTrue(testSetBlock(data, 0, 256, 0, RED_WOOL, AIR), "Can no set block outside chunk bounds");
assertTrue(testSetBlock(data, 0, 0, 16, RED_WOOL, AIR), "Can no set block outside chunk bounds");
assertTrue(this.testSetBlock(data, 0, 0, 0, ChunkDataTest.RED_WOOL, ChunkDataTest.RED_WOOL), "Can set block inside chunk bounds");
assertTrue(this.testSetBlock(data, 15, 255, 15, ChunkDataTest.RED_WOOL, ChunkDataTest.RED_WOOL), "Can set block inside chunk bounds");
assertTrue(this.testSetBlock(data, -1, 0, 0, ChunkDataTest.RED_WOOL, ChunkDataTest.AIR), "Can no set block outside chunk bounds");
assertTrue(this.testSetBlock(data, 0, -1, 0, ChunkDataTest.RED_WOOL, ChunkDataTest.AIR), "Can no set block outside chunk bounds");
assertTrue(this.testSetBlock(data, 0, 0, -1, ChunkDataTest.RED_WOOL, ChunkDataTest.AIR), "Can no set block outside chunk bounds");
assertTrue(this.testSetBlock(data, 16, 0, 0, ChunkDataTest.RED_WOOL, ChunkDataTest.AIR), "Can no set block outside chunk bounds");
assertTrue(this.testSetBlock(data, 0, 256, 0, ChunkDataTest.RED_WOOL, ChunkDataTest.AIR), "Can no set block outside chunk bounds");
assertTrue(this.testSetBlock(data, 0, 0, 16, ChunkDataTest.RED_WOOL, ChunkDataTest.AIR), "Can no set block outside chunk bounds");
}
@Test
public void testSetRegion() {
OldCraftChunkData data = new OldCraftChunkData(0, 256, RegistryHelper.getBiomes());
testSetRegion(data, -100, 0, -100, 0, 256, 0, RED_WOOL); // exclusively outside
testSetRegion(data, 16, 256, 16, 0, 0, 0, RED_WOOL); // minimum >= maximum
testSetRegion(data, 0, 0, 0, 0, 0, 0, RED_WOOL); // minimum == maximum
testSetRegion(data, 0, 0, 0, 16, 16, 16, RED_WOOL); // Whole Chunk Section
data.setRegion(0, 0, 0, 16, 256, 16, AIR);
testSetRegion(data, 0, 8, 0, 16, 24, 16, RED_WOOL); // Start middle of this section, end middle of next
data.setRegion(0, 0, 0, 16, 256, 16, AIR);
testSetRegion(data, 0, 4, 0, 16, 12, 16, RED_WOOL); // Start in this section, end in this section
data.setRegion(0, 0, 0, 16, 256, 16, AIR);
testSetRegion(data, 0, 0, 0, 16, 16, 1, RED_WOOL); // Whole Chunk Section
data.setRegion(0, 0, 0, 16, 256, 16, AIR);
testSetRegion(data, 0, 8, 0, 16, 24, 1, RED_WOOL); // Start middle of this section, end middle of next
data.setRegion(0, 0, 0, 16, 256, 16, AIR);
testSetRegion(data, 0, 4, 0, 16, 12, 1, RED_WOOL); // Start in this section, end in this section
data.setRegion(0, 0, 0, 16, 256, 16, AIR);
testSetRegion(data, 0, 0, 0, 1, 16, 1, RED_WOOL); // Whole Chunk Section
data.setRegion(0, 0, 0, 16, 256, 16, AIR);
testSetRegion(data, 0, 8, 0, 1, 24, 1, RED_WOOL); // Start middle of this section, end middle of next
data.setRegion(0, 0, 0, 16, 256, 16, AIR);
testSetRegion(data, 0, 4, 0, 1, 12, 1, RED_WOOL); // Start in this section, end in this section
data.setRegion(0, 0, 0, 16, 256, 16, AIR);
testSetRegion(data, 0, 0, 0, 1, 1, 1, RED_WOOL); // Set single block.
this.testSetRegion(data, -100, 0, -100, 0, 256, 0, ChunkDataTest.RED_WOOL); // exclusively outside
this.testSetRegion(data, 16, 256, 16, 0, 0, 0, ChunkDataTest.RED_WOOL); // minimum >= maximum
this.testSetRegion(data, 0, 0, 0, 0, 0, 0, ChunkDataTest.RED_WOOL); // minimum == maximum
this.testSetRegion(data, 0, 0, 0, 16, 16, 16, ChunkDataTest.RED_WOOL); // Whole Chunk Section
data.setRegion(0, 0, 0, 16, 256, 16, ChunkDataTest.AIR);
this.testSetRegion(data, 0, 8, 0, 16, 24, 16, ChunkDataTest.RED_WOOL); // Start middle of this section, end middle of next
data.setRegion(0, 0, 0, 16, 256, 16, ChunkDataTest.AIR);
this.testSetRegion(data, 0, 4, 0, 16, 12, 16, ChunkDataTest.RED_WOOL); // Start in this section, end in this section
data.setRegion(0, 0, 0, 16, 256, 16, ChunkDataTest.AIR);
this.testSetRegion(data, 0, 0, 0, 16, 16, 1, ChunkDataTest.RED_WOOL); // Whole Chunk Section
data.setRegion(0, 0, 0, 16, 256, 16, ChunkDataTest.AIR);
this.testSetRegion(data, 0, 8, 0, 16, 24, 1, ChunkDataTest.RED_WOOL); // Start middle of this section, end middle of next
data.setRegion(0, 0, 0, 16, 256, 16, ChunkDataTest.AIR);
this.testSetRegion(data, 0, 4, 0, 16, 12, 1, ChunkDataTest.RED_WOOL); // Start in this section, end in this section
data.setRegion(0, 0, 0, 16, 256, 16, ChunkDataTest.AIR);
this.testSetRegion(data, 0, 0, 0, 1, 16, 1, ChunkDataTest.RED_WOOL); // Whole Chunk Section
data.setRegion(0, 0, 0, 16, 256, 16, ChunkDataTest.AIR);
this.testSetRegion(data, 0, 8, 0, 1, 24, 1, ChunkDataTest.RED_WOOL); // Start middle of this section, end middle of next
data.setRegion(0, 0, 0, 16, 256, 16, ChunkDataTest.AIR);
this.testSetRegion(data, 0, 4, 0, 1, 12, 1, ChunkDataTest.RED_WOOL); // Start in this section, end in this section
data.setRegion(0, 0, 0, 16, 256, 16, ChunkDataTest.AIR);
this.testSetRegion(data, 0, 0, 0, 1, 1, 1, ChunkDataTest.RED_WOOL); // Set single block.
}
}

View File

@@ -24,7 +24,7 @@ public class CompositeSerialization {
@Test
public void testSaveRestoreCompositeList() throws InvalidConfigurationException {
YamlConfiguration out = getConfig();
YamlConfiguration out = this.getConfig();
List<ItemStack> stacks = new ArrayList<ItemStack>();
stacks.add(new ItemStack(Material.STONE));

View File

@@ -27,7 +27,7 @@ public class DeprecatedItemMetaCustomValueTest {
@BeforeAll
public static void setup() {
VALID_KEY = new NamespacedKey("test", "validkey");
DeprecatedItemMetaCustomValueTest.VALID_KEY = new NamespacedKey("test", "validkey");
}
/*
@@ -35,7 +35,7 @@ public class DeprecatedItemMetaCustomValueTest {
*/
@Test
public void testSetNoAdapter() {
ItemMeta itemMeta = createNewItemMeta();
ItemMeta itemMeta = this.createNewItemMeta();
assertThrows(IllegalArgumentException.class, () -> itemMeta.getCustomTagContainer().setCustomTag(VALID_KEY, new PrimitiveTagType<>(boolean.class), true));
}
@@ -44,8 +44,8 @@ public class DeprecatedItemMetaCustomValueTest {
*/
@Test
public void testHasNoAdapter() {
ItemMeta itemMeta = createNewItemMeta();
itemMeta.getCustomTagContainer().setCustomTag(VALID_KEY, ItemTagType.INTEGER, 1); // We gotta set this so we at least try to compare it
ItemMeta itemMeta = this.createNewItemMeta();
itemMeta.getCustomTagContainer().setCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, ItemTagType.INTEGER, 1); // We gotta set this so we at least try to compare it
assertThrows(IllegalArgumentException.class, () -> itemMeta.getCustomTagContainer().hasCustomTag(VALID_KEY, new PrimitiveTagType<>(boolean.class)));
}
@@ -54,15 +54,15 @@ public class DeprecatedItemMetaCustomValueTest {
*/
@Test
public void testGetNoAdapter() {
ItemMeta itemMeta = createNewItemMeta();
itemMeta.getCustomTagContainer().setCustomTag(VALID_KEY, ItemTagType.INTEGER, 1); //We gotta set this so we at least try to compare it
ItemMeta itemMeta = this.createNewItemMeta();
itemMeta.getCustomTagContainer().setCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, ItemTagType.INTEGER, 1); //We gotta set this so we at least try to compare it
assertThrows(IllegalArgumentException.class, () -> itemMeta.getCustomTagContainer().getCustomTag(VALID_KEY, new PrimitiveTagType<>(boolean.class)));
}
@Test
public void testGetWrongType() {
ItemMeta itemMeta = createNewItemMeta();
itemMeta.getCustomTagContainer().setCustomTag(VALID_KEY, ItemTagType.INTEGER, 1);
ItemMeta itemMeta = this.createNewItemMeta();
itemMeta.getCustomTagContainer().setCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, ItemTagType.INTEGER, 1);
assertThrows(IllegalArgumentException.class, () -> itemMeta.getCustomTagContainer().getCustomTag(VALID_KEY, ItemTagType.STRING));
}
@@ -71,7 +71,7 @@ public class DeprecatedItemMetaCustomValueTest {
NamespacedKey namespacedKeyA = new NamespacedKey("plugin-a", "damage");
NamespacedKey namespacedKeyB = new NamespacedKey("plugin-b", "damage");
ItemMeta meta = createNewItemMeta();
ItemMeta meta = this.createNewItemMeta();
meta.getCustomTagContainer().setCustomTag(namespacedKeyA, ItemTagType.LONG, 15L);
meta.getCustomTagContainer().setCustomTag(namespacedKeyB, ItemTagType.LONG, 160L);
@@ -92,7 +92,7 @@ public class DeprecatedItemMetaCustomValueTest {
*/
@Test
public void testNBTTagStoring() {
CraftMetaItem itemMeta = createComplexItemMeta();
CraftMetaItem itemMeta = this.createComplexItemMeta();
CraftMetaItem.Applicator compound = new CraftMetaItem.Applicator();
itemMeta.applyToItem(compound);
@@ -102,7 +102,7 @@ public class DeprecatedItemMetaCustomValueTest {
@Test
public void testMapStoring() {
CraftMetaItem itemMeta = createComplexItemMeta();
CraftMetaItem itemMeta = this.createComplexItemMeta();
Map<String, Object> serialize = itemMeta.serialize();
assertEquals(itemMeta, new CraftMetaItem(serialize));
@@ -111,7 +111,7 @@ public class DeprecatedItemMetaCustomValueTest {
@Test
public void testYAMLStoring() {
ItemStack stack = new ItemStack(Material.DIAMOND);
CraftMetaItem meta = createComplexItemMeta();
CraftMetaItem meta = this.createComplexItemMeta();
stack.setItemMeta(meta);
YamlConfiguration configuration = new YamlConfiguration();
@@ -127,10 +127,10 @@ public class DeprecatedItemMetaCustomValueTest {
@Test
public void testCorrectType() {
ItemStack stack = new ItemStack(Material.DIAMOND);
CraftMetaItem meta = createComplexItemMeta();
CraftMetaItem meta = this.createComplexItemMeta();
meta.getCustomTagContainer().setCustomTag(requestKey("int"), ItemTagType.STRING, "1");
meta.getCustomTagContainer().setCustomTag(requestKey("double"), ItemTagType.STRING, "1.33");
meta.getCustomTagContainer().setCustomTag(this.requestKey("int"), ItemTagType.STRING, "1");
meta.getCustomTagContainer().setCustomTag(this.requestKey("double"), ItemTagType.STRING, "1.33");
stack.setItemMeta(meta);
YamlConfiguration configuration = new YamlConfiguration();
@@ -140,28 +140,28 @@ public class DeprecatedItemMetaCustomValueTest {
YamlConfiguration loadedConfig = YamlConfiguration.loadConfiguration(new StringReader(configValue));
ItemStack newStack = loadedConfig.getSerializable("testpath", ItemStack.class);
assertTrue(newStack.getItemMeta().getCustomTagContainer().hasCustomTag(requestKey("int"), ItemTagType.STRING));
assertEquals(newStack.getItemMeta().getCustomTagContainer().getCustomTag(requestKey("int"), ItemTagType.STRING), "1");
assertTrue(newStack.getItemMeta().getCustomTagContainer().hasCustomTag(this.requestKey("int"), ItemTagType.STRING));
assertEquals(newStack.getItemMeta().getCustomTagContainer().getCustomTag(this.requestKey("int"), ItemTagType.STRING), "1");
assertTrue(newStack.getItemMeta().getCustomTagContainer().hasCustomTag(requestKey("double"), ItemTagType.STRING));
assertEquals(newStack.getItemMeta().getCustomTagContainer().getCustomTag(requestKey("double"), ItemTagType.STRING), "1.33");
assertTrue(newStack.getItemMeta().getCustomTagContainer().hasCustomTag(this.requestKey("double"), ItemTagType.STRING));
assertEquals(newStack.getItemMeta().getCustomTagContainer().getCustomTag(this.requestKey("double"), ItemTagType.STRING), "1.33");
}
private CraftMetaItem createComplexItemMeta() {
CraftMetaItem itemMeta = (CraftMetaItem) createNewItemMeta();
CraftMetaItem itemMeta = (CraftMetaItem) this.createNewItemMeta();
itemMeta.setDisplayName("Item Display Name");
itemMeta.getCustomTagContainer().setCustomTag(requestKey("custom-long"), ItemTagType.LONG, 4L); //Add random primitive values
itemMeta.getCustomTagContainer().setCustomTag(requestKey("custom-byte-array"), ItemTagType.BYTE_ARRAY, new byte[]{
itemMeta.getCustomTagContainer().setCustomTag(this.requestKey("custom-long"), ItemTagType.LONG, 4L); //Add random primitive values
itemMeta.getCustomTagContainer().setCustomTag(this.requestKey("custom-byte-array"), ItemTagType.BYTE_ARRAY, new byte[]{
0, 1, 2, 10
});
itemMeta.getCustomTagContainer().setCustomTag(requestKey("custom-string"), ItemTagType.STRING, "Hello there world");
itemMeta.getCustomTagContainer().setCustomTag(requestKey("custom-int"), ItemTagType.INTEGER, 3);
itemMeta.getCustomTagContainer().setCustomTag(requestKey("custom-double"), ItemTagType.DOUBLE, 3.123);
itemMeta.getCustomTagContainer().setCustomTag(this.requestKey("custom-string"), ItemTagType.STRING, "Hello there world");
itemMeta.getCustomTagContainer().setCustomTag(this.requestKey("custom-int"), ItemTagType.INTEGER, 3);
itemMeta.getCustomTagContainer().setCustomTag(this.requestKey("custom-double"), ItemTagType.DOUBLE, 3.123);
CustomItemTagContainer innerContainer = itemMeta.getCustomTagContainer().getAdapterContext().newTagContainer(); //Add a inner container
innerContainer.setCustomTag(VALID_KEY, ItemTagType.LONG, 5L);
itemMeta.getCustomTagContainer().setCustomTag(requestKey("custom-inner-compound"), ItemTagType.TAG_CONTAINER, innerContainer);
innerContainer.setCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, ItemTagType.LONG, 5L);
itemMeta.getCustomTagContainer().setCustomTag(this.requestKey("custom-inner-compound"), ItemTagType.TAG_CONTAINER, innerContainer);
return itemMeta;
}
@@ -170,43 +170,43 @@ public class DeprecatedItemMetaCustomValueTest {
*/
@Test
public void storeUUIDOnItemTest() {
ItemMeta itemMeta = createNewItemMeta();
ItemMeta itemMeta = this.createNewItemMeta();
UUIDItemTagType uuidItemTagType = new UUIDItemTagType();
UUID uuid = UUID.fromString("434eea72-22a6-4c61-b5ef-945874a5c478");
itemMeta.getCustomTagContainer().setCustomTag(VALID_KEY, uuidItemTagType, uuid);
assertTrue(itemMeta.getCustomTagContainer().hasCustomTag(VALID_KEY, uuidItemTagType));
assertEquals(uuid, itemMeta.getCustomTagContainer().getCustomTag(VALID_KEY, uuidItemTagType));
itemMeta.getCustomTagContainer().setCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, uuidItemTagType, uuid);
assertTrue(itemMeta.getCustomTagContainer().hasCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, uuidItemTagType));
assertEquals(uuid, itemMeta.getCustomTagContainer().getCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, uuidItemTagType));
}
@Test
public void encapsulatedContainers() {
NamespacedKey innerKey = new NamespacedKey("plugin-a", "inner");
ItemMeta meta = createNewItemMeta();
ItemMeta meta = this.createNewItemMeta();
ItemTagAdapterContext context = meta.getCustomTagContainer().getAdapterContext();
CustomItemTagContainer thirdContainer = context.newTagContainer();
thirdContainer.setCustomTag(VALID_KEY, ItemTagType.LONG, 3L);
thirdContainer.setCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, ItemTagType.LONG, 3L);
CustomItemTagContainer secondContainer = context.newTagContainer();
secondContainer.setCustomTag(VALID_KEY, ItemTagType.LONG, 2L);
secondContainer.setCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, ItemTagType.LONG, 2L);
secondContainer.setCustomTag(innerKey, ItemTagType.TAG_CONTAINER, thirdContainer);
meta.getCustomTagContainer().setCustomTag(VALID_KEY, ItemTagType.LONG, 1L);
meta.getCustomTagContainer().setCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, ItemTagType.LONG, 1L);
meta.getCustomTagContainer().setCustomTag(innerKey, ItemTagType.TAG_CONTAINER, secondContainer);
assertEquals(3L, meta.getCustomTagContainer()
.getCustomTag(innerKey, ItemTagType.TAG_CONTAINER)
.getCustomTag(innerKey, ItemTagType.TAG_CONTAINER)
.getCustomTag(VALID_KEY, ItemTagType.LONG).longValue());
.getCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, ItemTagType.LONG).longValue());
assertEquals(2L, meta.getCustomTagContainer()
.getCustomTag(innerKey, ItemTagType.TAG_CONTAINER)
.getCustomTag(VALID_KEY, ItemTagType.LONG).longValue());
.getCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, ItemTagType.LONG).longValue());
assertEquals(1L, meta.getCustomTagContainer()
.getCustomTag(VALID_KEY, ItemTagType.LONG).longValue());
.getCustomTag(DeprecatedItemMetaCustomValueTest.VALID_KEY, ItemTagType.LONG).longValue());
}
class UUIDItemTagType implements ItemTagType<byte[], UUID> {
@@ -240,24 +240,24 @@ public class DeprecatedItemMetaCustomValueTest {
@Test
public void testPrimitiveCustomTags() {
ItemMeta itemMeta = createNewItemMeta();
ItemMeta itemMeta = this.createNewItemMeta();
testPrimitiveCustomTag(itemMeta, ItemTagType.BYTE, (byte) 1);
testPrimitiveCustomTag(itemMeta, ItemTagType.SHORT, (short) 1);
testPrimitiveCustomTag(itemMeta, ItemTagType.INTEGER, 1);
testPrimitiveCustomTag(itemMeta, ItemTagType.LONG, 1L);
testPrimitiveCustomTag(itemMeta, ItemTagType.FLOAT, 1.34F);
testPrimitiveCustomTag(itemMeta, ItemTagType.DOUBLE, 151.123);
this.testPrimitiveCustomTag(itemMeta, ItemTagType.BYTE, (byte) 1);
this.testPrimitiveCustomTag(itemMeta, ItemTagType.SHORT, (short) 1);
this.testPrimitiveCustomTag(itemMeta, ItemTagType.INTEGER, 1);
this.testPrimitiveCustomTag(itemMeta, ItemTagType.LONG, 1L);
this.testPrimitiveCustomTag(itemMeta, ItemTagType.FLOAT, 1.34F);
this.testPrimitiveCustomTag(itemMeta, ItemTagType.DOUBLE, 151.123);
testPrimitiveCustomTag(itemMeta, ItemTagType.STRING, "test");
this.testPrimitiveCustomTag(itemMeta, ItemTagType.STRING, "test");
testPrimitiveCustomTag(itemMeta, ItemTagType.BYTE_ARRAY, new byte[]{
this.testPrimitiveCustomTag(itemMeta, ItemTagType.BYTE_ARRAY, new byte[]{
1, 4, 2, Byte.MAX_VALUE
});
testPrimitiveCustomTag(itemMeta, ItemTagType.INTEGER_ARRAY, new int[]{
this.testPrimitiveCustomTag(itemMeta, ItemTagType.INTEGER_ARRAY, new int[]{
1, 4, 2, Integer.MAX_VALUE
});
testPrimitiveCustomTag(itemMeta, ItemTagType.LONG_ARRAY, new long[]{
this.testPrimitiveCustomTag(itemMeta, ItemTagType.LONG_ARRAY, new long[]{
1L, 4L, 2L, Long.MAX_VALUE
});
}
@@ -293,12 +293,12 @@ public class DeprecatedItemMetaCustomValueTest {
@Override
public Class<T> getPrimitiveType() {
return primitiveType;
return this.primitiveType;
}
@Override
public Class<T> getComplexType() {
return primitiveType;
return this.primitiveType;
}
@Override

View File

@@ -39,14 +39,14 @@ public class FactoryItemMaterialTest {
static String name(Enum<?> from, Enum<?> to) {
if (from.getClass() == to.getClass()) {
return buffer.delete(0, Integer.MAX_VALUE).append(from.getClass().getName()).append(' ').append(from.name()).append(" to ").append(to.name()).toString();
return FactoryItemMaterialTest.buffer.delete(0, Integer.MAX_VALUE).append(from.getClass().getName()).append(' ').append(from.name()).append(" to ").append(to.name()).toString();
}
return buffer.delete(0, Integer.MAX_VALUE).append(from.getClass().getName()).append('(').append(from.name()).append(") to ").append(to.getClass().getName()).append('(').append(to.name()).append(')').toString();
return FactoryItemMaterialTest.buffer.delete(0, Integer.MAX_VALUE).append(from.getClass().getName()).append('(').append(from.name()).append(") to ").append(to.getClass().getName()).append('(').append(to.name()).append(')').toString();
}
public static Stream<Arguments> data() {
List<Arguments> list = new ArrayList<>();
for (Material material : materials) {
for (Material material : FactoryItemMaterialTest.materials) {
list.add(Arguments.of(material));
}
return list.stream();
@@ -57,27 +57,27 @@ public class FactoryItemMaterialTest {
public void itemStack(Material material) {
ItemStack bukkitStack = new ItemStack(material);
CraftItemStack craftStack = CraftItemStack.asCraftCopy(bukkitStack);
ItemMeta meta = factory.getItemMeta(material);
ItemMeta meta = FactoryItemMaterialTest.factory.getItemMeta(material);
if (meta == null) {
assertThat(material, is(Material.AIR));
} else {
assertTrue(factory.isApplicable(meta, bukkitStack));
assertTrue(factory.isApplicable(meta, craftStack));
assertTrue(FactoryItemMaterialTest.factory.isApplicable(meta, bukkitStack));
assertTrue(FactoryItemMaterialTest.factory.isApplicable(meta, craftStack));
}
}
@ParameterizedTest
@MethodSource("data")
public void generalCase(Material material) {
CraftMetaItem meta = (CraftMetaItem) factory.getItemMeta(material);
CraftMetaItem meta = (CraftMetaItem) FactoryItemMaterialTest.factory.getItemMeta(material);
if (meta == null) {
assertThat(material, is(Material.AIR));
} else {
assertTrue(factory.isApplicable(meta, material));
assertTrue(FactoryItemMaterialTest.factory.isApplicable(meta, material));
assertTrue(meta.applicableTo(material));
meta = meta.clone();
assertTrue(factory.isApplicable(meta, material));
assertTrue(FactoryItemMaterialTest.factory.isApplicable(meta, material));
assertTrue(meta.applicableTo(material));
}
}
@@ -85,27 +85,27 @@ public class FactoryItemMaterialTest {
@ParameterizedTest
@MethodSource("data")
public void asMetaFor(Material material) {
final CraftMetaItem baseMeta = (CraftMetaItem) factory.getItemMeta(material);
final CraftMetaItem baseMeta = (CraftMetaItem) FactoryItemMaterialTest.factory.getItemMeta(material);
if (baseMeta == null) {
assertThat(material, is(Material.AIR));
return;
}
for (Material other : materials) {
for (Material other : FactoryItemMaterialTest.materials) {
final ItemStack bukkitStack = new ItemStack(other);
final CraftItemStack craftStack = CraftItemStack.asCraftCopy(bukkitStack);
final CraftMetaItem otherMeta = (CraftMetaItem) factory.asMetaFor(baseMeta, other);
final CraftMetaItem otherMeta = (CraftMetaItem) FactoryItemMaterialTest.factory.asMetaFor(baseMeta, other);
final String testName = name(material, other);
final String testName = FactoryItemMaterialTest.name(material, other);
if (otherMeta == null) {
assertThat(other, is(Material.AIR), testName);
continue;
}
assertTrue(factory.isApplicable(otherMeta, craftStack), testName);
assertTrue(factory.isApplicable(otherMeta, bukkitStack), testName);
assertTrue(factory.isApplicable(otherMeta, other), testName);
assertTrue(FactoryItemMaterialTest.factory.isApplicable(otherMeta, craftStack), testName);
assertTrue(FactoryItemMaterialTest.factory.isApplicable(otherMeta, bukkitStack), testName);
assertTrue(FactoryItemMaterialTest.factory.isApplicable(otherMeta, other), testName);
assertTrue(otherMeta.applicableTo(other), testName);
}
}
@@ -116,7 +116,7 @@ public class FactoryItemMaterialTest {
if (material == Material.AIR) {
return;
}
final CraftMetaItem baseMeta = (CraftMetaItem) factory.getItemMeta(material);
final CraftMetaItem baseMeta = (CraftMetaItem) FactoryItemMaterialTest.factory.getItemMeta(material);
final CraftMetaItem baseMetaClone = baseMeta.clone();
final ItemStack baseMetaStack = new ItemStack(material);
@@ -124,29 +124,29 @@ public class FactoryItemMaterialTest {
assertThat(baseMeta, is(not(sameInstance(baseMetaStack.getItemMeta()))));
assertTrue(factory.equals(baseMeta, null));
assertTrue(factory.equals(null, baseMeta));
assertTrue(FactoryItemMaterialTest.factory.equals(baseMeta, null));
assertTrue(FactoryItemMaterialTest.factory.equals(null, baseMeta));
assertTrue(factory.equals(baseMeta, baseMetaClone));
assertTrue(factory.equals(baseMetaClone, baseMeta));
assertTrue(FactoryItemMaterialTest.factory.equals(baseMeta, baseMetaClone));
assertTrue(FactoryItemMaterialTest.factory.equals(baseMetaClone, baseMeta));
assertThat(baseMeta, is(not(sameInstance(baseMetaClone))));
assertThat(baseMeta, is(baseMetaClone));
assertThat(baseMetaClone, is(baseMeta));
for (Material other : materials) {
final String testName = name(material, other);
for (Material other : FactoryItemMaterialTest.materials) {
final String testName = FactoryItemMaterialTest.name(material, other);
final CraftMetaItem otherMeta = (CraftMetaItem) factory.asMetaFor(baseMetaClone, other);
final CraftMetaItem otherMeta = (CraftMetaItem) FactoryItemMaterialTest.factory.asMetaFor(baseMetaClone, other);
if (otherMeta == null) {
assertThat(other, is(Material.AIR), testName);
continue;
}
assertTrue(factory.equals(baseMeta, otherMeta), testName);
assertTrue(factory.equals(otherMeta, baseMeta), testName);
assertTrue(FactoryItemMaterialTest.factory.equals(baseMeta, otherMeta), testName);
assertTrue(FactoryItemMaterialTest.factory.equals(otherMeta, baseMeta), testName);
assertThat(baseMeta, is(otherMeta), testName);
assertThat(otherMeta, is(baseMeta), testName);

View File

@@ -24,15 +24,15 @@ public class ItemMetaImplementationOverrideTest {
List<Class<? extends CraftMetaItem>> classes = new ArrayList<Class<? extends CraftMetaItem>>();
for (Material material : ItemStackTest.COMPOUND_MATERIALS) {
Class<? extends CraftMetaItem> clazz = CraftItemFactory.instance().getItemMeta(material).getClass().asSubclass(parent);
if (clazz != parent) {
Class<? extends CraftMetaItem> clazz = CraftItemFactory.instance().getItemMeta(material).getClass().asSubclass(ItemMetaImplementationOverrideTest.parent);
if (clazz != ItemMetaImplementationOverrideTest.parent) {
classes.add(clazz);
}
}
List<Method> list = new ArrayList<Method>();
for (Method method: parent.getDeclaredMethods()) {
for (Method method: ItemMetaImplementationOverrideTest.parent.getDeclaredMethods()) {
if (method.isAnnotationPresent(Overridden.class)) {
list.add(method);
}

View File

@@ -8,12 +8,12 @@ import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemBlock;
import net.minecraft.world.item.ItemBlockWallable;
import net.minecraft.world.item.StandingAndWallBlockItem;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.ITileEntity;
import net.minecraft.world.level.block.EntityBlock;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.DyeColor;
@@ -91,8 +91,8 @@ public class ItemMetaTest {
@Test
public void testPowers() {
for (int i = 0; i <= MAX_FIREWORK_POWER; i++) {
FireworkMeta firework = newFireworkMeta();
for (int i = 0; i <= ItemMetaTest.MAX_FIREWORK_POWER; i++) {
FireworkMeta firework = ItemMetaTest.newFireworkMeta();
firework.setPower(i);
assertThat(firework.getPower(), is(i), String.valueOf(i));
}
@@ -162,11 +162,11 @@ public class ItemMetaTest {
List<Block> queue = new ArrayList<>();
for (Item item : BuiltInRegistries.ITEM) {
if (item instanceof ItemBlock) {
queue.add(((ItemBlock) item).getBlock());
if (item instanceof BlockItem) {
queue.add(((BlockItem) item).getBlock());
}
if (item instanceof ItemBlockWallable) {
queue.add(((ItemBlockWallable) item).wallBlock);
if (item instanceof StandingAndWallBlockItem) {
queue.add(((StandingAndWallBlockItem) item).wallBlock);
}
}
@@ -180,7 +180,7 @@ public class ItemMetaTest {
}
ItemMeta meta = stack.getItemMeta();
if (block instanceof ITileEntity) {
if (block instanceof EntityBlock) {
assertTrue(meta instanceof BlockStateMeta, stack + " has meta of type " + meta + " expected BlockStateMeta");
BlockStateMeta blockState = (BlockStateMeta) meta;
@@ -197,7 +197,7 @@ public class ItemMetaTest {
@Test
public void testSpawnEggsHasMeta() {
for (Item item : BuiltInRegistries.ITEM) {
if (item instanceof net.minecraft.world.item.ItemMonsterEgg) {
if (item instanceof net.minecraft.world.item.SpawnEggItem) {
Material material = CraftItemType.minecraftToBukkit(item);
CraftMetaItem baseMeta = (CraftMetaItem) Bukkit.getItemFactory().getItemMeta(material);
ItemMeta baseMetaItem = CraftItemStack.getItemMeta(item.getDefaultInstance());
@@ -363,7 +363,7 @@ public class ItemMetaTest {
new StackProvider(Material.ARMOR_STAND) {
@Override ItemStack operate(ItemStack cleanStack) {
final CraftMetaArmorStand meta = (CraftMetaArmorStand) cleanStack.getItemMeta();
meta.entityTag = new NBTTagCompound();
meta.entityTag = new CompoundTag();
meta.entityTag.putBoolean("Small", true);
cleanStack.setItemMeta(meta);
return cleanStack;
@@ -380,7 +380,7 @@ public class ItemMetaTest {
new StackProvider(Material.ITEM_FRAME) {
@Override ItemStack operate(ItemStack cleanStack) {
final CraftMetaEntityTag meta = ((CraftMetaEntityTag) cleanStack.getItemMeta());
meta.entityTag = new NBTTagCompound();
meta.entityTag = new CompoundTag();
meta.entityTag.putBoolean("Invisible", true);
cleanStack.setItemMeta(meta);
return cleanStack;
@@ -431,8 +431,8 @@ public class ItemMetaTest {
assertThat(providers, hasSize(ItemStackTest.COMPOUND_MATERIALS.length - 4/* Normal item meta, skulls, eggs and tile entities */), "Forgotten test?");
for (final StackProvider provider : providers) {
downCastTest(new BukkitWrapper(provider));
downCastTest(new CraftWrapper(provider));
this.downCastTest(new BukkitWrapper(provider));
this.downCastTest(new CraftWrapper(provider));
}
}
@@ -495,13 +495,13 @@ public class ItemMetaTest {
assertThat(provider.stack(), is(provider.stack()), name);
assertThat(provider.stack().isSimilar(provider.stack()), is(true), name);
downCastTest(name, provider.stack(), blank);
this.downCastTest(name, provider.stack(), blank);
blank.setItemMeta(blank.getItemMeta());
downCastTest(name, provider.stack(), blank);
this.downCastTest(name, provider.stack(), blank);
downCastTest(name, provider.stack(), craftBlank);
this.downCastTest(name, provider.stack(), craftBlank);
craftBlank.setItemMeta(craftBlank.getItemMeta());
downCastTest(name, provider.stack(), craftBlank);
this.downCastTest(name, provider.stack(), craftBlank);
}
private void downCastTest(final String name, final ItemStack stack, final ItemStack blank) {

View File

@@ -12,7 +12,7 @@ import org.junit.jupiter.params.provider.Arguments;
public class ItemStackBookTest extends ItemStackTest {
public static Stream<Arguments> data() {
return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.WRITTEN_BOOK, Material.WRITABLE_BOOK);
return StackProvider.compound(ItemStackBookTest.operators(), "%s %s", NAME_PARAMETER, Material.WRITTEN_BOOK, Material.WRITABLE_BOOK);
}
@SuppressWarnings("unchecked")

View File

@@ -13,7 +13,7 @@ import org.junit.jupiter.params.provider.Arguments;
public class ItemStackEnchantStorageTest extends ItemStackTest {
public static Stream<Arguments> data() {
return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.ENCHANTED_BOOK);
return StackProvider.compound(ItemStackEnchantStorageTest.operators(), "%s %s", NAME_PARAMETER, Material.ENCHANTED_BOOK);
}
@SuppressWarnings("unchecked")

View File

@@ -15,7 +15,7 @@ import org.junit.jupiter.params.provider.Arguments;
public class ItemStackFireworkChargeTest extends ItemStackTest {
public static Stream<Arguments> data() {
return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.FIREWORK_STAR);
return StackProvider.compound(ItemStackFireworkChargeTest.operators(), "%s %s", NAME_PARAMETER, Material.FIREWORK_STAR);
}
@SuppressWarnings("unchecked")

View File

@@ -15,7 +15,7 @@ import org.junit.jupiter.params.provider.Arguments;
public class ItemStackFireworkTest extends ItemStackTest {
public static Stream<Arguments> data() {
return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.FIREWORK_ROCKET);
return StackProvider.compound(ItemStackFireworkTest.operators(), "%s %s", NAME_PARAMETER, Material.FIREWORK_ROCKET);
}
@SuppressWarnings("unchecked")

View File

@@ -13,7 +13,7 @@ import org.junit.jupiter.params.provider.Arguments;
public class ItemStackLeatherTest extends ItemStackTest {
public static Stream<Arguments> data() {
return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.LEATHER_BOOTS, Material.LEATHER_CHESTPLATE, Material.LEATHER_HELMET, Material.LEATHER_LEGGINGS);
return StackProvider.compound(ItemStackLeatherTest.operators(), "%s %s", NAME_PARAMETER, Material.LEATHER_BOOTS, Material.LEATHER_CHESTPLATE, Material.LEATHER_HELMET, Material.LEATHER_LEGGINGS);
}
@SuppressWarnings("unchecked")

View File

@@ -13,7 +13,7 @@ import org.junit.jupiter.params.provider.Arguments;
public class ItemStackLoreEnchantmentTest extends ItemStackTest {
public static Stream<Arguments> data() {
return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, ItemStackTest.COMPOUND_MATERIALS);
return StackProvider.compound(ItemStackLoreEnchantmentTest.operators(), "%s %s", NAME_PARAMETER, ItemStackTest.COMPOUND_MATERIALS);
}
@SuppressWarnings("unchecked")

View File

@@ -12,7 +12,7 @@ import org.junit.jupiter.params.provider.Arguments;
public class ItemStackMapTest extends ItemStackTest {
public static Stream<Arguments> data() {
return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.FILLED_MAP);
return StackProvider.compound(ItemStackMapTest.operators(), "%s %s", NAME_PARAMETER, Material.FILLED_MAP);
}
@SuppressWarnings("unchecked")

View File

@@ -13,7 +13,7 @@ import org.junit.jupiter.params.provider.Arguments;
public class ItemStackPotionsTest extends ItemStackTest {
public static Stream<Arguments> data() {
return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.POTION);
return StackProvider.compound(ItemStackPotionsTest.operators(), "%s %s", NAME_PARAMETER, Material.POTION);
}
@SuppressWarnings("unchecked")

View File

@@ -12,7 +12,7 @@ import org.junit.jupiter.params.provider.Arguments;
public class ItemStackSkullTest extends ItemStackTest {
public static Stream<Arguments> data() {
return StackProvider.compound(operators(), "%s %s", NAME_PARAMETER, Material.PLAYER_HEAD);
return StackProvider.compound(ItemStackSkullTest.operators(), "%s %s", NAME_PARAMETER, Material.PLAYER_HEAD);
}
@SuppressWarnings("unchecked")

View File

@@ -39,11 +39,11 @@ public class ItemStackTest {
}
ItemStack bukkit() {
return operate(cleanStack(material, false));
return this.operate(StackProvider.cleanStack(this.material, false));
}
ItemStack craft() {
return operate(cleanStack(material, true));
return this.operate(StackProvider.cleanStack(this.material, true));
}
abstract ItemStack operate(ItemStack cleanStack);
@@ -55,7 +55,7 @@ public class ItemStackTest {
@Override
public String toString() {
return material.toString();
return this.material.toString();
}
/**
@@ -124,7 +124,7 @@ public class ItemStackTest {
@Override
public ItemStack operate(ItemStack cleanStack) {
for (Operator operator : operators) {
for (Operator operator : this.operators) {
operator.operate(cleanStack);
}
return cleanStack;
@@ -132,7 +132,7 @@ public class ItemStackTest {
@Override
public String toString() {
return Arrays.toString(operators);
return Arrays.toString(this.operators);
}
@@ -162,7 +162,7 @@ public class ItemStackTest {
for (final List<Object[]> primarySingleton : singletons) {
// Iterate over our singletons, to multiply the 'out' each time
for (final Object[] entry : out.toArray(EMPTY_ARRAY)) {
for (final Object[] entry : out.toArray(ItemStackTest.EMPTY_ARRAY)) {
// Iterate over a snapshot of 'out' to prevent CMEs / infinite iteration
final int len = entry.length;
for (final Object[] singleton : primarySingleton) {
@@ -196,7 +196,7 @@ public class ItemStackTest {
final RecursiveContainer methodParams = new RecursiveContainer(joiner, new Object[lists.length], nameParameter, new ArrayList<Object[]>(lists.length), new ArrayList<Object[]>(), lists);
recursivelyCompound(methodParams, 0);
CompoundOperator.recursivelyCompound(methodParams, 0);
methodParams.out.addAll(out);
return methodParams.out;
@@ -239,7 +239,7 @@ public class ItemStackTest {
for (final Object[] params : methodParams.lists[level]) {
stack.add(params);
recursivelyCompound(methodParams, level + 1);
CompoundOperator.recursivelyCompound(methodParams, level + 1);
stack.remove(marker);
}
}
@@ -259,12 +259,12 @@ public class ItemStackTest {
@Override
public ItemStack stack() {
return provider.craft();
return this.provider.craft();
}
@Override
public String toString() {
return "Craft " + provider;
return "Craft " + this.provider;
}
}
@@ -277,12 +277,12 @@ public class ItemStackTest {
@Override
public ItemStack stack() {
return provider.bukkit();
return this.provider.bukkit();
}
@Override
public String toString() {
return "Bukkit " + provider;
return "Bukkit " + this.provider;
}
}
@@ -327,7 +327,7 @@ public class ItemStackTest {
COMPOUND_MATERIALS = possibleMaterials.values().toArray(new Material[possibleMaterials.size()]);
}
@ParameterizedTest(name = "[{index}]:{" + NAME_PARAMETER + "}")
@ParameterizedTest(name = "[{index}]:{" + ItemStackTest.NAME_PARAMETER + "}")
@MethodSource({"data",
"org.bukkit.craftbukkit.inventory.ItemStackSkullTest#data",
"org.bukkit.craftbukkit.inventory.ItemStackPotionsTest#data",
@@ -341,11 +341,11 @@ public class ItemStackTest {
})
public void testBukkitInequality(StackProvider provider, StackProvider unequalProvider, String name) {
final StackWrapper bukkitWrapper = new CraftWrapper(provider);
testInequality(bukkitWrapper, new BukkitWrapper(unequalProvider));
testInequality(bukkitWrapper, new BukkitWrapper(new NoOpProvider(provider.material)));
ItemStackTest.testInequality(bukkitWrapper, new BukkitWrapper(unequalProvider));
ItemStackTest.testInequality(bukkitWrapper, new BukkitWrapper(new NoOpProvider(provider.material)));
}
@ParameterizedTest(name = "[{index}]:{" + NAME_PARAMETER + "}")
@ParameterizedTest(name = "[{index}]:{" + ItemStackTest.NAME_PARAMETER + "}")
@MethodSource({"data",
"org.bukkit.craftbukkit.inventory.ItemStackSkullTest#data",
"org.bukkit.craftbukkit.inventory.ItemStackPotionsTest#data",
@@ -359,11 +359,11 @@ public class ItemStackTest {
})
public void testCraftInequality(StackProvider provider, StackProvider unequalProvider, String name) {
final StackWrapper craftWrapper = new CraftWrapper(provider);
testInequality(craftWrapper, new CraftWrapper(unequalProvider));
testInequality(craftWrapper, new CraftWrapper(new NoOpProvider(provider.material)));
ItemStackTest.testInequality(craftWrapper, new CraftWrapper(unequalProvider));
ItemStackTest.testInequality(craftWrapper, new CraftWrapper(new NoOpProvider(provider.material)));
}
@ParameterizedTest(name = "[{index}]:{" + NAME_PARAMETER + "}")
@ParameterizedTest(name = "[{index}]:{" + ItemStackTest.NAME_PARAMETER + "}")
@MethodSource({"data",
"org.bukkit.craftbukkit.inventory.ItemStackSkullTest#data",
"org.bukkit.craftbukkit.inventory.ItemStackPotionsTest#data",
@@ -377,12 +377,12 @@ public class ItemStackTest {
})
public void testMixedInequality(StackProvider provider, StackProvider unequalProvider, String name) {
final StackWrapper craftWrapper = new CraftWrapper(provider);
testInequality(craftWrapper, new BukkitWrapper(unequalProvider));
testInequality(craftWrapper, new BukkitWrapper(new NoOpProvider(provider.material)));
ItemStackTest.testInequality(craftWrapper, new BukkitWrapper(unequalProvider));
ItemStackTest.testInequality(craftWrapper, new BukkitWrapper(new NoOpProvider(provider.material)));
final StackWrapper bukkitWrapper = new CraftWrapper(provider);
testInequality(bukkitWrapper, new CraftWrapper(unequalProvider));
testInequality(bukkitWrapper, new CraftWrapper(new NoOpProvider(provider.material)));
ItemStackTest.testInequality(bukkitWrapper, new CraftWrapper(unequalProvider));
ItemStackTest.testInequality(bukkitWrapper, new CraftWrapper(new NoOpProvider(provider.material)));
}
static void testInequality(StackWrapper provider, StackWrapper unequalProvider) {
@@ -426,7 +426,7 @@ public class ItemStackTest {
assertThat(newUnequalCraftStack.getItemMeta(), is(not(stack.getItemMeta())));
}
@ParameterizedTest(name = "[{index}]:{" + NAME_PARAMETER + "}")
@ParameterizedTest(name = "[{index}]:{" + ItemStackTest.NAME_PARAMETER + "}")
@MethodSource({"data",
"org.bukkit.craftbukkit.inventory.ItemStackSkullTest#data",
"org.bukkit.craftbukkit.inventory.ItemStackPotionsTest#data",
@@ -439,10 +439,10 @@ public class ItemStackTest {
"org.bukkit.craftbukkit.inventory.ItemStackBookTest#data"
})
public void testBukkitYamlDeserialize(StackProvider provider, StackProvider unequalProvider, String name) throws Throwable {
testYamlDeserialize(new BukkitWrapper(provider), new BukkitWrapper(unequalProvider));
ItemStackTest.testYamlDeserialize(new BukkitWrapper(provider), new BukkitWrapper(unequalProvider));
}
@ParameterizedTest(name = "[{index}]:{" + NAME_PARAMETER + "}")
@ParameterizedTest(name = "[{index}]:{" + ItemStackTest.NAME_PARAMETER + "}")
@MethodSource({"data",
"org.bukkit.craftbukkit.inventory.ItemStackSkullTest#data",
"org.bukkit.craftbukkit.inventory.ItemStackPotionsTest#data",
@@ -455,10 +455,10 @@ public class ItemStackTest {
"org.bukkit.craftbukkit.inventory.ItemStackBookTest#data"
})
public void testCraftYamlDeserialize(StackProvider provider, StackProvider unequalProvider, String name) throws Throwable {
testYamlDeserialize(new CraftWrapper(provider), new CraftWrapper(unequalProvider));
ItemStackTest.testYamlDeserialize(new CraftWrapper(provider), new CraftWrapper(unequalProvider));
}
@ParameterizedTest(name = "[{index}]:{" + NAME_PARAMETER + "}")
@ParameterizedTest(name = "[{index}]:{" + ItemStackTest.NAME_PARAMETER + "}")
@MethodSource({"data",
"org.bukkit.craftbukkit.inventory.ItemStackSkullTest#data",
"org.bukkit.craftbukkit.inventory.ItemStackPotionsTest#data",
@@ -471,10 +471,10 @@ public class ItemStackTest {
"org.bukkit.craftbukkit.inventory.ItemStackBookTest#data"
})
public void testBukkitStreamDeserialize(StackProvider provider, StackProvider unequalProvider, String name) throws Throwable {
testStreamDeserialize(new BukkitWrapper(provider), new BukkitWrapper(unequalProvider));
ItemStackTest.testStreamDeserialize(new BukkitWrapper(provider), new BukkitWrapper(unequalProvider));
}
@ParameterizedTest(name = "[{index}]:{" + NAME_PARAMETER + "}")
@ParameterizedTest(name = "[{index}]:{" + ItemStackTest.NAME_PARAMETER + "}")
@MethodSource({"data",
"org.bukkit.craftbukkit.inventory.ItemStackSkullTest#data",
"org.bukkit.craftbukkit.inventory.ItemStackPotionsTest#data",
@@ -487,7 +487,7 @@ public class ItemStackTest {
"org.bukkit.craftbukkit.inventory.ItemStackBookTest#data"
})
public void testCraftStreamDeserialize(StackProvider provider, StackProvider unequalProvider, String name) throws Throwable {
testStreamDeserialize(new CraftWrapper(provider), new CraftWrapper(unequalProvider));
ItemStackTest.testStreamDeserialize(new CraftWrapper(provider), new CraftWrapper(unequalProvider));
}
static void testStreamDeserialize(StackWrapper provider, StackWrapper unequalProvider) throws Throwable {
@@ -532,7 +532,7 @@ public class ItemStackTest {
}
}
testEqualities(data, readFirst, readSecond, stack, unequalStack);
ItemStackTest.testEqualities(data, readFirst, readSecond, stack, unequalStack);
}
static void testYamlDeserialize(StackWrapper provider, StackWrapper unequalProvider) {
@@ -552,7 +552,7 @@ public class ItemStackTest {
throw new RuntimeException(out, ex);
}
testEqualities(out, configIn.getItemStack("provider"), configIn.getItemStack("unequal"), stack, unequalStack);
ItemStackTest.testEqualities(out, configIn.getItemStack("provider"), configIn.getItemStack("unequal"), stack, unequalStack);
}
static void testEqualities(String information, ItemStack primaryRead, ItemStack unequalRead, ItemStack primaryOriginal, ItemStack unequalOriginal) {

View File

@@ -40,43 +40,43 @@ public class PersistentDataContainerTest {
@BeforeAll
public static void setup() {
VALID_KEY = new NamespacedKey("test", "validkey");
PersistentDataContainerTest.VALID_KEY = new NamespacedKey("test", "validkey");
}
// Sets a test
@Test
public void testSetNoAdapter() {
ItemMeta itemMeta = createNewItemMeta();
ItemMeta itemMeta = PersistentDataContainerTest.createNewItemMeta();
assertThrows(IllegalArgumentException.class, () -> itemMeta.getPersistentDataContainer().set(VALID_KEY, new PrimitiveTagType<>(boolean.class), true));
}
// Contains a tag
@Test
public void testHasNoAdapter() {
ItemMeta itemMeta = createNewItemMeta();
itemMeta.getPersistentDataContainer().set(VALID_KEY, PersistentDataType.INTEGER, 1); // We gotta set this so we at least try to compare it
ItemMeta itemMeta = PersistentDataContainerTest.createNewItemMeta();
itemMeta.getPersistentDataContainer().set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.INTEGER, 1); // We gotta set this so we at least try to compare it
assertThrows(IllegalArgumentException.class, () -> itemMeta.getPersistentDataContainer().has(VALID_KEY, new PrimitiveTagType<>(boolean.class)));
}
@Test
public void testHasNoType() {
ItemMeta itemMeta = createNewItemMeta();
itemMeta.getPersistentDataContainer().set(VALID_KEY, PersistentDataType.INTEGER, 1); // We gotta set this so we at least try to compare it
assertTrue(itemMeta.getPersistentDataContainer().has(VALID_KEY));
ItemMeta itemMeta = PersistentDataContainerTest.createNewItemMeta();
itemMeta.getPersistentDataContainer().set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.INTEGER, 1); // We gotta set this so we at least try to compare it
assertTrue(itemMeta.getPersistentDataContainer().has(PersistentDataContainerTest.VALID_KEY));
}
// Getting a tag
@Test
public void testGetNoAdapter() {
ItemMeta itemMeta = createNewItemMeta();
itemMeta.getPersistentDataContainer().set(VALID_KEY, PersistentDataType.INTEGER, 1); //We gotta set this so we at least try to compare it
ItemMeta itemMeta = PersistentDataContainerTest.createNewItemMeta();
itemMeta.getPersistentDataContainer().set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.INTEGER, 1); //We gotta set this so we at least try to compare it
assertThrows(IllegalArgumentException.class, () -> itemMeta.getPersistentDataContainer().get(VALID_KEY, new PrimitiveTagType<>(boolean.class)));
}
@Test
public void testGetWrongType() {
ItemMeta itemMeta = createNewItemMeta();
itemMeta.getPersistentDataContainer().set(VALID_KEY, PersistentDataType.INTEGER, 1);
ItemMeta itemMeta = PersistentDataContainerTest.createNewItemMeta();
itemMeta.getPersistentDataContainer().set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.INTEGER, 1);
assertThrows(IllegalArgumentException.class, () -> itemMeta.getPersistentDataContainer().get(VALID_KEY, PersistentDataType.STRING));
}
@@ -85,7 +85,7 @@ public class PersistentDataContainerTest {
NamespacedKey namespacedKeyA = new NamespacedKey("plugin-a", "damage");
NamespacedKey namespacedKeyB = new NamespacedKey("plugin-b", "damage");
ItemMeta meta = createNewItemMeta();
ItemMeta meta = PersistentDataContainerTest.createNewItemMeta();
meta.getPersistentDataContainer().set(namespacedKeyA, PersistentDataType.LONG, 15L);
meta.getPersistentDataContainer().set(namespacedKeyB, PersistentDataType.LONG, 160L);
@@ -103,21 +103,21 @@ public class PersistentDataContainerTest {
@Test
public void testCopyTo() {
PersistentDataContainer container = createComplexItemMeta().getPersistentDataContainer();
PersistentDataContainer container = this.createComplexItemMeta().getPersistentDataContainer();
PersistentDataContainer target = container.getAdapterContext().newPersistentDataContainer();
target.set(VALID_KEY, PersistentDataType.INTEGER, 1);
container.set(VALID_KEY, PersistentDataType.INTEGER, 2);
target.set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.INTEGER, 1);
container.set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.INTEGER, 2);
container.copyTo(target, false);
assertEquals(1, target.get(VALID_KEY, PersistentDataType.INTEGER)); // Should not be replaced
assertEquals(1, target.get(PersistentDataContainerTest.VALID_KEY, PersistentDataType.INTEGER)); // Should not be replaced
}
@Test
public void testCopyToReplace() {
PersistentDataContainer container = createComplexItemMeta().getPersistentDataContainer();
PersistentDataContainer container = this.createComplexItemMeta().getPersistentDataContainer();
PersistentDataContainer target = container.getAdapterContext().newPersistentDataContainer();
target.set(VALID_KEY, PersistentDataType.INTEGER, 1);
container.set(VALID_KEY, PersistentDataType.INTEGER, 2);
target.set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.INTEGER, 1);
container.set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.INTEGER, 2);
container.copyTo(target, true);
assertEquals(container, target);
@@ -126,7 +126,7 @@ public class PersistentDataContainerTest {
// Removing a tag
@Test
public void testNBTTagStoring() {
CraftMetaItem itemMeta = createComplexItemMeta();
CraftMetaItem itemMeta = this.createComplexItemMeta();
CraftMetaItem.Applicator compound = new CraftMetaItem.Applicator();
itemMeta.applyToItem(compound);
@@ -136,7 +136,7 @@ public class PersistentDataContainerTest {
@Test
public void testMapStoring() {
CraftMetaItem itemMeta = createComplexItemMeta();
CraftMetaItem itemMeta = this.createComplexItemMeta();
Map<String, Object> serialize = itemMeta.serialize();
assertEquals(itemMeta, new CraftMetaItem(serialize));
@@ -145,7 +145,7 @@ public class PersistentDataContainerTest {
@Test
public void testYAMLStoring() {
ItemStack stack = new ItemStack(Material.DIAMOND);
CraftMetaItem meta = createComplexItemMeta();
CraftMetaItem meta = this.createComplexItemMeta();
stack.setItemMeta(meta);
YamlConfiguration configuration = new YamlConfiguration();
@@ -161,10 +161,10 @@ public class PersistentDataContainerTest {
@Test
public void testCorrectType() {
ItemStack stack = new ItemStack(Material.DIAMOND);
CraftMetaItem meta = createComplexItemMeta();
CraftMetaItem meta = this.createComplexItemMeta();
meta.getPersistentDataContainer().set(requestKey("int"), PersistentDataType.STRING, "1");
meta.getPersistentDataContainer().set(requestKey("double"), PersistentDataType.STRING, "1.33");
meta.getPersistentDataContainer().set(PersistentDataContainerTest.requestKey("int"), PersistentDataType.STRING, "1");
meta.getPersistentDataContainer().set(PersistentDataContainerTest.requestKey("double"), PersistentDataType.STRING, "1.33");
stack.setItemMeta(meta);
YamlConfiguration configuration = new YamlConfiguration();
@@ -174,34 +174,34 @@ public class PersistentDataContainerTest {
YamlConfiguration loadedConfig = YamlConfiguration.loadConfiguration(new StringReader(configValue));
ItemStack newStack = loadedConfig.getSerializable("testpath", ItemStack.class);
assertTrue(newStack.getItemMeta().getPersistentDataContainer().has(requestKey("int"), PersistentDataType.STRING));
assertEquals(newStack.getItemMeta().getPersistentDataContainer().get(requestKey("int"), PersistentDataType.STRING), "1");
assertTrue(newStack.getItemMeta().getPersistentDataContainer().has(PersistentDataContainerTest.requestKey("int"), PersistentDataType.STRING));
assertEquals(newStack.getItemMeta().getPersistentDataContainer().get(PersistentDataContainerTest.requestKey("int"), PersistentDataType.STRING), "1");
assertTrue(newStack.getItemMeta().getPersistentDataContainer().has(requestKey("double"), PersistentDataType.STRING));
assertEquals(newStack.getItemMeta().getPersistentDataContainer().get(requestKey("double"), PersistentDataType.STRING), "1.33");
assertTrue(newStack.getItemMeta().getPersistentDataContainer().has(PersistentDataContainerTest.requestKey("double"), PersistentDataType.STRING));
assertEquals(newStack.getItemMeta().getPersistentDataContainer().get(PersistentDataContainerTest.requestKey("double"), PersistentDataType.STRING), "1.33");
}
private CraftMetaItem createComplexItemMeta() {
CraftMetaItem itemMeta = (CraftMetaItem) createNewItemMeta();
CraftMetaItem itemMeta = (CraftMetaItem) PersistentDataContainerTest.createNewItemMeta();
itemMeta.setDisplayName("Item Display Name");
itemMeta.getPersistentDataContainer().set(requestKey("custom-long"), PersistentDataType.LONG, 4L); //Add random primitive values
itemMeta.getPersistentDataContainer().set(requestKey("custom-byte-array"), PersistentDataType.BYTE_ARRAY, new byte[]{
itemMeta.getPersistentDataContainer().set(PersistentDataContainerTest.requestKey("custom-long"), PersistentDataType.LONG, 4L); //Add random primitive values
itemMeta.getPersistentDataContainer().set(PersistentDataContainerTest.requestKey("custom-byte-array"), PersistentDataType.BYTE_ARRAY, new byte[]{
0, 1, 2, 10
});
itemMeta.getPersistentDataContainer().set(requestKey("custom-string"), PersistentDataType.STRING, "Hello there world");
itemMeta.getPersistentDataContainer().set(requestKey("custom-int"), PersistentDataType.INTEGER, 3);
itemMeta.getPersistentDataContainer().set(requestKey("custom-double"), PersistentDataType.DOUBLE, 3.123);
itemMeta.getPersistentDataContainer().set(PersistentDataContainerTest.requestKey("custom-string"), PersistentDataType.STRING, "Hello there world");
itemMeta.getPersistentDataContainer().set(PersistentDataContainerTest.requestKey("custom-int"), PersistentDataType.INTEGER, 3);
itemMeta.getPersistentDataContainer().set(PersistentDataContainerTest.requestKey("custom-double"), PersistentDataType.DOUBLE, 3.123);
itemMeta.getPersistentDataContainer().set(
requestKey("custom-list-string"), PersistentDataType.LIST.strings(), List.of("first[]", "second{}", "third()")
PersistentDataContainerTest.requestKey("custom-list-string"), PersistentDataType.LIST.strings(), List.of("first[]", "second{}", "third()")
);
itemMeta.getPersistentDataContainer().set(
requestKey("custom-list-bytes"), PersistentDataType.LIST.bytes(), List.of((byte) 1, (byte) 2, (byte) 3)
PersistentDataContainerTest.requestKey("custom-list-bytes"), PersistentDataType.LIST.bytes(), List.of((byte) 1, (byte) 2, (byte) 3)
);
PersistentDataContainer innerContainer = itemMeta.getPersistentDataContainer().getAdapterContext().newPersistentDataContainer(); //Add a inner container
innerContainer.set(VALID_KEY, PersistentDataType.LONG, 5L);
itemMeta.getPersistentDataContainer().set(requestKey("custom-inner-compound"), PersistentDataType.TAG_CONTAINER, innerContainer);
innerContainer.set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.LONG, 5L);
itemMeta.getPersistentDataContainer().set(PersistentDataContainerTest.requestKey("custom-inner-compound"), PersistentDataType.TAG_CONTAINER, innerContainer);
return itemMeta;
}
@@ -222,11 +222,11 @@ public class PersistentDataContainerTest {
""";
final PersistentDataContainer pdc = meta.getPersistentDataContainer();
pdc.set(requestKey("string_int"), PersistentDataType.STRING, "5i");
pdc.set(requestKey("string_true"), PersistentDataType.STRING, "true");
pdc.set(requestKey("string_byte_array"), PersistentDataType.STRING, "[B;-128B]");
pdc.set(requestKey("string_array_lookalike"), PersistentDataType.STRING, arrayLookalike);
pdc.set(requestKey("string_json_lookalike"), PersistentDataType.STRING, jsonLookalike);
pdc.set(PersistentDataContainerTest.requestKey("string_int"), PersistentDataType.STRING, "5i");
pdc.set(PersistentDataContainerTest.requestKey("string_true"), PersistentDataType.STRING, "true");
pdc.set(PersistentDataContainerTest.requestKey("string_byte_array"), PersistentDataType.STRING, "[B;-128B]");
pdc.set(PersistentDataContainerTest.requestKey("string_array_lookalike"), PersistentDataType.STRING, arrayLookalike);
pdc.set(PersistentDataContainerTest.requestKey("string_json_lookalike"), PersistentDataType.STRING, jsonLookalike);
stack.setItemMeta(meta);
@@ -240,52 +240,52 @@ public class PersistentDataContainerTest {
assertNotNull(loadedMeta);
final PersistentDataContainer loadedPdc = loadedMeta.getPersistentDataContainer();
assertEquals("5i", loadedPdc.get(requestKey("string_int"), PersistentDataType.STRING));
assertEquals("true", loadedPdc.get(requestKey("string_true"), PersistentDataType.STRING));
assertEquals(arrayLookalike, loadedPdc.get(requestKey("string_array_lookalike"), PersistentDataType.STRING));
assertEquals(jsonLookalike, loadedPdc.get(requestKey("string_json_lookalike"), PersistentDataType.STRING));
assertEquals("5i", loadedPdc.get(PersistentDataContainerTest.requestKey("string_int"), PersistentDataType.STRING));
assertEquals("true", loadedPdc.get(PersistentDataContainerTest.requestKey("string_true"), PersistentDataType.STRING));
assertEquals(arrayLookalike, loadedPdc.get(PersistentDataContainerTest.requestKey("string_array_lookalike"), PersistentDataType.STRING));
assertEquals(jsonLookalike, loadedPdc.get(PersistentDataContainerTest.requestKey("string_json_lookalike"), PersistentDataType.STRING));
}
// Test complex object storage
@Test
public void storeUUIDOnItemTest() {
ItemMeta itemMeta = createNewItemMeta();
ItemMeta itemMeta = PersistentDataContainerTest.createNewItemMeta();
UUIDPersistentDataType uuidPersistentDataType = new UUIDPersistentDataType();
UUID uuid = UUID.fromString("434eea72-22a6-4c61-b5ef-945874a5c478");
itemMeta.getPersistentDataContainer().set(VALID_KEY, uuidPersistentDataType, uuid);
assertTrue(itemMeta.getPersistentDataContainer().has(VALID_KEY, uuidPersistentDataType));
assertEquals(uuid, itemMeta.getPersistentDataContainer().get(VALID_KEY, uuidPersistentDataType));
itemMeta.getPersistentDataContainer().set(PersistentDataContainerTest.VALID_KEY, uuidPersistentDataType, uuid);
assertTrue(itemMeta.getPersistentDataContainer().has(PersistentDataContainerTest.VALID_KEY, uuidPersistentDataType));
assertEquals(uuid, itemMeta.getPersistentDataContainer().get(PersistentDataContainerTest.VALID_KEY, uuidPersistentDataType));
}
@Test
public void encapsulatedContainers() {
NamespacedKey innerKey = new NamespacedKey("plugin-a", "inner");
ItemMeta meta = createNewItemMeta();
ItemMeta meta = PersistentDataContainerTest.createNewItemMeta();
PersistentDataAdapterContext context = meta.getPersistentDataContainer().getAdapterContext();
PersistentDataContainer thirdContainer = context.newPersistentDataContainer();
thirdContainer.set(VALID_KEY, PersistentDataType.LONG, 3L);
thirdContainer.set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.LONG, 3L);
PersistentDataContainer secondContainer = context.newPersistentDataContainer();
secondContainer.set(VALID_KEY, PersistentDataType.LONG, 2L);
secondContainer.set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.LONG, 2L);
secondContainer.set(innerKey, PersistentDataType.TAG_CONTAINER, thirdContainer);
meta.getPersistentDataContainer().set(VALID_KEY, PersistentDataType.LONG, 1L);
meta.getPersistentDataContainer().set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.LONG, 1L);
meta.getPersistentDataContainer().set(innerKey, PersistentDataType.TAG_CONTAINER, secondContainer);
assertEquals(3L, meta.getPersistentDataContainer()
.get(innerKey, PersistentDataType.TAG_CONTAINER)
.get(innerKey, PersistentDataType.TAG_CONTAINER)
.get(VALID_KEY, PersistentDataType.LONG).longValue());
.get(PersistentDataContainerTest.VALID_KEY, PersistentDataType.LONG).longValue());
assertEquals(2L, meta.getPersistentDataContainer()
.get(innerKey, PersistentDataType.TAG_CONTAINER)
.get(VALID_KEY, PersistentDataType.LONG).longValue());
.get(PersistentDataContainerTest.VALID_KEY, PersistentDataType.LONG).longValue());
assertEquals(1L, meta.getPersistentDataContainer()
.get(VALID_KEY, PersistentDataType.LONG).longValue());
.get(PersistentDataContainerTest.VALID_KEY, PersistentDataType.LONG).longValue());
}
class UUIDPersistentDataType implements PersistentDataType<byte[], UUID> {
@@ -323,7 +323,7 @@ public class PersistentDataContainerTest {
@Test
public void testPrimitiveCustomTags() {
ItemMeta itemMeta = createNewItemMeta();
ItemMeta itemMeta = PersistentDataContainerTest.createNewItemMeta();
this.testPrimitiveCustomTag(itemMeta, PersistentDataType.BYTE, (byte) 1);
this.testPrimitiveCustomTag(itemMeta, PersistentDataType.SHORT, (short) 1);
@@ -401,9 +401,9 @@ public class PersistentDataContainerTest {
@Test
public void testItemMetaClone() {
ItemMeta itemMeta = createNewItemMeta();
ItemMeta itemMeta = PersistentDataContainerTest.createNewItemMeta();
PersistentDataContainer container = itemMeta.getPersistentDataContainer();
itemMeta.getPersistentDataContainer().set(VALID_KEY, PersistentDataType.STRING, "notch");
itemMeta.getPersistentDataContainer().set(PersistentDataContainerTest.VALID_KEY, PersistentDataType.STRING, "notch");
ItemMeta clonedMeta = itemMeta.clone();
PersistentDataContainer clonedContainer = clonedMeta.getPersistentDataContainer();
@@ -418,12 +418,12 @@ public class PersistentDataContainerTest {
@ParameterizedTest
@MethodSource("testListTypeArgumentSource")
public <T> void testListType(@NotNull final ListPersistentDataType<T, T> type, @NotNull final List<T> list, @NotNull final BiConsumer<T, T> equalsCheck) {
final ItemMeta meta = createNewItemMeta();
final ItemMeta meta = PersistentDataContainerTest.createNewItemMeta();
final PersistentDataContainer container = meta.getPersistentDataContainer();
container.set(requestKey("list"), type, list);
container.set(PersistentDataContainerTest.requestKey("list"), type, list);
final List<T> returnedList = container.get(requestKey("list"), type);
final List<T> returnedList = container.get(PersistentDataContainerTest.requestKey("list"), type);
assertNotNull(returnedList);
assertEquals(list.size(), returnedList.size());
@@ -437,10 +437,10 @@ public class PersistentDataContainerTest {
@NotNull
private static Stream<Arguments> testListTypeArgumentSource() {
final PersistentDataContainer first = createNewItemMeta().getPersistentDataContainer();
final PersistentDataContainer first = PersistentDataContainerTest.createNewItemMeta().getPersistentDataContainer();
final PersistentDataContainer second = first.getAdapterContext().newPersistentDataContainer();
first.set(requestKey("a"), PersistentDataType.STRING, "hello world");
second.set(requestKey("b"), PersistentDataType.BOOLEAN, true);
first.set(PersistentDataContainerTest.requestKey("a"), PersistentDataType.STRING, "hello world");
second.set(PersistentDataContainerTest.requestKey("b"), PersistentDataType.BOOLEAN, true);
final BiConsumer<Object, Object> objectAssertion = Assertions::assertEquals;
final BiConsumer<byte[], byte[]> byteArrayAssertion = Assertions::assertArrayEquals;
@@ -467,11 +467,11 @@ public class PersistentDataContainerTest {
final CraftMetaItem craftItem = new CraftMetaItem(DataComponentPatch.EMPTY);
final PersistentDataContainer container = craftItem.getPersistentDataContainer();
container.set(requestKey("list"), PersistentDataType.LIST.strings(), List.of());
assertTrue(container.has(requestKey("list"), PersistentDataType.LIST.strings()));
assertTrue(container.has(requestKey("list"), PersistentDataType.LIST.bytes()));
assertFalse(container.has(requestKey("list"), PersistentDataType.STRING));
assertEquals(List.of(), container.get(requestKey("list"), PersistentDataType.LIST.strings()));
container.set(PersistentDataContainerTest.requestKey("list"), PersistentDataType.LIST.strings(), List.of());
assertTrue(container.has(PersistentDataContainerTest.requestKey("list"), PersistentDataType.LIST.strings()));
assertTrue(container.has(PersistentDataContainerTest.requestKey("list"), PersistentDataType.LIST.bytes()));
assertFalse(container.has(PersistentDataContainerTest.requestKey("list"), PersistentDataType.STRING));
assertEquals(List.of(), container.get(PersistentDataContainerTest.requestKey("list"), PersistentDataType.LIST.strings()));
// Write and read the entire container to NBT
final CraftMetaItem.Applicator storage = new CraftMetaItem.Applicator();
@@ -480,10 +480,10 @@ public class PersistentDataContainerTest {
final CraftMetaItem readItem = new CraftMetaItem(storage.build());
final PersistentDataContainer readContainer = readItem.getPersistentDataContainer();
assertTrue(readContainer.has(requestKey("list"), PersistentDataType.LIST.strings()));
assertTrue(readContainer.has(requestKey("list"), PersistentDataType.LIST.bytes()));
assertFalse(readContainer.has(requestKey("list"), PersistentDataType.STRING));
assertEquals(List.of(), readContainer.get(requestKey("list"), PersistentDataType.LIST.strings()));
assertTrue(readContainer.has(PersistentDataContainerTest.requestKey("list"), PersistentDataType.LIST.strings()));
assertTrue(readContainer.has(PersistentDataContainerTest.requestKey("list"), PersistentDataType.LIST.bytes()));
assertFalse(readContainer.has(PersistentDataContainerTest.requestKey("list"), PersistentDataType.STRING));
assertEquals(List.of(), readContainer.get(PersistentDataContainerTest.requestKey("list"), PersistentDataType.LIST.strings()));
}
// This is a horrific marriage of tag container array "primitive" types the API offered and the new list types.
@@ -497,24 +497,24 @@ public class PersistentDataContainerTest {
public void testListOfListViaContainerArray() {
final ListPersistentDataType<PersistentDataContainer[], PersistentDataContainer[]> listPersistentDataType = PersistentDataType.LIST.listTypeFrom(PersistentDataType.TAG_CONTAINER_ARRAY);
final ItemMeta meta = createNewItemMeta();
final ItemMeta meta = PersistentDataContainerTest.createNewItemMeta();
final PersistentDataContainer container = meta.getPersistentDataContainer();
final PersistentDataAdapterContext adapterContext = container.getAdapterContext();
final PersistentDataContainer first = adapterContext.newPersistentDataContainer();
first.set(requestKey("a"), PersistentDataType.STRING, "hi");
first.set(PersistentDataContainerTest.requestKey("a"), PersistentDataType.STRING, "hi");
final PersistentDataContainer second = adapterContext.newPersistentDataContainer();
second.set(requestKey("a"), PersistentDataType.INTEGER, 2);
second.set(PersistentDataContainerTest.requestKey("a"), PersistentDataType.INTEGER, 2);
final List<PersistentDataContainer[]> listOfArrays = new ArrayList<>();
listOfArrays.add(new PersistentDataContainer[]{first, second});
container.set(requestKey("containerListList"), listPersistentDataType, listOfArrays);
container.set(PersistentDataContainerTest.requestKey("containerListList"), listPersistentDataType, listOfArrays);
assertTrue(container.has(requestKey("containerListList"), listPersistentDataType));
assertTrue(container.has(PersistentDataContainerTest.requestKey("containerListList"), listPersistentDataType));
final List<PersistentDataContainer[]> containerListList = container.get(requestKey("containerListList"), listPersistentDataType);
final List<PersistentDataContainer[]> containerListList = container.get(PersistentDataContainerTest.requestKey("containerListList"), listPersistentDataType);
assertNotNull(containerListList);
assertEquals(1, containerListList.size());
@@ -522,7 +522,7 @@ public class PersistentDataContainerTest {
final PersistentDataContainer[] arrayOfPDC = containerListList.get(0);
assertEquals(2, arrayOfPDC.length);
assertEquals("hi", arrayOfPDC[0].get(requestKey("a"), PersistentDataType.STRING));
assertEquals(2, arrayOfPDC[1].get(requestKey("a"), PersistentDataType.INTEGER));
assertEquals("hi", arrayOfPDC[0].get(PersistentDataContainerTest.requestKey("a"), PersistentDataType.STRING));
assertEquals(2, arrayOfPDC[1].get(PersistentDataContainerTest.requestKey("a"), PersistentDataType.INTEGER));
}
}

View File

@@ -1,7 +1,8 @@
package org.bukkit.craftbukkit.inventory;
import static org.junit.jupiter.api.Assertions.*;
import net.minecraft.world.entity.player.PlayerInventory;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import org.bukkit.support.environment.Normal;
@@ -19,7 +20,7 @@ public class PlayerInventoryTest {
ItemStack itemStack64Coal = new ItemStack(Items.COAL, 64);
// keep one slot empty
PlayerInventory inventory = new PlayerInventory(null);
Inventory inventory = new Inventory(null);
for (int i = 0; i < inventory.items.size() - 1; i++) {
inventory.setItem(i, itemStackApple);
}

View File

@@ -146,15 +146,15 @@ public class LegacyTest {
@Test
public void toLegacyMaterial() {
for (Material material : Material.values()) {
if (!INVALIDATED_MATERIALS.contains(material) && !material.isLegacy()) {
if (!this.INVALIDATED_MATERIALS.contains(material) && !material.isLegacy()) {
MaterialData converted = CraftLegacy.toLegacyData(material);
assertNotEquals(Material.LEGACY_AIR, converted.getItemType(), "Could not toLegacy " + material);
if (!INVALIDATED_MATERIALS.contains(converted.getItemType())) {
if (!this.INVALIDATED_MATERIALS.contains(converted.getItemType())) {
assertNotEquals(Material.AIR, CraftLegacy.fromLegacy(converted), "Could not fromLegacy(toLegacy) " + converted + "(" + material + ")");
}
if (!INVERSION_FAILS.contains(material)) {
if (!this.INVERSION_FAILS.contains(material)) {
assertEquals(material, CraftLegacy.fromLegacy(converted), "Could not fromLegacy(toLegacy) " + converted + "(" + material + ")");
}
}
@@ -166,12 +166,12 @@ public class LegacyTest {
@Test
public void fromLegacyMaterial() {
for (Material material : Material.values()) {
if (!INVALIDATED_MATERIALS.contains(material) && material.isLegacy()) {
if (!this.INVALIDATED_MATERIALS.contains(material) && material.isLegacy()) {
Material converted = CraftLegacy.fromLegacy(material);
assertNotEquals(Material.AIR, converted, "Could not fromLegacy " + material);
assertNotEquals(Material.AIR, CraftLegacy.toLegacy(converted), "Could not toLegacy(fromLegacy) " + converted + "(" + material + ")");
if (!INVERSION_FAILS.contains(material)) {
if (!this.INVERSION_FAILS.contains(material)) {
assertEquals(material, CraftLegacy.toLegacy(converted), "Could not toLegacy(fromLegacy) " + converted + "(" + material + ")");
}
}

View File

@@ -46,7 +46,7 @@ public class MaterialReroutingTest {
private static JarFile jarFile = null;
public static Stream<Arguments> bukkitData() {
return jarFile
return MaterialReroutingTest.jarFile
.stream()
.filter(entry -> entry.getName().endsWith(".class"))
// Add class exceptions here
@@ -58,7 +58,7 @@ public class MaterialReroutingTest {
.filter(entry -> !entry.getName().startsWith("org/bukkit/material"))
.map(entry -> {
try {
return jarFile.getInputStream(entry);
return MaterialReroutingTest.jarFile.getInputStream(entry);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -67,7 +67,7 @@ public class MaterialReroutingTest {
@BeforeAll
public static void beforeAll() throws IOException {
jarFile = new JarFile(new File(BUKKIT_CLASSES));
MaterialReroutingTest.jarFile = new JarFile(new File(MaterialReroutingTest.BUKKIT_CLASSES));
}
@ParameterizedTest
@@ -94,7 +94,7 @@ public class MaterialReroutingTest {
}
}
if (!Commodore.rerouteMethods(ApiVersion.CURRENT, MATERIAL_METHOD_REROUTE, (methodNode.access & Opcodes.ACC_STATIC) != 0, classNode.name, methodNode.name, methodNode.desc, a -> { })) {
if (!Commodore.rerouteMethods(ApiVersion.CURRENT, MaterialReroutingTest.MATERIAL_METHOD_REROUTE, (methodNode.access & Opcodes.ACC_STATIC) != 0, classNode.name, methodNode.name, methodNode.desc, a -> { })) {
missingReroute.add(methodNode.name + " " + methodNode.desc + " " + methodNode.signature);
}
}
@@ -111,8 +111,8 @@ public class MaterialReroutingTest {
@AfterAll
public static void clear() throws IOException {
if (jarFile != null) {
jarFile.close();
if (MaterialReroutingTest.jarFile != null) {
MaterialReroutingTest.jarFile.close();
}
}
}

View File

@@ -24,7 +24,7 @@ public class PersistentDataContainerLegacyTest {
CraftItemFactory.instance(); // Initialize craft item factory to register craft item meta serializers
YamlConfiguration legacyConfig = null;
try (final InputStream input = getClass().getClassLoader().getResourceAsStream("pdc/legacy_pdc.yml")) {
try (final InputStream input = this.getClass().getClassLoader().getResourceAsStream("pdc/legacy_pdc.yml")) {
assertNotNull(input, "Legacy pdc yaml was null");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, Charsets.UTF_8))) {
@@ -43,23 +43,23 @@ public class PersistentDataContainerLegacyTest {
assertNotNull(meta);
final PersistentDataContainer pdc = meta.getPersistentDataContainer();
assertEquals(Byte.valueOf(Byte.MAX_VALUE), pdc.get(key("byte"), PersistentDataType.BYTE), "legacy byte was wrong");
assertEquals(Short.valueOf(Short.MAX_VALUE), pdc.get(key("short"), PersistentDataType.SHORT), "legacy short was wrong");
assertEquals(Integer.valueOf(Integer.MAX_VALUE), pdc.get(key("integer"), PersistentDataType.INTEGER), "legacy integer was wrong");
assertEquals(Long.valueOf(Long.MAX_VALUE), pdc.get(key("long"), PersistentDataType.LONG), "legacy long was wrong");
assertEquals(Float.valueOf(Float.MAX_VALUE), pdc.get(key("float"), PersistentDataType.FLOAT), "legacy float was wrong");
assertEquals(Double.valueOf(Double.MAX_VALUE), pdc.get(key("double"), PersistentDataType.DOUBLE), "legacy double was wrong");
assertEquals("stringy", pdc.get(key("string_simple"), PersistentDataType.STRING), "legacy string-simple was wrong");
assertEquals("What a fun complex string 🔥", pdc.get(key("string_complex"), PersistentDataType.STRING), "legacy string-complex was wrong");
assertEquals(Byte.valueOf(Byte.MAX_VALUE), pdc.get(this.key("byte"), PersistentDataType.BYTE), "legacy byte was wrong");
assertEquals(Short.valueOf(Short.MAX_VALUE), pdc.get(this.key("short"), PersistentDataType.SHORT), "legacy short was wrong");
assertEquals(Integer.valueOf(Integer.MAX_VALUE), pdc.get(this.key("integer"), PersistentDataType.INTEGER), "legacy integer was wrong");
assertEquals(Long.valueOf(Long.MAX_VALUE), pdc.get(this.key("long"), PersistentDataType.LONG), "legacy long was wrong");
assertEquals(Float.valueOf(Float.MAX_VALUE), pdc.get(this.key("float"), PersistentDataType.FLOAT), "legacy float was wrong");
assertEquals(Double.valueOf(Double.MAX_VALUE), pdc.get(this.key("double"), PersistentDataType.DOUBLE), "legacy double was wrong");
assertEquals("stringy", pdc.get(this.key("string_simple"), PersistentDataType.STRING), "legacy string-simple was wrong");
assertEquals("What a fun complex string 🔥", pdc.get(this.key("string_complex"), PersistentDataType.STRING), "legacy string-complex was wrong");
assertArrayEquals(new byte[]{Byte.MIN_VALUE}, pdc.get(key("byte_array"), PersistentDataType.BYTE_ARRAY), "legacy byte array was wrong");
assertArrayEquals(new byte[]{Byte.MIN_VALUE}, pdc.get(this.key("byte_array"), PersistentDataType.BYTE_ARRAY), "legacy byte array was wrong");
assertArrayEquals(new int[]{Integer.MIN_VALUE}, pdc.get(key("integer_array"), PersistentDataType.INTEGER_ARRAY), "legacy integer array was wrong");
assertArrayEquals(new int[]{Integer.MIN_VALUE}, pdc.get(this.key("integer_array"), PersistentDataType.INTEGER_ARRAY), "legacy integer array was wrong");
assertArrayEquals(new long[]{Long.MIN_VALUE}, pdc.get(key("long_array"), PersistentDataType.LONG_ARRAY), "legacy long array was wrong");
assertArrayEquals(new long[]{Long.MIN_VALUE}, pdc.get(this.key("long_array"), PersistentDataType.LONG_ARRAY), "legacy long array was wrong");
assertEquals("5", pdc.get(key("string_edge_case_number"), PersistentDataType.STRING), "legacy string edge case number");
assertEquals("\"Hello world\"", pdc.get(key("string_edge_case_quoted"), PersistentDataType.STRING), "legacy string edge case quotes");
assertEquals("5", pdc.get(this.key("string_edge_case_number"), PersistentDataType.STRING), "legacy string edge case number");
assertEquals("\"Hello world\"", pdc.get(this.key("string_edge_case_quoted"), PersistentDataType.STRING), "legacy string edge case quotes");
}
private NamespacedKey key(String key) {

View File

@@ -11,11 +11,11 @@ import org.objectweb.asm.Type;
public abstract class AbstractRerouteTest {
void test(Class<?> testClass, Map<String, RerouteMethodData> dataMap) {
test(testClass, Predicates.alwaysTrue(), dataMap);
this.test(testClass, Predicates.alwaysTrue(), dataMap);
}
void test(Class<?> testClass, Predicate<String> predicate, Map<String, RerouteMethodData> dataMap) {
test(testClass, Predicates.and(predicate), dataMap.entrySet().stream().map(entry -> new TestDataHolder(entry.getKey(), List.of(entry.getValue()))).toList());
this.test(testClass, Predicates.and(predicate), dataMap.entrySet().stream().map(entry -> new TestDataHolder(entry.getKey(), List.of(entry.getValue()))).toList());
}
void test(Class<?> testClass, Predicate<String> predicate, List<TestDataHolder> dataList) {
@@ -34,7 +34,7 @@ public abstract class AbstractRerouteTest {
RerouteMethodData actual = holder.rerouteMethodDataMap.get(testData.sourceOwner().getInternalName());
assertNotNull(actual, String.format("No reroute method data found for %s", testData));
check(actual, testData);
this.check(actual, testData);
}
}
}

View File

@@ -10,7 +10,7 @@ public class DoNotRerouteTest extends AbstractRerouteTest {
@Test
public void testDoNotReroute() {
test(DoNotRerouteTestData.class, Map.of());
this.test(DoNotRerouteTestData.class, Map.of());
}
public static class DoNotRerouteTestData {

View File

@@ -12,8 +12,8 @@ public class InjectCompatibilityTest extends AbstractRerouteTest {
@Test
public void testInjectCompatibility() {
test(InjectCompatibilityTestData.class, Map.of(
"()Ljava/util/List;getList", create(
this.test(InjectCompatibilityTestData.class, Map.of(
"()Ljava/util/List;getList", this.create(
"()Ljava/util/List;getList",
"()Ljava/util/List;",
"java/lang/Object",
@@ -22,9 +22,9 @@ public class InjectCompatibilityTest extends AbstractRerouteTest {
"(Ljava/lang/Object;Z)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/InjectCompatibilityTest$InjectCompatibilityTestData",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null),
create("Z", "Z", false, false, "test-value")
this.create(
this.create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null),
this.create("Z", "Z", false, false, "test-value")
),
"Ljava/util/List;",
true,

View File

@@ -12,8 +12,8 @@ public class InjectPluginNameTest extends AbstractRerouteTest {
@Test
public void testInjectPluginName() {
test(InjectPluginNameTestData.class, Map.of(
"()Ljava/util/List;getList", create(
this.test(InjectPluginNameTestData.class, Map.of(
"()Ljava/util/List;getList", this.create(
"()Ljava/util/List;getList",
"()Ljava/util/List;",
"java/lang/Object",
@@ -22,9 +22,9 @@ public class InjectPluginNameTest extends AbstractRerouteTest {
"(Ljava/lang/Object;Ljava/lang/String;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/InjectPluginNameTest$InjectPluginNameTestData",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null),
create("Ljava/lang/String;", "Ljava/lang/String;", true, false, null)
this.create(
this.create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null),
this.create("Ljava/lang/String;", "Ljava/lang/String;", true, false, null)
),
"Ljava/util/List;",
true,

View File

@@ -13,8 +13,8 @@ public class InjectPluginVersionTest extends AbstractRerouteTest {
@Test
public void testInjectPluginVersion() {
test(InjectPluginVersionTestData.class, Map.of(
"()Ljava/util/List;getList", create(
this.test(InjectPluginVersionTestData.class, Map.of(
"()Ljava/util/List;getList", this.create(
"()Ljava/util/List;getList",
"()Ljava/util/List;",
"java/lang/Object",
@@ -23,9 +23,9 @@ public class InjectPluginVersionTest extends AbstractRerouteTest {
"(Ljava/lang/Object;Lorg/bukkit/craftbukkit/util/ApiVersion;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/InjectPluginVersionTest$InjectPluginVersionTestData",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null),
create("Lorg/bukkit/craftbukkit/util/ApiVersion;", "Lorg/bukkit/craftbukkit/util/ApiVersion;", false, true, null)
this.create(
this.create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null),
this.create("Lorg/bukkit/craftbukkit/util/ApiVersion;", "Lorg/bukkit/craftbukkit/util/ApiVersion;", false, true, null)
),
"Ljava/util/List;",
true,

View File

@@ -10,8 +10,8 @@ public class NotInBukkitTest extends AbstractRerouteTest {
@Test
public void testNotInBukkit() {
test(NotInBukkitTestData.class, Map.of(
"()Ljava/util/List;getList", create(
this.test(NotInBukkitTestData.class, Map.of(
"()Ljava/util/List;getList", this.create(
"()Ljava/util/List;getList",
"()Ljava/util/List;",
"java/lang/Object",
@@ -20,8 +20,8 @@ public class NotInBukkitTest extends AbstractRerouteTest {
"(Ljava/lang/Object;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/NotInBukkitTest$NotInBukkitTestData",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
this.create(
this.create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
),
"Ljava/util/List;",
false,

View File

@@ -11,8 +11,8 @@ public class RequireCompatibilityTest extends AbstractRerouteTest {
@Test
public void testRequireCompatibility() {
test(RequireCompatibilityTestData.class, Map.of(
"()Ljava/util/List;getList", create(
this.test(RequireCompatibilityTestData.class, Map.of(
"()Ljava/util/List;getList", this.create(
"()Ljava/util/List;getList",
"()Ljava/util/List;",
"java/lang/Object",
@@ -21,8 +21,8 @@ public class RequireCompatibilityTest extends AbstractRerouteTest {
"(Ljava/lang/Object;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/RequireCompatibilityTest$RequireCompatibilityTestData",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
this.create(
this.create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
),
"Ljava/util/List;",
true,
@@ -34,7 +34,7 @@ public class RequireCompatibilityTest extends AbstractRerouteTest {
@Test
public void testRequireCompatibilityNotPresent() {
test(RequireCompatibilityTestData.class, Predicates.alwaysFalse(), Map.of());
this.test(RequireCompatibilityTestData.class, Predicates.alwaysFalse(), Map.of());
}
public static class RequireCompatibilityTestData {

View File

@@ -11,8 +11,8 @@ public class RequirePluginVersionTest extends AbstractRerouteTest {
@Test
public void testRequirePluginVersion() {
test(RequirePluginVersionTestData.class, Map.of(
"()Ljava/util/List;getList", create(
this.test(RequirePluginVersionTestData.class, Map.of(
"()Ljava/util/List;getList", this.create(
"()Ljava/util/List;getList",
"()Ljava/util/List;",
"java/lang/Object",
@@ -21,8 +21,8 @@ public class RequirePluginVersionTest extends AbstractRerouteTest {
"(Ljava/lang/Object;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/RequirePluginVersionTest$RequirePluginVersionTestData",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
this.create(
this.create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
),
"Ljava/util/List;",
true,

View File

@@ -10,8 +10,8 @@ public class RerouteArgumentTypeTest extends AbstractRerouteTest {
@Test
public void testRerouteArgumentType() {
test(RerouteArgumentTypeTestData.class, Map.of(
"()Ljava/util/List;getList", create(
this.test(RerouteArgumentTypeTestData.class, Map.of(
"()Ljava/util/List;getList", this.create(
"()Ljava/util/List;getList",
"()Ljava/util/List;",
"java/util/Map",
@@ -20,8 +20,8 @@ public class RerouteArgumentTypeTest extends AbstractRerouteTest {
"(Ljava/lang/Object;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/RerouteArgumentTypeTest$RerouteArgumentTypeTestData",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/util/Map;", false, false, null)
this.create(
this.create("Ljava/lang/Object;", "Ljava/util/Map;", false, false, null)
),
"Ljava/util/List;",
true,
@@ -33,8 +33,8 @@ public class RerouteArgumentTypeTest extends AbstractRerouteTest {
@Test
public void testRerouteArgumentTypeSecond() {
test(RerouteArgumentTypeSecondTestData.class, Map.of(
"(Ljava/lang/String;)Ljava/util/List;getList", create(
this.test(RerouteArgumentTypeSecondTestData.class, Map.of(
"(Ljava/lang/String;)Ljava/util/List;getList", this.create(
"(Ljava/lang/String;)Ljava/util/List;getList",
"(Ljava/lang/String;)Ljava/util/List;",
"java/lang/Object",
@@ -43,9 +43,9 @@ public class RerouteArgumentTypeTest extends AbstractRerouteTest {
"(Ljava/lang/Object;Ljava/util/Map;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/RerouteArgumentTypeTest$RerouteArgumentTypeSecondTestData",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null),
create("Ljava/util/Map;", "Ljava/lang/String;", false, false, null)
this.create(
this.create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null),
this.create("Ljava/util/Map;", "Ljava/lang/String;", false, false, null)
),
"Ljava/util/List;",
true,

View File

@@ -13,8 +13,8 @@ public class RerouteBuilderTest extends AbstractRerouteTest {
@Test
public void testReroute() {
test(FirstTest.class, Map.of(
"()VtestReroute", create(
this.test(FirstTest.class, Map.of(
"()VtestReroute", this.create(
"()VtestReroute",
"()V",
"org/bukkit/craftbukkit/legacy/reroute/RerouteBuilderTest",
@@ -23,8 +23,8 @@ public class RerouteBuilderTest extends AbstractRerouteTest {
"(Lorg/bukkit/craftbukkit/legacy/reroute/RerouteBuilderTest;)V",
"org/bukkit/craftbukkit/legacy/reroute/RerouteBuilderTest$FirstTest",
"testReroute",
create(
create("Lorg/bukkit/craftbukkit/legacy/reroute/RerouteBuilderTest;", "Lorg/bukkit/craftbukkit/legacy/reroute/RerouteBuilderTest;", false, false, null)
this.create(
this.create("Lorg/bukkit/craftbukkit/legacy/reroute/RerouteBuilderTest;", "Lorg/bukkit/craftbukkit/legacy/reroute/RerouteBuilderTest;", false, false, null)
),
"V",
true,
@@ -35,13 +35,13 @@ public class RerouteBuilderTest extends AbstractRerouteTest {
@Test
public void testInvalidMethods() {
test(InvalidMethodTest.class, Map.of());
this.test(InvalidMethodTest.class, Map.of());
}
@Test
public void testMultipleMethods() {
test(MultipleMethodTest.class, Map.of(
"()Ljava/util/List;getList", create(
this.test(MultipleMethodTest.class, Map.of(
"()Ljava/util/List;getList", this.create(
"()Ljava/util/List;getList",
"()Ljava/util/List;",
"java/lang/Object",
@@ -50,14 +50,14 @@ public class RerouteBuilderTest extends AbstractRerouteTest {
"(Ljava/lang/Object;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/RerouteBuilderTest$MultipleMethodTest",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
this.create(
this.create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
),
"Ljava/util/List;",
true,
null
),
"(Ljava/util/Map;)Ljava/util/Map;getMap", create(
"(Ljava/util/Map;)Ljava/util/Map;getMap", this.create(
"(Ljava/util/Map;)Ljava/util/Map;getMap",
"(Ljava/util/Map;)Ljava/util/Map;",
"java/lang/String",
@@ -66,15 +66,15 @@ public class RerouteBuilderTest extends AbstractRerouteTest {
"(Ljava/lang/String;Ljava/util/Map;)Ljava/util/Map;",
"org/bukkit/craftbukkit/legacy/reroute/RerouteBuilderTest$MultipleMethodTest",
"getMap",
create(
create("Ljava/lang/String;", "Ljava/lang/String;", false, false, null),
create("Ljava/util/Map;", "Ljava/util/Map;", false, false, null)
this.create(
this.create("Ljava/lang/String;", "Ljava/lang/String;", false, false, null),
this.create("Ljava/util/Map;", "Ljava/util/Map;", false, false, null)
),
"Ljava/util/Map;",
true,
null
),
"(ZS)IgetInt", create(
"(ZS)IgetInt", this.create(
"(ZS)IgetInt",
"(ZS)I",
"java/util/logging/Logger",
@@ -83,10 +83,10 @@ public class RerouteBuilderTest extends AbstractRerouteTest {
"(Ljava/util/logging/Logger;ZS)I",
"org/bukkit/craftbukkit/legacy/reroute/RerouteBuilderTest$MultipleMethodTest",
"getInt",
create(
create("Ljava/util/logging/Logger;", "Ljava/util/logging/Logger;", false, false, null),
create("Z", "Z", false, false, null),
create("S", "S", false, false, null)
this.create(
this.create("Ljava/util/logging/Logger;", "Ljava/util/logging/Logger;", false, false, null),
this.create("Z", "Z", false, false, null),
this.create("S", "S", false, false, null)
),
"I",
true,
@@ -113,8 +113,8 @@ public class RerouteBuilderTest extends AbstractRerouteTest {
@Test
public void testSameKey() {
test(SameKeyTest.class, Predicates.alwaysTrue(), List.of(
new TestDataHolder("()Ljava/util/List;getList", List.of(create(
this.test(SameKeyTest.class, Predicates.alwaysTrue(), List.of(
new TestDataHolder("()Ljava/util/List;getList", List.of(this.create(
"()Ljava/util/List;getList",
"()Ljava/util/List;",
"java/lang/Object",
@@ -123,14 +123,14 @@ public class RerouteBuilderTest extends AbstractRerouteTest {
"(Ljava/lang/Object;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/RerouteBuilderTest$SameKeyTest",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
this.create(
this.create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
),
"Ljava/util/List;",
true,
null
),
create(
this.create(
"()Ljava/util/List;getList",
"()Ljava/util/List;",
"java/lang/String",
@@ -139,9 +139,9 @@ public class RerouteBuilderTest extends AbstractRerouteTest {
"(Ljava/lang/String;Ljava/lang/String;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/RerouteBuilderTest$SameKeyTest",
"getList",
create(
create("Ljava/lang/String;", "Ljava/lang/String;", false, false, null),
create("Ljava/lang/String;", "Ljava/lang/String;", true, false, null)
this.create(
this.create("Ljava/lang/String;", "Ljava/lang/String;", false, false, null),
this.create("Ljava/lang/String;", "Ljava/lang/String;", true, false, null)
),
"Ljava/util/List;",
true,

View File

@@ -10,8 +10,8 @@ public class RerouteMethodNameTest extends AbstractRerouteTest {
@Test
public void testRerouteMethodName() {
test(RerouteMethodNameTestData.class, Map.of(
"()Ljava/util/List;getMap", create(
this.test(RerouteMethodNameTestData.class, Map.of(
"()Ljava/util/List;getMap", this.create(
"()Ljava/util/List;getMap",
"()Ljava/util/List;",
"java/lang/Object",
@@ -20,8 +20,8 @@ public class RerouteMethodNameTest extends AbstractRerouteTest {
"(Ljava/lang/Object;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/RerouteMethodNameTest$RerouteMethodNameTestData",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
this.create(
this.create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
),
"Ljava/util/List;",
true,

View File

@@ -10,8 +10,8 @@ public class RerouteReturnTypeTest extends AbstractRerouteTest {
@Test
public void testRerouteReturnType() {
test(RerouteReturnTypeTestData.class, Map.of(
"()Ljava/util/Map;getList", create(
this.test(RerouteReturnTypeTestData.class, Map.of(
"()Ljava/util/Map;getList", this.create(
"()Ljava/util/Map;getList",
"()Ljava/util/Map;",
"java/lang/Object",
@@ -20,8 +20,8 @@ public class RerouteReturnTypeTest extends AbstractRerouteTest {
"(Ljava/lang/Object;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/RerouteReturnTypeTest$RerouteReturnTypeTestData",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
this.create(
this.create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
),
"Ljava/util/List;",
true,

View File

@@ -10,8 +10,8 @@ public class RerouteStaticTest extends AbstractRerouteTest {
@Test
public void testStaticReroute() {
test(RerouteStaticTestData.class, Map.of(
"(Ljava/lang/Object;)Ljava/util/List;getList", create(
this.test(RerouteStaticTestData.class, Map.of(
"(Ljava/lang/Object;)Ljava/util/List;getList", this.create(
"(Ljava/lang/Object;)Ljava/util/List;getList",
"(Ljava/lang/Object;)Ljava/util/List;",
"java/util/Map",
@@ -20,8 +20,8 @@ public class RerouteStaticTest extends AbstractRerouteTest {
"(Ljava/lang/Object;)Ljava/util/List;",
"org/bukkit/craftbukkit/legacy/reroute/RerouteStaticTest$RerouteStaticTestData",
"getList",
create(
create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
this.create(
this.create("Ljava/lang/Object;", "Ljava/lang/Object;", false, false, null)
),
"Ljava/util/List;",
true,

View File

@@ -36,7 +36,7 @@ public class RerouteValidationTest {
continue;
}
String error = isValid(entry.getKey(), entry.getValue());
String error = this.isValid(entry.getKey(), entry.getValue());
if (error != null) {
wrongReroutes.put(entry.getKey(), error);
@@ -56,13 +56,13 @@ public class RerouteValidationTest {
private String isValid(String key, RerouteMethodData rerouteMethodData) {
try {
Class<?> clazz = toClass(rerouteMethodData.sourceOwner());
Class<?> returnClazz = toClass(rerouteMethodData.sourceDesc().getReturnType());
Class<?> clazz = this.toClass(rerouteMethodData.sourceOwner());
Class<?> returnClazz = this.toClass(rerouteMethodData.sourceDesc().getReturnType());
Class<?>[] paras = new Class[rerouteMethodData.sourceDesc().getArgumentCount()];
Type[] paraTypes = rerouteMethodData.sourceDesc().getArgumentTypes();
for (int i = 0; i < paraTypes.length; i++) {
paras[i] = toClass(paraTypes[i]);
paras[i] = this.toClass(paraTypes[i]);
}
Method method = clazz.getDeclaredMethod(rerouteMethodData.sourceName(), paras);
@@ -93,9 +93,9 @@ public class RerouteValidationTest {
private Class<?> toClass(Type type) throws ClassNotFoundException {
if (type.getSort() == Type.OBJECT) {
return Class.forName(type.getClassName(), false, getClass().getClassLoader());
return Class.forName(type.getClassName(), false, this.getClass().getClassLoader());
} else if (type.getSort() == Type.ARRAY) {
return Class.forName(type.getDescriptor().replace('/', '.'), false, getClass().getClassLoader());
return Class.forName(type.getDescriptor().replace('/', '.'), false, this.getClass().getClassLoader());
} else {
return switch (type.getSort()) {
case Type.VOID -> void.class;

View File

@@ -6,7 +6,7 @@ import com.mojang.authlib.properties.Property;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
import net.minecraft.SystemUtils;
import net.minecraft.Util;
import net.minecraft.world.item.component.ResolvableProfile;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
@@ -58,15 +58,15 @@ public class PlayerProfileTest {
private static final String COMPACT_VALUE = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjg0ZGJmNjA3MDBiOTg4MmMwYzJhZDE5NDNiNTE1Y2MxMTFmMGI0ZTU2MmE5YTM2NjgyNDk1NjM2ZDg0Njc1NCJ9fX0=";
private static CraftPlayerProfile buildPlayerProfile() {
GameProfile gameProfile = new GameProfile(UNIQUE_ID, NAME);
gameProfile.getProperties().put(CraftPlayerTextures.PROPERTY_NAME, new Property(CraftPlayerTextures.PROPERTY_NAME, VALUE, SIGNATURE));
GameProfile gameProfile = new GameProfile(PlayerProfileTest.UNIQUE_ID, PlayerProfileTest.NAME);
gameProfile.getProperties().put(CraftPlayerTextures.PROPERTY_NAME, new Property(CraftPlayerTextures.PROPERTY_NAME, PlayerProfileTest.VALUE, PlayerProfileTest.SIGNATURE));
return new CraftPlayerProfile(gameProfile);
}
@Test
@EnableIfMojangServerAvailable
public void testProvidedValues() {
Property property = new Property(CraftPlayerTextures.PROPERTY_NAME, VALUE, SIGNATURE);
Property property = new Property(CraftPlayerTextures.PROPERTY_NAME, PlayerProfileTest.VALUE, PlayerProfileTest.SIGNATURE);
assertTrue(CraftProfileProperty.hasValidSignature(property), "Invalid test property signature, has the public key changed?");
}
@@ -84,9 +84,9 @@ public class PlayerProfileTest {
});
// Valid profiles:
new CraftPlayerProfile(UNIQUE_ID, null);
new CraftPlayerProfile(null, NAME);
new CraftPlayerProfile(UNIQUE_ID, NAME);
new CraftPlayerProfile(PlayerProfileTest.UNIQUE_ID, null);
new CraftPlayerProfile(null, PlayerProfileTest.NAME);
new CraftPlayerProfile(PlayerProfileTest.UNIQUE_ID, PlayerProfileTest.NAME);
}
@Test
@@ -100,49 +100,49 @@ public class PlayerProfileTest {
});
// Valid profiles:
CraftPlayerProfile profile1 = new CraftPlayerProfile(new GameProfile(UNIQUE_ID, NAME));
assertEquals(UNIQUE_ID, profile1.getUniqueId(), "Unique id is not the same");
assertEquals(NAME, profile1.getName(), "Name is not the same");
CraftPlayerProfile profile1 = new CraftPlayerProfile(new GameProfile(PlayerProfileTest.UNIQUE_ID, PlayerProfileTest.NAME));
assertEquals(PlayerProfileTest.UNIQUE_ID, profile1.getUniqueId(), "Unique id is not the same");
assertEquals(PlayerProfileTest.NAME, profile1.getName(), "Name is not the same");
CraftPlayerProfile profile2 = new CraftPlayerProfile(new GameProfile(UNIQUE_ID, ""));
assertEquals(UNIQUE_ID, profile2.getUniqueId(), "Unique id is not the same");
CraftPlayerProfile profile2 = new CraftPlayerProfile(new GameProfile(PlayerProfileTest.UNIQUE_ID, ""));
assertEquals(PlayerProfileTest.UNIQUE_ID, profile2.getUniqueId(), "Unique id is not the same");
assertEquals(null, profile2.getName(), "Name is not null");
CraftPlayerProfile profile3 = new CraftPlayerProfile(new GameProfile(SystemUtils.NIL_UUID, NAME));
CraftPlayerProfile profile3 = new CraftPlayerProfile(new GameProfile(Util.NIL_UUID, PlayerProfileTest.NAME));
assertEquals(null, profile3.getUniqueId(), "Unique id is not null");
assertEquals(NAME, profile3.getName(), "Name is not the same");
assertEquals(PlayerProfileTest.NAME, profile3.getName(), "Name is not the same");
}
@Test
public void testTexturesLoading() {
CraftPlayerProfile profile = buildPlayerProfile();
assertEquals(UNIQUE_ID, profile.getUniqueId(), "Unique id is not the same");
assertEquals(NAME, profile.getName(), "Name is not the same");
assertEquals(SKIN, profile.getTextures().getSkin(), "Skin url is not the same");
CraftPlayerProfile profile = PlayerProfileTest.buildPlayerProfile();
assertEquals(PlayerProfileTest.UNIQUE_ID, profile.getUniqueId(), "Unique id is not the same");
assertEquals(PlayerProfileTest.NAME, profile.getName(), "Name is not the same");
assertEquals(PlayerProfileTest.SKIN, profile.getTextures().getSkin(), "Skin url is not the same");
assertEquals(PlayerTextures.SkinModel.SLIM, profile.getTextures().getSkinModel(), "Skin model is not the same");
assertEquals(CAPE, profile.getTextures().getCape(), "Cape url is not the same");
assertEquals(TIMESTAMP, profile.getTextures().getTimestamp(), "Timestamp is not the same");
assertEquals(PlayerProfileTest.CAPE, profile.getTextures().getCape(), "Cape url is not the same");
assertEquals(PlayerProfileTest.TIMESTAMP, profile.getTextures().getTimestamp(), "Timestamp is not the same");
}
@Test
@EnableIfMojangServerAvailable
public void testBuildGameProfile() {
CraftPlayerProfile profile = buildPlayerProfile();
CraftPlayerProfile profile = PlayerProfileTest.buildPlayerProfile();
GameProfile gameProfile = profile.buildGameProfile();
assertNotNull(gameProfile, "GameProfile is null");
Property property = CraftPlayerProfile.getProperty(gameProfile, CraftPlayerTextures.PROPERTY_NAME);
assertNotNull(property, "Textures property is null");
assertEquals(VALUE, property.value(), "Property values are not the same");
assertEquals(NAME, gameProfile.getName(), "Names are not the same");
assertEquals(UNIQUE_ID, gameProfile.getId(), "Unique ids are not the same");
assertEquals(PlayerProfileTest.VALUE, property.value(), "Property values are not the same");
assertEquals(PlayerProfileTest.NAME, gameProfile.getName(), "Names are not the same");
assertEquals(PlayerProfileTest.UNIQUE_ID, gameProfile.getId(), "Unique ids are not the same");
assertTrue(property.hasSignature(), "Signature is missing");
assertTrue(CraftProfileProperty.hasValidSignature(property), "Signature is not valid");
}
@Test
public void testBuildGameProfileReturnsNewInstance() {
CraftPlayerProfile profile = buildPlayerProfile();
CraftPlayerProfile profile = PlayerProfileTest.buildPlayerProfile();
GameProfile gameProfile1 = profile.buildGameProfile();
GameProfile gameProfile2 = profile.buildGameProfile();
assertNotSame(gameProfile1, gameProfile2, "CraftPlayerProfile#buildGameProfile() does not produce a new instance");
@@ -151,13 +151,13 @@ public class PlayerProfileTest {
@Test
@EnableIfMojangServerAvailable
public void testSignatureValidation() {
CraftPlayerProfile profile = buildPlayerProfile();
CraftPlayerProfile profile = PlayerProfileTest.buildPlayerProfile();
assertTrue(profile.getTextures().isSigned(), "Signature is not valid");
}
@Test
public void testSignatureInvalidation() {
CraftPlayerProfile profile = buildPlayerProfile();
CraftPlayerProfile profile = PlayerProfileTest.buildPlayerProfile();
profile.getTextures().setSkin(null);
assertEquals(0L, profile.getTextures().getTimestamp(), "Textures has a timestamp");
assertFalse(profile.getTextures().isSigned(), "Textures signature is valid");
@@ -170,16 +170,16 @@ public class PlayerProfileTest {
@Test
public void testSetSkinResetsSkinModel() {
CraftPlayerProfile profile = buildPlayerProfile();
CraftPlayerProfile profile = PlayerProfileTest.buildPlayerProfile();
assertEquals(PlayerTextures.SkinModel.SLIM, profile.getTextures().getSkinModel(), "Skin model is not the same");
profile.getTextures().setSkin(SKIN);
profile.getTextures().setSkin(PlayerProfileTest.SKIN);
assertEquals(PlayerTextures.SkinModel.CLASSIC, profile.getTextures().getSkinModel(), "Skin model was not reset by skin change");
}
@Test
public void testSetTextures() {
CraftPlayerProfile profile = buildPlayerProfile();
CraftPlayerProfile profile2 = new CraftPlayerProfile(new GameProfile(UNIQUE_ID, NAME));
CraftPlayerProfile profile = PlayerProfileTest.buildPlayerProfile();
CraftPlayerProfile profile2 = new CraftPlayerProfile(new GameProfile(PlayerProfileTest.UNIQUE_ID, PlayerProfileTest.NAME));
assertFalse(profile.getTextures().isEmpty(), "profile has no textures");
assertTrue(profile2.getTextures().isEmpty(), "profile2 has textures");
@@ -196,7 +196,7 @@ public class PlayerProfileTest {
@Test
public void testClearTextures() {
CraftPlayerProfile profile = buildPlayerProfile();
CraftPlayerProfile profile = PlayerProfileTest.buildPlayerProfile();
assertFalse(profile.getTextures().isEmpty(), "profile has no textures");
profile.getTextures().clear();
@@ -207,19 +207,19 @@ public class PlayerProfileTest {
@Test
public void testCustomSkin() {
CraftPlayerProfile profile = new CraftPlayerProfile(UNIQUE_ID, NAME);
profile.getTextures().setSkin(SKIN);
assertEquals(COMPACT_VALUE, profile.getTextures().getProperty().value(), "profile with custom skin does not match expected value");
CraftPlayerProfile profile = new CraftPlayerProfile(PlayerProfileTest.UNIQUE_ID, PlayerProfileTest.NAME);
profile.getTextures().setSkin(PlayerProfileTest.SKIN);
assertEquals(PlayerProfileTest.COMPACT_VALUE, profile.getTextures().getProperty().value(), "profile with custom skin does not match expected value");
}
@Test
public void testEquals() {
CraftPlayerProfile profile1 = buildPlayerProfile();
CraftPlayerProfile profile2 = buildPlayerProfile();
CraftPlayerProfile profile3 = new CraftPlayerProfile(UNIQUE_ID, NAME);
CraftPlayerProfile profile4 = new CraftPlayerProfile(UNIQUE_ID, NAME);
CraftPlayerProfile profile5 = new CraftPlayerProfile(UNIQUE_ID, null);
CraftPlayerProfile profile6 = new CraftPlayerProfile(null, NAME);
CraftPlayerProfile profile1 = PlayerProfileTest.buildPlayerProfile();
CraftPlayerProfile profile2 = PlayerProfileTest.buildPlayerProfile();
CraftPlayerProfile profile3 = new CraftPlayerProfile(PlayerProfileTest.UNIQUE_ID, PlayerProfileTest.NAME);
CraftPlayerProfile profile4 = new CraftPlayerProfile(PlayerProfileTest.UNIQUE_ID, PlayerProfileTest.NAME);
CraftPlayerProfile profile5 = new CraftPlayerProfile(PlayerProfileTest.UNIQUE_ID, null);
CraftPlayerProfile profile6 = new CraftPlayerProfile(null, PlayerProfileTest.NAME);
assertEquals(profile1, profile2, "profile1 and profile2 are not equal");
assertEquals(profile3, profile4, "profile3 and profile4 are not equal");
@@ -230,8 +230,8 @@ public class PlayerProfileTest {
@Test
public void testTexturesEquals() {
CraftPlayerProfile profile1 = buildPlayerProfile();
CraftPlayerProfile profile2 = buildPlayerProfile();
CraftPlayerProfile profile1 = PlayerProfileTest.buildPlayerProfile();
CraftPlayerProfile profile2 = PlayerProfileTest.buildPlayerProfile();
assertEquals(profile1.getTextures(), profile2.getTextures(), "Profile textures are not equal");
profile1.getTextures().setCape(null);
@@ -243,19 +243,19 @@ public class PlayerProfileTest {
@Test
public void testClone() {
PlayerProfile profile = buildPlayerProfile();
PlayerProfile profile = PlayerProfileTest.buildPlayerProfile();
PlayerProfile copy = profile.clone();
assertEquals(profile, copy, "profile and copy are not equal");
// New copies are independent (don't affect the original profile):
copy.getTextures().setSkin(null);
assertEquals(SKIN, profile.getTextures().getSkin(), "copy is not independent");
assertEquals(PlayerProfileTest.SKIN, profile.getTextures().getSkin(), "copy is not independent");
}
@Test
public void testSerializationFullProfile() throws InvalidConfigurationException {
ConfigurationSerialization.registerClass(CraftPlayerProfile.class);
PlayerProfile playerProfile = buildPlayerProfile();
PlayerProfile playerProfile = PlayerProfileTest.buildPlayerProfile();
YamlConfiguration configuration = new YamlConfiguration();
configuration.set("test", playerProfile);

View File

@@ -1,9 +1,10 @@
package org.bukkit.craftbukkit.util;
import static org.junit.jupiter.api.Assertions.*;
import net.minecraft.network.chat.IChatBaseComponent;
import net.minecraft.network.chat.IChatMutableComponent;
import net.minecraft.network.chat.contents.LiteralContents;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.contents.PlainTextContents;
import org.bukkit.support.environment.Normal;
import org.junit.jupiter.api.Test;
@@ -13,29 +14,29 @@ public class CraftChatMessageTest {
@Test
public void testSimpleStrings() {
// These should be able to go from legacy to comp to legacy back without data changing
testString("§fFoo");
testString("§fFoo§f§l"); // Keeps empty format at end
testString("Foo");
this.testString("§fFoo");
this.testString("§fFoo§f§l"); // Keeps empty format at end
this.testString("Foo");
// testString("§r§oFoo"); // Retains reset at start (item names can use this to get rid of italics)
testString("Foo§bBar");
testString("F§loo§b§oBa§b§lr"); // any non color formatting code implies previous color code.
this.testString("Foo§bBar");
this.testString("F§loo§b§oBa§b§lr"); // any non color formatting code implies previous color code.
// So §l at start has no inherited color code, so that's fine, but the one at the end,
// while Ba§l would work visually, serializing back will include the implied color
testString("F§loo§rBa§lr"); // But if reset was used before.... then it can be standalone
testString("§fFoo§bBar");
testString("§fFoo§bBar§rBaz");
this.testString("F§loo§rBa§lr"); // But if reset was used before.... then it can be standalone
this.testString("§fFoo§bBar");
this.testString("§fFoo§bBar§rBaz");
}
@Test
public void testNewLineBehavior() {
// new line retain should stay as 1 comp
testString("Hello§0\n§rFoo\n§5Test", true);
testString("§0Foo!\n", true);
testString("§0Foo!§0\\n§0\\n§0Bar\n", true);
this.testString("Hello§0\n§rFoo\n§5Test", true);
this.testString("§0Foo!\n", true);
this.testString("§0Foo!§0\\n§0\\n§0Bar\n", true);
// dont retain line returns multiple components
IChatBaseComponent[] components = CraftChatMessage.fromString("Hello§0\n§rFoo\n§5Test");
Component[] components = CraftChatMessage.fromString("Hello§0\n§rFoo\n§5Test");
assertEquals(3, components.length, "Has 3 components");
assertEquals("Hello§0", CraftChatMessage.fromComponent(components[0]));
assertEquals(/*§r*/"Foo", CraftChatMessage.fromComponent(components[1]));
@@ -44,26 +45,26 @@ public class CraftChatMessageTest {
@Test
public void testComponents() {
testComponent("Foo§bBar§rBaz", create("Foo", "§bBar", "Baz"));
testComponent("§fFoo§bBar§rBaz", create("", "§fFoo", "§bBar", "Baz"));
testComponent("§fFoo§bBar§rBaz", create("", "§fFoo", "§bBar", "", "Baz"));
testComponent("§fFoo§bBar§rBaz", create("§fFoo", "§bBar", "Baz"));
testComponent("Foo§bBar§rBaz", create("", "Foo", "§bBar", "Baz"));
testComponent("§fFoo§bBar§rBaz", create("§fFoo", "§bBar", "Baz"));
testComponent("F§foo§bBar§rBaz", create("F§foo", "§bBar", "Baz"));
this.testComponent("Foo§bBar§rBaz", this.create("Foo", "§bBar", "Baz"));
this.testComponent("§fFoo§bBar§rBaz", this.create("", "§fFoo", "§bBar", "Baz"));
this.testComponent("§fFoo§bBar§rBaz", this.create("", "§fFoo", "§bBar", "", "Baz"));
this.testComponent("§fFoo§bBar§rBaz", this.create("§fFoo", "§bBar", "Baz"));
this.testComponent("Foo§bBar§rBaz", this.create("", "Foo", "§bBar", "Baz"));
this.testComponent("§fFoo§bBar§rBaz", this.create("§fFoo", "§bBar", "Baz"));
this.testComponent("F§foo§bBar§rBaz", this.create("F§foo", "§bBar", "Baz"));
}
@Test
public void testPlainText() {
testPlainString("");
testPlainString("Foo§f§mBar§0");
testPlainString("Link to https://www.spigotmc.org/ ...");
testPlainString("Link to http://www.spigotmc.org/ ...");
testPlainString("Link to www.spigotmc.org ...");
this.testPlainString("");
this.testPlainString("Foo§f§mBar§0");
this.testPlainString("Link to https://www.spigotmc.org/ ...");
this.testPlainString("Link to http://www.spigotmc.org/ ...");
this.testPlainString("Link to www.spigotmc.org ...");
}
private IChatBaseComponent create(String txt, String... rest) {
IChatMutableComponent cmp = CraftChatMessage.fromString(txt, false)[0].copy();
private Component create(String txt, String... rest) {
MutableComponent cmp = CraftChatMessage.fromString(txt, false)[0].copy();
for (String s : rest) {
cmp.append(CraftChatMessage.fromString(s, true)[0]);
}
@@ -72,44 +73,44 @@ public class CraftChatMessageTest {
}
private void testString(String expected) {
testString(expected, false);
this.testString(expected, false);
}
private void testString(String expected, boolean keepNewLines) {
testString(expected, expected, keepNewLines);
this.testString(expected, expected, keepNewLines);
}
private void testString(String input, String expected) {
testString(input, expected, false);
this.testString(input, expected, false);
}
private void testString(String input, String expected, boolean keepNewLines) {
IChatBaseComponent cmp = CraftChatMessage.fromString(input, keepNewLines)[0];
Component cmp = CraftChatMessage.fromString(input, keepNewLines)[0];
String actual = CraftChatMessage.fromComponent(cmp);
assertEquals(expected, actual, "\nComponent: " + cmp + "\n");
}
private void testPlainString(String expected) {
IChatBaseComponent component = CraftChatMessage.fromString(expected, false, true)[0];
Component component = CraftChatMessage.fromString(expected, false, true)[0];
String actual = CraftChatMessage.fromComponent(component);
assertEquals(expected, actual, "fromComponent does not match input: " + component);
assertFalse(containsNonPlainComponent(component), "Non-plain component: " + component);
assertFalse(this.containsNonPlainComponent(component), "Non-plain component: " + component);
}
private boolean containsNonPlainComponent(IChatBaseComponent component) {
for (IChatBaseComponent c : component) {
if (c.getContents() != LiteralContents.EMPTY && !(c.getContents() instanceof LiteralContents)) {
private boolean containsNonPlainComponent(Component component) {
for (Component c : component) {
if (c.getContents() != PlainTextContents.EMPTY && !(c.getContents() instanceof PlainTextContents)) {
return true;
}
}
return false;
}
private void testComponent(String expected, IChatBaseComponent cmp) {
private void testComponent(String expected, Component cmp) {
String actual = CraftChatMessage.fromComponent(cmp);
assertEquals(expected, actual, "\nComponent: " + cmp + "\n");
IChatBaseComponent expectedCmp = CraftChatMessage.fromString(expected, true)[0];
Component expectedCmp = CraftChatMessage.fromString(expected, true)[0];
String actualExpectedCmp = CraftChatMessage.fromComponent(expectedCmp);
assertEquals(expected, actualExpectedCmp, "\nComponent: " + expectedCmp + "\n");
}

View File

@@ -1,7 +1,8 @@
package org.bukkit.entity;
import static org.junit.jupiter.api.Assertions.*;
import net.minecraft.world.entity.boss.enderdragon.phases.DragonControllerPhase;
import net.minecraft.world.entity.boss.enderdragon.phases.EnderDragonPhase;
import org.bukkit.craftbukkit.entity.CraftEnderDragon;
import org.bukkit.support.environment.Normal;
import org.junit.jupiter.api.Test;
@@ -12,7 +13,7 @@ public class EnderDragonPhaseTest {
@Test
public void testNotNull() {
for (EnderDragon.Phase phase : EnderDragon.Phase.values()) {
DragonControllerPhase dragonControllerPhase = CraftEnderDragon.getMinecraftPhase(phase);
EnderDragonPhase dragonControllerPhase = CraftEnderDragon.getMinecraftPhase(phase);
assertNotNull(dragonControllerPhase, phase.name());
assertNotNull(CraftEnderDragon.getBukkitPhase(dragonControllerPhase), phase.name());
}
@@ -20,31 +21,31 @@ public class EnderDragonPhaseTest {
@Test
public void testBukkitToMinecraft() {
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.CIRCLING), DragonControllerPhase.HOLDING_PATTERN, "CIRCLING");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.STRAFING), DragonControllerPhase.STRAFE_PLAYER, "STRAFING");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.FLY_TO_PORTAL), DragonControllerPhase.LANDING_APPROACH, "FLY_TO_PORTAL");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.LAND_ON_PORTAL), DragonControllerPhase.LANDING, "LAND_ON_PORTAL");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.LEAVE_PORTAL), DragonControllerPhase.TAKEOFF, "LEAVE_PORTAL");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.BREATH_ATTACK), DragonControllerPhase.SITTING_FLAMING, "BREATH_ATTACK");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.SEARCH_FOR_BREATH_ATTACK_TARGET), DragonControllerPhase.SITTING_SCANNING, "SEARCH_FOR_BREATH_ATTACK_TARGET");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.ROAR_BEFORE_ATTACK), DragonControllerPhase.SITTING_ATTACKING, "ROAR_BEFORE_ATTACK");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.CHARGE_PLAYER), DragonControllerPhase.CHARGING_PLAYER, "CHARGE_PLAYER");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.DYING), DragonControllerPhase.DYING, "DYING");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.HOVER), DragonControllerPhase.HOVERING, "HOVER");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.CIRCLING), EnderDragonPhase.HOLDING_PATTERN, "CIRCLING");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.STRAFING), EnderDragonPhase.STRAFE_PLAYER, "STRAFING");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.FLY_TO_PORTAL), EnderDragonPhase.LANDING_APPROACH, "FLY_TO_PORTAL");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.LAND_ON_PORTAL), EnderDragonPhase.LANDING, "LAND_ON_PORTAL");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.LEAVE_PORTAL), EnderDragonPhase.TAKEOFF, "LEAVE_PORTAL");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.BREATH_ATTACK), EnderDragonPhase.SITTING_FLAMING, "BREATH_ATTACK");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.SEARCH_FOR_BREATH_ATTACK_TARGET), EnderDragonPhase.SITTING_SCANNING, "SEARCH_FOR_BREATH_ATTACK_TARGET");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.ROAR_BEFORE_ATTACK), EnderDragonPhase.SITTING_ATTACKING, "ROAR_BEFORE_ATTACK");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.CHARGE_PLAYER), EnderDragonPhase.CHARGING_PLAYER, "CHARGE_PLAYER");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.DYING), EnderDragonPhase.DYING, "DYING");
assertEquals(CraftEnderDragon.getMinecraftPhase(EnderDragon.Phase.HOVER), EnderDragonPhase.HOVERING, "HOVER");
}
@Test
public void testMinecraftToBukkit() {
assertEquals(CraftEnderDragon.getBukkitPhase(DragonControllerPhase.HOLDING_PATTERN), EnderDragon.Phase.CIRCLING, "CIRCLING");
assertEquals(CraftEnderDragon.getBukkitPhase(DragonControllerPhase.STRAFE_PLAYER), EnderDragon.Phase.STRAFING, "STRAFING");
assertEquals(CraftEnderDragon.getBukkitPhase(DragonControllerPhase.LANDING_APPROACH), EnderDragon.Phase.FLY_TO_PORTAL, "FLY_TO_PORTAL");
assertEquals(CraftEnderDragon.getBukkitPhase(DragonControllerPhase.LANDING), EnderDragon.Phase.LAND_ON_PORTAL, "LAND_ON_PORTAL");
assertEquals(CraftEnderDragon.getBukkitPhase(DragonControllerPhase.TAKEOFF), EnderDragon.Phase.LEAVE_PORTAL, "LEAVE_PORTAL");
assertEquals(CraftEnderDragon.getBukkitPhase(DragonControllerPhase.SITTING_FLAMING), EnderDragon.Phase.BREATH_ATTACK, "BREATH_ATTACK");
assertEquals(CraftEnderDragon.getBukkitPhase(DragonControllerPhase.SITTING_SCANNING), EnderDragon.Phase.SEARCH_FOR_BREATH_ATTACK_TARGET, "SEARCH_FOR_BREATH_ATTACK_TARGET");
assertEquals(CraftEnderDragon.getBukkitPhase(DragonControllerPhase.SITTING_ATTACKING), EnderDragon.Phase.ROAR_BEFORE_ATTACK, "ROAR_BEFORE_ATTACK");
assertEquals(CraftEnderDragon.getBukkitPhase(DragonControllerPhase.CHARGING_PLAYER), EnderDragon.Phase.CHARGE_PLAYER, "CHARGE_PLAYER");
assertEquals(CraftEnderDragon.getBukkitPhase(DragonControllerPhase.DYING), EnderDragon.Phase.DYING, "DYING");
assertEquals(CraftEnderDragon.getBukkitPhase(DragonControllerPhase.HOVERING), EnderDragon.Phase.HOVER, "HOVER");
assertEquals(CraftEnderDragon.getBukkitPhase(EnderDragonPhase.HOLDING_PATTERN), EnderDragon.Phase.CIRCLING, "CIRCLING");
assertEquals(CraftEnderDragon.getBukkitPhase(EnderDragonPhase.STRAFE_PLAYER), EnderDragon.Phase.STRAFING, "STRAFING");
assertEquals(CraftEnderDragon.getBukkitPhase(EnderDragonPhase.LANDING_APPROACH), EnderDragon.Phase.FLY_TO_PORTAL, "FLY_TO_PORTAL");
assertEquals(CraftEnderDragon.getBukkitPhase(EnderDragonPhase.LANDING), EnderDragon.Phase.LAND_ON_PORTAL, "LAND_ON_PORTAL");
assertEquals(CraftEnderDragon.getBukkitPhase(EnderDragonPhase.TAKEOFF), EnderDragon.Phase.LEAVE_PORTAL, "LEAVE_PORTAL");
assertEquals(CraftEnderDragon.getBukkitPhase(EnderDragonPhase.SITTING_FLAMING), EnderDragon.Phase.BREATH_ATTACK, "BREATH_ATTACK");
assertEquals(CraftEnderDragon.getBukkitPhase(EnderDragonPhase.SITTING_SCANNING), EnderDragon.Phase.SEARCH_FOR_BREATH_ATTACK_TARGET, "SEARCH_FOR_BREATH_ATTACK_TARGET");
assertEquals(CraftEnderDragon.getBukkitPhase(EnderDragonPhase.SITTING_ATTACKING), EnderDragon.Phase.ROAR_BEFORE_ATTACK, "ROAR_BEFORE_ATTACK");
assertEquals(CraftEnderDragon.getBukkitPhase(EnderDragonPhase.CHARGING_PLAYER), EnderDragon.Phase.CHARGE_PLAYER, "CHARGE_PLAYER");
assertEquals(CraftEnderDragon.getBukkitPhase(EnderDragonPhase.DYING), EnderDragon.Phase.DYING, "DYING");
assertEquals(CraftEnderDragon.getBukkitPhase(EnderDragonPhase.HOVERING), EnderDragon.Phase.HOVER, "HOVER");
}
}

View File

@@ -1,7 +1,8 @@
package org.bukkit.entity;
import static org.junit.jupiter.api.Assertions.*;
import net.minecraft.world.entity.EntityPose;
import net.minecraft.world.entity.Pose;
import org.bukkit.support.environment.Normal;
import org.junit.jupiter.api.Test;
@@ -11,14 +12,14 @@ public class EntityPoseTest {
@Test
public void testBukkitToMinecraft() {
for (Pose pose : Pose.values()) {
assertNotNull(EntityPose.values()[pose.ordinal()], pose.name());
assertNotNull(Pose.values()[pose.ordinal()], pose.name());
}
}
@Test
public void testMinecraftToBukkit() {
for (EntityPose entityPose : EntityPose.values()) {
assertNotNull(Pose.values()[entityPose.ordinal()], entityPose.name());
for (Pose entityPose : Pose.values()) {
assertNotNull(org.bukkit.entity.Pose.values()[entityPose.ordinal()], entityPose.name());
}
}
}

View File

@@ -5,8 +5,8 @@ import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.world.entity.EntityTypes;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityType;
import org.bukkit.support.environment.AllFeatures;
import org.junit.jupiter.api.Test;
@@ -17,10 +17,10 @@ public class EntityTypesTest {
public void testMaps() {
Set<EntityType> allBukkit = Arrays.stream(EntityType.values()).filter((b) -> b.getName() != null).collect(Collectors.toSet());
for (EntityTypes<?> nms : BuiltInRegistries.ENTITY_TYPE) {
MinecraftKey key = EntityTypes.getKey(nms);
for (EntityType<?> nms : BuiltInRegistries.ENTITY_TYPE) {
ResourceLocation key = EntityType.getKey(nms);
EntityType bukkit = EntityType.fromName(key.getPath());
org.bukkit.entity.EntityType bukkit = org.bukkit.entity.EntityType.fromName(key.getPath());
assertNotNull(bukkit, "Missing nms->bukkit " + key);
assertTrue(allBukkit.remove(bukkit), "Duplicate entity nms->" + bukkit);
@@ -31,7 +31,7 @@ public class EntityTypesTest {
@Test
public void testTranslationKey() {
for (EntityType entityType : EntityType.values()) {
for (org.bukkit.entity.EntityType entityType : org.bukkit.entity.EntityType.values()) {
// Currently EntityType#getTranslationKey has a validation for null name then for test skip this and check correct names.
if (entityType.getName() != null) {
assertNotNull(entityType.getTranslationKey(), "Nulllable translation key for " + entityType);

View File

@@ -1,7 +1,8 @@
package org.bukkit.entity;
import static org.junit.jupiter.api.Assertions.*;
import net.minecraft.world.entity.animal.EntityPanda;
import net.minecraft.world.entity.animal.Panda;
import org.bukkit.craftbukkit.entity.CraftPanda;
import org.bukkit.support.environment.Normal;
import org.junit.jupiter.api.Test;
@@ -12,7 +13,7 @@ public class PandaGeneTest {
@Test
public void testBukkit() {
for (Panda.Gene gene : Panda.Gene.values()) {
EntityPanda.Gene nms = CraftPanda.toNms(gene);
Panda.Gene nms = CraftPanda.toNms(gene);
assertNotNull(nms, "NMS gene null for " + gene);
assertEquals(gene.isRecessive(), nms.isRecessive(), "Recessive status did not match " + gene);
@@ -22,8 +23,8 @@ public class PandaGeneTest {
@Test
public void testNMS() {
for (EntityPanda.Gene gene : EntityPanda.Gene.values()) {
Panda.Gene bukkit = CraftPanda.fromNms(gene);
for (Panda.Gene gene : Panda.Gene.values()) {
org.bukkit.entity.Panda.Gene bukkit = CraftPanda.fromNms(gene);
assertNotNull(bukkit, "Bukkit gene null for " + gene);
assertEquals(gene.isRecessive(), bukkit.isRecessive(), "Recessive status did not match " + gene);

View File

@@ -1,6 +1,6 @@
package org.bukkit.entity;
import net.minecraft.world.entity.EnumCreatureType;
import net.minecraft.world.entity.MobCategory;
import org.bukkit.craftbukkit.util.CraftSpawnCategory;
import org.bukkit.support.environment.Normal;
import org.junit.jupiter.api.Test;
@@ -10,7 +10,7 @@ public class SpawnCategoryTest {
@Test
public void testMatch() {
for (EnumCreatureType enumCreatureType : EnumCreatureType.values()) {
for (MobCategory enumCreatureType : MobCategory.values()) {
// If it is missing a convert to Bukkit then throw a UnsupportedOperationException
SpawnCategory spawnCategory = CraftSpawnCategory.toBukkit(enumCreatureType);
@@ -23,7 +23,7 @@ public class SpawnCategoryTest {
for (SpawnCategory spawnCategory : SpawnCategory.values()) {
// If it is missing a convert to NMS then throw a UnsupportedOperationException
EnumCreatureType enumCreatureType = CraftSpawnCategory.toNMS(spawnCategory);
MobCategory enumCreatureType = CraftSpawnCategory.toNMS(spawnCategory);
}
}
}

View File

@@ -13,28 +13,28 @@ public class TropicalFishTest {
@Test
public void testVariants() {
testVariant(65536, DyeColor.ORANGE, DyeColor.WHITE, Pattern.KOB);
testVariant(917504, DyeColor.RED, DyeColor.WHITE, Pattern.KOB);
testVariant(918273, DyeColor.RED, DyeColor.WHITE, Pattern.BLOCKFISH);
testVariant(918529, DyeColor.RED, DyeColor.WHITE, Pattern.BETTY);
testVariant(16778497, DyeColor.WHITE, DyeColor.ORANGE, Pattern.CLAYFISH);
testVariant(50660352, DyeColor.LIME, DyeColor.LIGHT_BLUE, Pattern.BRINELY);
testVariant(50726144, DyeColor.PINK, DyeColor.LIGHT_BLUE, Pattern.SPOTTY);
testVariant(50790656, DyeColor.GRAY, DyeColor.LIGHT_BLUE, Pattern.SUNSTREAK);
testVariant(67108865, DyeColor.WHITE, DyeColor.YELLOW, Pattern.FLOPPER);
testVariant(67110144, DyeColor.WHITE, DyeColor.YELLOW, Pattern.SPOTTY);
testVariant(67371265, DyeColor.YELLOW, DyeColor.YELLOW, Pattern.STRIPEY);
testVariant(67764993, DyeColor.PURPLE, DyeColor.YELLOW, Pattern.BLOCKFISH);
testVariant(101253888, DyeColor.CYAN, DyeColor.PINK, Pattern.DASHER);
testVariant(117441025, DyeColor.WHITE, DyeColor.GRAY, Pattern.GLITTER);
testVariant(117441280, DyeColor.WHITE, DyeColor.GRAY, Pattern.DASHER);
testVariant(117441536, DyeColor.WHITE, DyeColor.GRAY, Pattern.BRINELY);
testVariant(117506305, DyeColor.ORANGE, DyeColor.GRAY, Pattern.STRIPEY);
testVariant(117899265, DyeColor.GRAY, DyeColor.GRAY, Pattern.FLOPPER);
testVariant(118161664, DyeColor.BLUE, DyeColor.GRAY, Pattern.SUNSTREAK);
testVariant(134217984, DyeColor.WHITE, DyeColor.LIGHT_GRAY, Pattern.SUNSTREAK);
testVariant(234882305, DyeColor.WHITE, DyeColor.RED, Pattern.CLAYFISH);
testVariant(235340288, DyeColor.GRAY, DyeColor.RED, Pattern.SNOOPER);
this.testVariant(65536, DyeColor.ORANGE, DyeColor.WHITE, Pattern.KOB);
this.testVariant(917504, DyeColor.RED, DyeColor.WHITE, Pattern.KOB);
this.testVariant(918273, DyeColor.RED, DyeColor.WHITE, Pattern.BLOCKFISH);
this.testVariant(918529, DyeColor.RED, DyeColor.WHITE, Pattern.BETTY);
this.testVariant(16778497, DyeColor.WHITE, DyeColor.ORANGE, Pattern.CLAYFISH);
this.testVariant(50660352, DyeColor.LIME, DyeColor.LIGHT_BLUE, Pattern.BRINELY);
this.testVariant(50726144, DyeColor.PINK, DyeColor.LIGHT_BLUE, Pattern.SPOTTY);
this.testVariant(50790656, DyeColor.GRAY, DyeColor.LIGHT_BLUE, Pattern.SUNSTREAK);
this.testVariant(67108865, DyeColor.WHITE, DyeColor.YELLOW, Pattern.FLOPPER);
this.testVariant(67110144, DyeColor.WHITE, DyeColor.YELLOW, Pattern.SPOTTY);
this.testVariant(67371265, DyeColor.YELLOW, DyeColor.YELLOW, Pattern.STRIPEY);
this.testVariant(67764993, DyeColor.PURPLE, DyeColor.YELLOW, Pattern.BLOCKFISH);
this.testVariant(101253888, DyeColor.CYAN, DyeColor.PINK, Pattern.DASHER);
this.testVariant(117441025, DyeColor.WHITE, DyeColor.GRAY, Pattern.GLITTER);
this.testVariant(117441280, DyeColor.WHITE, DyeColor.GRAY, Pattern.DASHER);
this.testVariant(117441536, DyeColor.WHITE, DyeColor.GRAY, Pattern.BRINELY);
this.testVariant(117506305, DyeColor.ORANGE, DyeColor.GRAY, Pattern.STRIPEY);
this.testVariant(117899265, DyeColor.GRAY, DyeColor.GRAY, Pattern.FLOPPER);
this.testVariant(118161664, DyeColor.BLUE, DyeColor.GRAY, Pattern.SUNSTREAK);
this.testVariant(134217984, DyeColor.WHITE, DyeColor.LIGHT_GRAY, Pattern.SUNSTREAK);
this.testVariant(234882305, DyeColor.WHITE, DyeColor.RED, Pattern.CLAYFISH);
this.testVariant(235340288, DyeColor.GRAY, DyeColor.RED, Pattern.SNOOPER);
}
private void testVariant(int variant, DyeColor bodyColor, DyeColor patternColor, Pattern pattern) {

View File

@@ -45,7 +45,7 @@ public class EntityRemoveEventTest {
if (instruction instanceof MethodInsnNode methodInsnNode) {
// Check for discard and remove method call
if (check(methodInsnNode.owner, methodInsnNode.name, methodInsnNode.desc)) {
if (this.check(methodInsnNode.owner, methodInsnNode.name, methodInsnNode.desc)) {
// Add to list
missingReason.add(String.format("Method name: %s, name: %s, line number: %s", methodNode.name, methodInsnNode.name, lastLineNumber.line));
}
@@ -58,7 +58,7 @@ public class EntityRemoveEventTest {
Handle handle = (Handle) dynamicInsnNode.bsmArgs[1];
if (check(handle.getOwner(), handle.getName(), handle.getDesc())) {
if (this.check(handle.getOwner(), handle.getName(), handle.getDesc())) {
// Add to list
missingReason.add(String.format("[D] Method name: %s, name: %s, line number: %s", methodNode.name, handle.getName(), lastLineNumber.line));
}
@@ -93,7 +93,7 @@ public class EntityRemoveEventTest {
private boolean check(String owner, String name, String desc) throws ClassNotFoundException {
if (!name.equals("discard") && !name.equals("remove") && !name.equals("setRemoved")) {
if (!checkExtraMethod(owner, name, desc)) {
if (!this.checkExtraMethod(owner, name, desc)) {
return false;
}
}
@@ -102,7 +102,7 @@ public class EntityRemoveEventTest {
return false;
}
Class<?> ownerClass = Class.forName(owner.replace('/', '.'), false, getClass().getClassLoader());
Class<?> ownerClass = Class.forName(owner.replace('/', '.'), false, this.getClass().getClassLoader());
// Found missing discard, remove or setRemoved method call
return EntityAccess.class.isAssignableFrom(ownerClass);

View File

@@ -4,9 +4,8 @@ import static org.junit.jupiter.api.Assertions.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Locale;
import net.minecraft.core.IRegistry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.resources.ResourceLocation;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.craftbukkit.CraftRegistry;
@@ -34,9 +33,9 @@ public class StructureTest {
@Test
public void testMinecraftToBukkitFieldName() {
IRegistry<net.minecraft.world.level.levelgen.structure.Structure> structureBuiltInRegistries = CraftRegistry.getMinecraftRegistry(Registries.STRUCTURE);
net.minecraft.core.Registry<net.minecraft.world.level.levelgen.structure.Structure> structureBuiltInRegistries = CraftRegistry.getMinecraftRegistry(Registries.STRUCTURE);
for (net.minecraft.world.level.levelgen.structure.Structure structure : structureBuiltInRegistries) {
MinecraftKey minecraftKey = structureBuiltInRegistries.getKey(structure);
ResourceLocation minecraftKey = structureBuiltInRegistries.getKey(structure);
try {
Structure bukkit = (Structure) Structure.class.getField(minecraftKey.getPath().toUpperCase(Locale.ROOT)).get(null);

View File

@@ -6,7 +6,7 @@ import java.lang.reflect.Modifier;
import java.util.Locale;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.resources.ResourceLocation;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
import org.bukkit.craftbukkit.CraftRegistry;
@@ -35,7 +35,7 @@ public class StructureTypeTest {
@Test
public void testMinecraftToBukkitFieldName() {
for (net.minecraft.world.level.levelgen.structure.StructureType<?> structureType : CraftRegistry.getMinecraftRegistry(Registries.STRUCTURE_TYPE)) {
MinecraftKey minecraftKey = BuiltInRegistries.STRUCTURE_TYPE.getKey(structureType);
ResourceLocation minecraftKey = BuiltInRegistries.STRUCTURE_TYPE.getKey(structureType);
try {
StructureType bukkit = (StructureType) StructureType.class.getField(minecraftKey.getPath().toUpperCase(Locale.ROOT)).get(null);

View File

@@ -5,7 +5,7 @@ import java.awt.Color;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.world.level.material.MaterialMapColor;
import net.minecraft.world.level.material.MapColor;
import org.bukkit.craftbukkit.map.CraftMapColorCache;
import org.bukkit.support.environment.Normal;
import org.bukkit.support.environment.Slow;
@@ -20,7 +20,7 @@ public class MapTest {
@Test
@Normal
public void testColors() {
MaterialMapColor[] nmsColors = MaterialMapColor.MATERIAL_COLORS;
MapColor[] nmsColors = MapColor.MATERIAL_COLORS;
Color[] bukkitColors = MapPalette.colors;
boolean fail = false;
@@ -35,23 +35,23 @@ public class MapTest {
int b = rgb & 0xFF;
if (i + 1 > bukkitColors.length / 4) {
for (int modi : modifiers) {
for (int modi : MapTest.modifiers) {
int mr = (r * modi) / 255;
int mg = (g * modi) / 255;
int mb = (b * modi) / 255;
logger.log(Level.WARNING, "Missing color (check CraftMapView#render and update md5 hash in CraftMapColorCache): c({0}, {1}, {2})", new Object[]{mr, mg, mb});
MapTest.logger.log(Level.WARNING, "Missing color (check CraftMapView#render and update md5 hash in CraftMapColorCache): c({0}, {1}, {2})", new Object[]{mr, mg, mb});
}
fail = true;
} else {
for (int j = 0; j < modifiers.length; j++) {
int modi = modifiers[j];
for (int j = 0; j < MapTest.modifiers.length; j++) {
int modi = MapTest.modifiers[j];
Color bukkit = bukkitColors[i * 4 + j];
int mr = (r * modi) / 255;
int mg = (g * modi) / 255;
int mb = (b * modi) / 255;
if (bukkit.getRed() != mr || bukkit.getGreen() != mg || bukkit.getBlue() != mb) {
logger.log(Level.WARNING, "Incorrect color: {6} {7} c({0}, {1}, {2}) != c({3}, {4}, {5})", new Object[]{
MapTest.logger.log(Level.WARNING, "Incorrect color: {6} {7} c({0}, {1}, {2}) != c({3}, {4}, {5})", new Object[]{
bukkit.getRed(), bukkit.getGreen(), bukkit.getBlue(),
mr, mg, mb,
i, j
@@ -67,7 +67,7 @@ public class MapTest {
@Test
@Slow("Test takes around 25 seconds, should be run by changes to the map color conversion")
public void testMapColorCacheBuilding() throws ExecutionException, InterruptedException {
CraftMapColorCache craftMapColorCache = new CraftMapColorCache(logger);
CraftMapColorCache craftMapColorCache = new CraftMapColorCache(MapTest.logger);
craftMapColorCache.initCache().get();
for (int r = 0; r < 256; r++) {

View File

@@ -5,10 +5,10 @@ import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectList;
import net.minecraft.world.item.alchemy.PotionRegistry;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.item.alchemy.Potion;
import org.bukkit.craftbukkit.legacy.FieldRename;
import org.bukkit.craftbukkit.potion.CraftPotionEffectType;
import org.bukkit.support.environment.AllFeatures;
@@ -19,8 +19,8 @@ public class PotionTest {
@Test
public void testEffectCompleteness() throws Throwable {
Map<PotionType, String> effects = new EnumMap(PotionType.class);
for (PotionRegistry reg : BuiltInRegistries.POTION) {
List<MobEffect> eff = reg.getEffects();
for (Potion reg : BuiltInRegistries.POTION) {
List<MobEffectInstance> eff = reg.getEffects();
if (eff.size() != 1) continue;
PotionEffectType type = CraftPotionEffectType.minecraftHolderToBukkit(eff.get(0).getEffect());
assertNotNull(type, String.valueOf(reg));
@@ -36,8 +36,8 @@ public class PotionTest {
@Test
public void testEffectType() {
for (MobEffectList nms : BuiltInRegistries.MOB_EFFECT) {
MinecraftKey key = BuiltInRegistries.MOB_EFFECT.getKey(nms);
for (MobEffect nms : BuiltInRegistries.MOB_EFFECT) {
ResourceLocation key = BuiltInRegistries.MOB_EFFECT.getKey(nms);
PotionEffectType bukkit = CraftPotionEffectType.minecraftToBukkit(nms);

View File

@@ -23,7 +23,7 @@ public class PerRegistryTest {
@BeforeAll
public static void init() {
random = new Random();
PerRegistryTest.random = new Random();
}
public static Stream<Arguments> data() {
@@ -63,12 +63,12 @@ public class PerRegistryTest {
registry.forEach(element -> {
NamespacedKey key = element.getKey();
assertSameMatchWithKeyMessage(registry, element, key.toString()); // namespace:key
assertSameMatchWithKeyMessage(registry, element, key.getKey()); // key
assertSameMatchWithKeyMessage(registry, element, key.toString().replace('_', ' ')); // namespace:key with space
assertSameMatchWithKeyMessage(registry, element, key.getKey().replace('_', ' ')); // key with space
assertSameMatchWithKeyMessage(registry, element, randomizeCase(key.toString())); // nAmeSPaCe:kEY
assertSameMatchWithKeyMessage(registry, element, randomizeCase(key.getKey())); // kEy
this.assertSameMatchWithKeyMessage(registry, element, key.toString()); // namespace:key
this.assertSameMatchWithKeyMessage(registry, element, key.getKey()); // key
this.assertSameMatchWithKeyMessage(registry, element, key.toString().replace('_', ' ')); // namespace:key with space
this.assertSameMatchWithKeyMessage(registry, element, key.getKey().replace('_', ' ')); // key with space
this.assertSameMatchWithKeyMessage(registry, element, this.randomizeCase(key.toString())); // nAmeSPaCe:kEY
this.assertSameMatchWithKeyMessage(registry, element, this.randomizeCase(key.getKey())); // kEy
});
}
@@ -82,7 +82,7 @@ public class PerRegistryTest {
for (int i = 0; i < size; i++) {
char character = input.charAt(i);
builder.append(random.nextBoolean() ? Character.toUpperCase(character) : character);
builder.append(PerRegistryTest.random.nextBoolean() ? Character.toUpperCase(character) : character);
}
return builder.toString();

View File

@@ -23,10 +23,9 @@ import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Logger;
import java.util.stream.Stream;
import net.minecraft.core.IRegistry;
import net.minecraft.core.IRegistryCustom;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.flag.FeatureElement;
import net.minecraft.world.flag.FeatureFlags;
import org.bukkit.Bukkit;
@@ -62,26 +61,26 @@ public class RegistryClassTest {
private static final Map<Class<? extends Keyed>, Data> INIT_DATA = new HashMap<>();
private static final List<Arguments> FIELD_DATA_CACHE = new ArrayList<>();
private static IRegistryCustom.Dimension vanilla_registry;
private static RegistryAccess.Frozen vanilla_registry;
public static Stream<Arguments> fieldData() {
return FIELD_DATA_CACHE.stream();
return RegistryClassTest.FIELD_DATA_CACHE.stream();
}
@BeforeAll
public static void init() {
initValueClasses();
initFieldDataCache();
RegistryClassTest.initValueClasses();
RegistryClassTest.initFieldDataCache();
}
@AfterAll
public static void cleanUp() {
INIT_DATA.clear();
FIELD_DATA_CACHE.clear();
RegistryClassTest.INIT_DATA.clear();
RegistryClassTest.FIELD_DATA_CACHE.clear();
}
private static void initValueClasses() {
vanilla_registry = RegistryHelper.createRegistry(FeatureFlags.VANILLA_SET);
RegistryClassTest.vanilla_registry = RegistryHelper.createRegistry(FeatureFlags.VANILLA_SET);
Map<Class<? extends Keyed>, List<NamespacedKey>> outsideRequest = new LinkedHashMap<>();
@@ -183,13 +182,13 @@ public class RegistryClassTest {
private static void initFieldDataCache() {
RegistriesArgumentProvider.getData().map(arguments -> {
Class<? extends Keyed> type = (Class<? extends Keyed>) arguments.get()[0];
Map<String, List<Class<? extends Annotation>>> annotations = getFieldAnnotations(type);
Map<String, List<Class<? extends Annotation>>> annotations = RegistryClassTest.getFieldAnnotations(type);
List<FieldData> fields = new ArrayList<>();
for (Field field : type.getFields()) {
// We ignore each field that does not have the class itself as its type,
// is not static, public, or is deprecated.
if (!isValidField(type, field)) {
if (!RegistryClassTest.isValidField(type, field)) {
continue;
}
@@ -258,7 +257,7 @@ public class RegistryClassTest {
@RegistriesTest
public <T extends Keyed> void testOutsideRequests(Class<T> type) {
Data data = INIT_DATA.get(type);
Data data = RegistryClassTest.INIT_DATA.get(type);
assertNotNull(data, String.format("No data present for %s. This should never happen since the same data source is used.\n"
+ "Something has gone horribly wrong.", type));
@@ -288,7 +287,7 @@ public class RegistryClassTest {
@RegistriesTest
public <T extends Keyed> void testNoNullValuePresent(Class<T> type) {
Data data = INIT_DATA.get(type);
Data data = RegistryClassTest.INIT_DATA.get(type);
assertNotNull(data, String.format("No data present for %s. This should never happen since the same data source is used.\n"
+ "Something has gone horribly wrong.", type));
@@ -308,7 +307,7 @@ public class RegistryClassTest {
for (Field field : type.getFields()) {
// We ignore each field that does not have the class itself as its type, is not static, public, or is deprecated.
if (!isValidField(type, field)) {
if (!RegistryClassTest.isValidField(type, field)) {
continue;
}
@@ -330,7 +329,7 @@ public class RegistryClassTest {
@ParameterizedTest
@MethodSource("fieldData")
public <T extends Keyed> void testExcessExperimentalAnnotation(Class<T> type, ResourceKey<IRegistry<?>> registryKey, List<FieldData> fieldDataList) throws IllegalAccessException {
public <T extends Keyed> void testExcessExperimentalAnnotation(Class<T> type, ResourceKey<net.minecraft.core.Registry<?>> registryKey, List<FieldData> fieldDataList) throws IllegalAccessException {
List<Field> excess = new ArrayList<>();
for (FieldData fieldData : fieldDataList) {
@@ -339,7 +338,7 @@ public class RegistryClassTest {
continue;
}
IRegistry<?> registry = vanilla_registry.lookupOrThrow(registryKey);
net.minecraft.core.Registry<?> registry = RegistryClassTest.vanilla_registry.lookupOrThrow(registryKey);
Optional<?> optionalValue = registry.getOptional(CraftNamespacedKey.toMinecraft(((Keyed) fieldData.field().get(null)).getKey()));
@@ -367,8 +366,8 @@ public class RegistryClassTest {
@ParameterizedTest
@MethodSource("fieldData")
public <T extends Keyed> void testMissingExperimentalAnnotation(Class<T> type, ResourceKey<IRegistry<?>> registryKey, List<FieldData> fieldDataList) throws IllegalAccessException {
IRegistry<?> registry = vanilla_registry.lookupOrThrow(registryKey);
public <T extends Keyed> void testMissingExperimentalAnnotation(Class<T> type, ResourceKey<net.minecraft.core.Registry<?>> registryKey, List<FieldData> fieldDataList) throws IllegalAccessException {
net.minecraft.core.Registry<?> registry = RegistryClassTest.vanilla_registry.lookupOrThrow(registryKey);
List<Field> missing = new ArrayList<>();
for (FieldData fieldData : fieldDataList) {
@@ -402,10 +401,10 @@ public class RegistryClassTest {
@ParameterizedTest
@MethodSource("fieldData")
public <T extends Keyed> void testExcessNullCheck(Class<T> type, ResourceKey<IRegistry<?>> registryKey, List<FieldData> fieldDataList) throws IllegalAccessException {
IRegistry<?> registry = vanilla_registry.lookupOrThrow(registryKey);
public <T extends Keyed> void testExcessNullCheck(Class<T> type, ResourceKey<net.minecraft.core.Registry<?>> registryKey, List<FieldData> fieldDataList) throws IllegalAccessException {
net.minecraft.core.Registry<?> registry = RegistryClassTest.vanilla_registry.lookupOrThrow(registryKey);
List<Field> excess = new ArrayList<>();
Data data = INIT_DATA.get(type);
Data data = RegistryClassTest.INIT_DATA.get(type);
for (FieldData fieldData : fieldDataList) {
NamespacedKey key = ((Keyed) fieldData.field().get(null)).getKey();
@@ -433,10 +432,10 @@ public class RegistryClassTest {
@ParameterizedTest
@MethodSource("fieldData")
public <T extends Keyed> void testMissingNullCheck(Class<T> type, ResourceKey<IRegistry<?>> registryKey, List<FieldData> fieldDataList) throws IllegalAccessException {
IRegistry<?> registry = vanilla_registry.lookupOrThrow(registryKey);
public <T extends Keyed> void testMissingNullCheck(Class<T> type, ResourceKey<net.minecraft.core.Registry<?>> registryKey, List<FieldData> fieldDataList) throws IllegalAccessException {
net.minecraft.core.Registry<?> registry = RegistryClassTest.vanilla_registry.lookupOrThrow(registryKey);
List<Field> missing = new ArrayList<>();
Data data = INIT_DATA.get(type);
Data data = RegistryClassTest.INIT_DATA.get(type);
for (FieldData fieldData : fieldDataList) {
NamespacedKey key = ((Keyed) fieldData.field().get(null)).getKey();
@@ -464,13 +463,13 @@ public class RegistryClassTest {
@ParameterizedTest
@MethodSource("fieldData")
public <T extends Keyed> void testMatchingFieldNames(Class<T> type, ResourceKey<IRegistry<?>> registryKey, List<FieldData> fieldDataList) throws IllegalAccessException {
public <T extends Keyed> void testMatchingFieldNames(Class<T> type, ResourceKey<net.minecraft.core.Registry<?>> registryKey, List<FieldData> fieldDataList) throws IllegalAccessException {
Map<Field, NamespacedKey> notMatching = new LinkedHashMap<>();
for (FieldData fieldData : fieldDataList) {
NamespacedKey key = ((Keyed) fieldData.field().get(null)).getKey();
if (fieldData.field().getName().equals(convertToFieldName(key.getKey()))) {
if (fieldData.field().getName().equals(this.convertToFieldName(key.getKey()))) {
continue;
}
@@ -490,19 +489,19 @@ public class RegistryClassTest {
@ParameterizedTest
@MethodSource("fieldData")
public <T extends Keyed> void testMissingConstants(Class<T> type, ResourceKey<IRegistry<?>> registryKey) throws IllegalAccessException {
IRegistry<Object> registry = RegistryHelper.getRegistry().lookupOrThrow(registryKey);
List<MinecraftKey> missingKeys = new ArrayList<>();
public <T extends Keyed> void testMissingConstants(Class<T> type, ResourceKey<net.minecraft.core.Registry<?>> registryKey) throws IllegalAccessException {
net.minecraft.core.Registry<Object> registry = RegistryHelper.getRegistry().lookupOrThrow(registryKey);
List<ResourceLocation> missingKeys = new ArrayList<>();
for (Object nmsObject : registry) {
MinecraftKey minecraftKey = registry.getKey(nmsObject);
ResourceLocation minecraftKey = registry.getKey(nmsObject);
try {
Field field = type.getField(convertToFieldName(minecraftKey.getPath()));
Field field = type.getField(this.convertToFieldName(minecraftKey.getPath()));
// Only fields which are not Deprecated
// and have the right registry item associated with the field count.
if (!isValidField(type, field)) {
if (!RegistryClassTest.isValidField(type, field)) {
missingKeys.add(minecraftKey);
continue;
}

View File

@@ -6,10 +6,9 @@ import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import net.minecraft.core.IRegistry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import org.bukkit.Keyed;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
@@ -61,12 +60,12 @@ public class RegistryConstantsTest {
assertTrue(excessKeys.isEmpty(), excessKeys.size() + " excess constants(s) in " + clazz.getSimpleName() + " that do not exist: " + excessKeys);
}
private <T extends Keyed, M> void testMissingConstants(Class<T> clazz, ResourceKey<IRegistry<M>> nmsRegistryKey) {
List<MinecraftKey> missingKeys = new ArrayList<>();
private <T extends Keyed, M> void testMissingConstants(Class<T> clazz, ResourceKey<net.minecraft.core.Registry<M>> nmsRegistryKey) {
List<ResourceLocation> missingKeys = new ArrayList<>();
IRegistry<M> nmsRegistry = RegistryHelper.getRegistry().lookupOrThrow(nmsRegistryKey);
net.minecraft.core.Registry<M> nmsRegistry = RegistryHelper.getRegistry().lookupOrThrow(nmsRegistryKey);
for (M nmsObject : nmsRegistry) {
MinecraftKey minecraftKey = nmsRegistry.getKey(nmsObject);
ResourceLocation minecraftKey = nmsRegistry.getKey(nmsObject);
try {
@SuppressWarnings("unchecked")

View File

@@ -11,7 +11,6 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.minecraft.core.IRegistry;
import net.minecraft.resources.ResourceKey;
import org.bukkit.Bukkit;
import org.bukkit.Keyed;
@@ -59,14 +58,14 @@ public class RegistryConversionTest {
The following implementation do not implement Handleable:
%s""", clazz.getName(), Joiner.on('\n').join(notImplemented)));
IMPLEMENT_HANDLE_ABLE.add(clazz);
RegistryConversionTest.IMPLEMENT_HANDLE_ABLE.add(clazz);
}
@Order(2)
@RegistriesTest
public void testMinecraftToBukkitPresent(Class<? extends Keyed> clazz, ResourceKey<IRegistry<?>> registryKey,
public void testMinecraftToBukkitPresent(Class<? extends Keyed> clazz, ResourceKey<net.minecraft.core.Registry<?>> registryKey,
Class<? extends Keyed> craftClazz, Class<?> minecraftClazz, boolean newMethod) {
String methodName = (newMethod) ? MINECRAFT_TO_BUKKIT_NEW : MINECRAFT_TO_BUKKIT;
String methodName = (newMethod) ? RegistryConversionTest.MINECRAFT_TO_BUKKIT_NEW : RegistryConversionTest.MINECRAFT_TO_BUKKIT;
Method method = null;
try {
method = craftClazz.getDeclaredMethod(methodName, minecraftClazz);
@@ -76,7 +75,7 @@ public class RegistryConversionTest {
Following method should be add which, returns the bukkit value based on the minecraft value.
%s
""", craftClazz, buildMinecraftToBukkitMethod(clazz, methodName, minecraftClazz)));
""", craftClazz, this.buildMinecraftToBukkitMethod(clazz, methodName, minecraftClazz)));
}
assertTrue(Modifier.isPublic(method.getModifiers()), String.format("""
@@ -84,23 +83,23 @@ public class RegistryConversionTest {
The method should be made public, method structure:
%s
""", methodName, craftClazz, buildMinecraftToBukkitMethod(clazz, methodName, minecraftClazz)));
""", methodName, craftClazz, this.buildMinecraftToBukkitMethod(clazz, methodName, minecraftClazz)));
assertTrue(Modifier.isStatic(method.getModifiers()), String.format("""
The method %s in class %s is not static.
The method should be made static, method structure:
%s
""", methodName, craftClazz, buildMinecraftToBukkitMethod(clazz, methodName, minecraftClazz)));
""", methodName, craftClazz, this.buildMinecraftToBukkitMethod(clazz, methodName, minecraftClazz)));
assertSame(clazz, method.getReturnType(), String.format("""
The method %s in class %s has the wrong return value.
The method should have the correct return value, method structure:
%s
""", methodName, craftClazz, buildMinecraftToBukkitMethod(clazz, methodName, minecraftClazz)));
""", methodName, craftClazz, this.buildMinecraftToBukkitMethod(clazz, methodName, minecraftClazz)));
MINECRAFT_TO_BUKKIT_METHODS.put(clazz, method);
RegistryConversionTest.MINECRAFT_TO_BUKKIT_METHODS.put(clazz, method);
}
private String buildMinecraftToBukkitMethod(Class<? extends Keyed> clazz, String methodName, Class<?> minecraftClazz) {
@@ -113,9 +112,9 @@ public class RegistryConversionTest {
@Order(2)
@RegistriesTest
public void testBukkitToMinecraftPresent(Class<? extends Keyed> clazz, ResourceKey<IRegistry<?>> registryKey,
public void testBukkitToMinecraftPresent(Class<? extends Keyed> clazz, ResourceKey<net.minecraft.core.Registry<?>> registryKey,
Class<? extends Keyed> craftClazz, Class<?> minecraftClazz, boolean newMethod) {
String methodName = (newMethod) ? BUKKIT_TO_MINECRAFT_NEW : BUKKIT_TO_MINECRAFT;
String methodName = (newMethod) ? RegistryConversionTest.BUKKIT_TO_MINECRAFT_NEW : RegistryConversionTest.BUKKIT_TO_MINECRAFT;
Method method = null;
try {
method = craftClazz.getDeclaredMethod(methodName, clazz);
@@ -125,7 +124,7 @@ public class RegistryConversionTest {
Following method should be add which, returns the minecraft value based on the bukkit value.
%s
""", craftClazz, buildBukkitToMinecraftMethod(clazz, methodName, minecraftClazz)));
""", craftClazz, this.buildBukkitToMinecraftMethod(clazz, methodName, minecraftClazz)));
}
assertTrue(Modifier.isPublic(method.getModifiers()), String.format("""
@@ -133,23 +132,23 @@ public class RegistryConversionTest {
The method should be made public, method structure:
%s
""", methodName, craftClazz, buildBukkitToMinecraftMethod(clazz, methodName, minecraftClazz)));
""", methodName, craftClazz, this.buildBukkitToMinecraftMethod(clazz, methodName, minecraftClazz)));
assertTrue(Modifier.isStatic(method.getModifiers()), String.format("""
The method %s in class %s is not static.
The method should be made static, method structure:
%s
""", methodName, craftClazz, buildBukkitToMinecraftMethod(clazz, methodName, minecraftClazz)));
""", methodName, craftClazz, this.buildBukkitToMinecraftMethod(clazz, methodName, minecraftClazz)));
assertSame(minecraftClazz, method.getReturnType(), String.format("""
The method %s in class %s has the wrong return value.
The method should have the correct return value, method structure:
%s
""", methodName, craftClazz, buildBukkitToMinecraftMethod(clazz, methodName, minecraftClazz)));
""", methodName, craftClazz, this.buildBukkitToMinecraftMethod(clazz, methodName, minecraftClazz)));
BUKKIT_TO_MINECRAFT_METHODS.put(clazz, method);
RegistryConversionTest.BUKKIT_TO_MINECRAFT_METHODS.put(clazz, method);
}
private String buildBukkitToMinecraftMethod(Class<? extends Keyed> clazz, String methodName, Class<?> minecraftClazz) {
@@ -163,49 +162,49 @@ public class RegistryConversionTest {
@Order(2)
@RegistriesTest
public void testMinecraftToBukkitNullValue(Class<? extends Keyed> clazz) throws IllegalAccessException {
checkValidMinecraftToBukkit(clazz);
this.checkValidMinecraftToBukkit(clazz);
try {
Object result = MINECRAFT_TO_BUKKIT_METHODS.get(clazz).invoke(null, (Object) null);
Object result = RegistryConversionTest.MINECRAFT_TO_BUKKIT_METHODS.get(clazz).invoke(null, (Object) null);
fail(String.format("""
Method %s in class %s should not accept null values and should throw a IllegalArgumentException.
Got '%s' as return object.
""", MINECRAFT_TO_BUKKIT, clazz.getName(), result));
""", RegistryConversionTest.MINECRAFT_TO_BUKKIT, clazz.getName(), result));
} catch (InvocationTargetException e) {
// #invoke wraps the error in a InvocationTargetException, so we need to check it this way
assertSame(IllegalArgumentException.class, e.getCause().getClass(), String.format("""
Method %s in class %s should not accept null values and should throw a IllegalArgumentException.
""", MINECRAFT_TO_BUKKIT, clazz.getName()));
""", RegistryConversionTest.MINECRAFT_TO_BUKKIT, clazz.getName()));
}
}
@Order(3)
@RegistriesTest
public void testBukkitToMinecraftNullValue(Class<? extends Keyed> clazz) throws IllegalAccessException {
checkValidBukkitToMinecraft(clazz);
this.checkValidBukkitToMinecraft(clazz);
try {
Object result = BUKKIT_TO_MINECRAFT_METHODS.get(clazz).invoke(null, (Object) null);
Object result = RegistryConversionTest.BUKKIT_TO_MINECRAFT_METHODS.get(clazz).invoke(null, (Object) null);
fail(String.format("""
Method %s in class %s should not accept null values and should throw a IllegalArgumentException.
Got '%s' as return object.
""", BUKKIT_TO_MINECRAFT, clazz.getName(), result));
""", RegistryConversionTest.BUKKIT_TO_MINECRAFT, clazz.getName(), result));
} catch (InvocationTargetException e) {
// #invoke wraps the error in a InvocationTargetException, so we need to check it this way
assertSame(IllegalArgumentException.class, e.getCause().getClass(), String.format("""
Method %s in class %s should not accept null values and should throw a IllegalArgumentException.
""", BUKKIT_TO_MINECRAFT, clazz.getName()));
""", RegistryConversionTest.BUKKIT_TO_MINECRAFT, clazz.getName()));
}
}
@Order(3)
@RegistriesTest
public void testMinecraftToBukkit(Class<? extends Keyed> clazz) {
checkValidMinecraftToBukkit(clazz);
checkValidHandle(clazz);
this.checkValidMinecraftToBukkit(clazz);
this.checkValidHandle(clazz);
Map<Object, Object> notMatching = new HashMap<>();
Method method = MINECRAFT_TO_BUKKIT_METHODS.get(clazz);
Method method = RegistryConversionTest.MINECRAFT_TO_BUKKIT_METHODS.get(clazz);
RegistryArgumentProvider.getValues(clazz).map(Arguments::get).forEach(arguments -> {
Keyed bukkit = (Keyed) arguments[0];
@@ -225,18 +224,18 @@ public class RegistryConversionTest {
The method %s in class %s does not match all registry items correctly.
Following registry items where match not correctly:
%s""", MINECRAFT_TO_BUKKIT, clazz.getName(),
%s""", RegistryConversionTest.MINECRAFT_TO_BUKKIT, clazz.getName(),
Joiner.on('\n').withKeyValueSeparator(" got: ").join(notMatching)));
}
@Order(3)
@RegistriesTest
public void testBukkitToMinecraft(Class<? extends Keyed> clazz) {
checkValidBukkitToMinecraft(clazz);
checkValidHandle(clazz);
this.checkValidBukkitToMinecraft(clazz);
this.checkValidHandle(clazz);
Map<Object, Object> notMatching = new HashMap<>();
Method method = BUKKIT_TO_MINECRAFT_METHODS.get(clazz);
Method method = RegistryConversionTest.BUKKIT_TO_MINECRAFT_METHODS.get(clazz);
RegistryArgumentProvider.getValues(clazz).map(Arguments::get).forEach(arguments -> {
Keyed bukkit = (Keyed) arguments[0];
@@ -256,7 +255,7 @@ public class RegistryConversionTest {
The method %s in class %s does not match all registry items correctly.
Following registry items where match not correctly:
%s""", BUKKIT_TO_MINECRAFT, clazz.getName(),
%s""", RegistryConversionTest.BUKKIT_TO_MINECRAFT, clazz.getName(),
Joiner.on('\n').withKeyValueSeparator(" got: ").join(notMatching)));
}
@@ -266,44 +265,44 @@ public class RegistryConversionTest {
*/
@Order(3)
@RegistriesTest
public void testMinecraftToBukkitNoValidMinecraft(Class<? extends Keyed> clazz, ResourceKey<IRegistry<?>> registryKey,
public void testMinecraftToBukkitNoValidMinecraft(Class<? extends Keyed> clazz, ResourceKey<net.minecraft.core.Registry<?>> registryKey,
Class<? extends Keyed> craftClazz, Class<?> minecraftClazz) throws IllegalAccessException {
checkValidMinecraftToBukkit(clazz);
this.checkValidMinecraftToBukkit(clazz);
try {
Object minecraft = mock(minecraftClazz);
Object result = MINECRAFT_TO_BUKKIT_METHODS.get(clazz).invoke(null, minecraft);
Object result = RegistryConversionTest.MINECRAFT_TO_BUKKIT_METHODS.get(clazz).invoke(null, minecraft);
fail(String.format("""
Method %s in class %s should not accept a none registered value and should throw a IllegalStateException.
Got '%s' as return object.
""", MINECRAFT_TO_BUKKIT, clazz.getName(), result));
""", RegistryConversionTest.MINECRAFT_TO_BUKKIT, clazz.getName(), result));
} catch (InvocationTargetException e) {
// #invoke wraps the error in a InvocationTargetException, so we need to check it this way
assertSame(IllegalStateException.class, e.getCause().getClass(), String.format("""
Method %s in class %s should not accept a none registered value and should throw a IllegalStateException.
""", MINECRAFT_TO_BUKKIT, clazz.getName()));
""", RegistryConversionTest.MINECRAFT_TO_BUKKIT, clazz.getName()));
}
}
private void checkValidBukkitToMinecraft(Class<? extends Keyed> clazz) {
assumeTrue(BUKKIT_TO_MINECRAFT_METHODS.containsKey(clazz), String.format("""
assumeTrue(RegistryConversionTest.BUKKIT_TO_MINECRAFT_METHODS.containsKey(clazz), String.format("""
Cannot test class %s, because it does not have a valid %s method.
Check test results of testBukkitToMinecraftPresent for more information.
""", clazz.getName(), BUKKIT_TO_MINECRAFT));
""", clazz.getName(), RegistryConversionTest.BUKKIT_TO_MINECRAFT));
}
private void checkValidMinecraftToBukkit(Class<? extends Keyed> clazz) {
assumeTrue(MINECRAFT_TO_BUKKIT_METHODS.containsKey(clazz), String.format("""
assumeTrue(RegistryConversionTest.MINECRAFT_TO_BUKKIT_METHODS.containsKey(clazz), String.format("""
Cannot test class %s, because it does not have a valid %s method.
Check test results of testMinecraftToBukkitPresent for more information.
""", clazz.getName(), MINECRAFT_TO_BUKKIT));
""", clazz.getName(), RegistryConversionTest.MINECRAFT_TO_BUKKIT));
}
private void checkValidHandle(Class<? extends Keyed> clazz) {
assumeTrue(IMPLEMENT_HANDLE_ABLE.contains(clazz), String.format("""
assumeTrue(RegistryConversionTest.IMPLEMENT_HANDLE_ABLE.contains(clazz), String.format("""
Cannot test class %s, because it does not implement Handleable.
Check test results of testHandleableImplementation for more information.

View File

@@ -6,11 +6,10 @@ import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import java.util.stream.Stream;
import net.minecraft.core.IRegistry;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.RegistrationInfo;
import net.minecraft.core.RegistryMaterials;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import org.bukkit.Keyed;
import org.bukkit.NamespacedKey;
import org.bukkit.Registry;
@@ -31,14 +30,14 @@ public class RegistryLoadOrderTest {
public static Stream<Arguments> data() {
return Stream.of(
Arguments.of(
(Supplier<Boolean>) () -> initInterface,
(Supplier<Boolean>) () -> RegistryLoadOrderTest.initInterface,
BukkitInterfaceTestType.class,
(BiFunction<NamespacedKey, MinecraftTestType, Keyed>) CraftBukkitInterfaceTestType::new,
(Supplier<Keyed>) () -> BukkitInterfaceTestType.TEST_ONE,
(Supplier<Keyed>) () -> BukkitInterfaceTestType.TEST_TWO
),
Arguments.of(
(Supplier<Boolean>) () -> initAbstract,
(Supplier<Boolean>) () -> RegistryLoadOrderTest.initAbstract,
BukkitAbstractTestType.class,
(BiFunction<NamespacedKey, MinecraftTestType, Keyed>) CraftBukkitAbstractTestType::new,
(Supplier<Keyed>) () -> BukkitAbstractTestType.TEST_ONE,
@@ -50,21 +49,21 @@ public class RegistryLoadOrderTest {
@ParameterizedTest
@MethodSource("data")
public void testRegistryLoadOrder(Supplier<Boolean> init, Class<Keyed> keyedClass, BiFunction<NamespacedKey, MinecraftTestType, Keyed> minecraftToBukkit, Supplier<Keyed> first, Supplier<Keyed> second) {
testClassNotLoaded(init.get());
this.testClassNotLoaded(init.get());
ResourceKey<IRegistry<MinecraftTestType>> resourceKey = ResourceKey.createRegistryKey(MinecraftKey.tryBuild("bukkit", "test-registry"));
RegistryMaterials<MinecraftTestType> minecraftRegistry = new RegistryMaterials<>(resourceKey, Lifecycle.experimental());
ResourceKey<net.minecraft.core.Registry<MinecraftTestType>> resourceKey = ResourceKey.createRegistryKey(ResourceLocation.tryBuild("bukkit", "test-registry"));
MappedRegistry<MinecraftTestType> minecraftRegistry = new MappedRegistry<>(resourceKey, Lifecycle.experimental());
minecraftRegistry.register(ResourceKey.create(resourceKey, MinecraftKey.tryBuild("bukkit", "test-one")), new MinecraftTestType(), new RegistrationInfo(Optional.empty(), Lifecycle.experimental()));
minecraftRegistry.register(ResourceKey.create(resourceKey, MinecraftKey.tryBuild("bukkit", "test-two")), new MinecraftTestType(), new RegistrationInfo(Optional.empty(), Lifecycle.experimental()));
minecraftRegistry.register(ResourceKey.create(resourceKey, ResourceLocation.tryBuild("bukkit", "test-one")), new MinecraftTestType(), new RegistrationInfo(Optional.empty(), Lifecycle.experimental()));
minecraftRegistry.register(ResourceKey.create(resourceKey, ResourceLocation.tryBuild("bukkit", "test-two")), new MinecraftTestType(), new RegistrationInfo(Optional.empty(), Lifecycle.experimental()));
minecraftRegistry.freeze();
registry = new CraftRegistry<>(keyedClass, minecraftRegistry, minecraftToBukkit, (namespacedKey, apiVersion) -> namespacedKey);
testClassNotLoaded(init.get());
RegistryLoadOrderTest.registry = new CraftRegistry<>(keyedClass, minecraftRegistry, minecraftToBukkit, (namespacedKey, apiVersion) -> namespacedKey);
this.testClassNotLoaded(init.get());
Object testOne = registry.get(new NamespacedKey("bukkit", "test-one"));
Object otherTestOne = registry.get(new NamespacedKey("bukkit", "test-one"));
Object testTwo = registry.get(new NamespacedKey("bukkit", "test-two"));
Object testOne = RegistryLoadOrderTest.registry.get(new NamespacedKey("bukkit", "test-one"));
Object otherTestOne = RegistryLoadOrderTest.registry.get(new NamespacedKey("bukkit", "test-one"));
Object testTwo = RegistryLoadOrderTest.registry.get(new NamespacedKey("bukkit", "test-two"));
assertNotNull(testOne);
assertNotNull(otherTestOne);
@@ -89,16 +88,16 @@ public class RegistryLoadOrderTest {
}
public interface BukkitInterfaceTestType extends Keyed {
BukkitInterfaceTestType TEST_ONE = get("test-one");
BukkitInterfaceTestType TEST_TWO = get("test-two");
BukkitInterfaceTestType TEST_ONE = BukkitInterfaceTestType.get("test-one");
BukkitInterfaceTestType TEST_TWO = BukkitInterfaceTestType.get("test-two");
private static BukkitInterfaceTestType get(String key) {
initInterface = true;
if (registry == null) {
RegistryLoadOrderTest.initInterface = true;
if (RegistryLoadOrderTest.registry == null) {
return null;
}
return (BukkitInterfaceTestType) registry.get(new NamespacedKey("bukkit", key));
return (BukkitInterfaceTestType) RegistryLoadOrderTest.registry.get(new NamespacedKey("bukkit", key));
}
}
@@ -113,21 +112,21 @@ public class RegistryLoadOrderTest {
@NotNull
@Override
public NamespacedKey getKey() {
return key;
return this.key;
}
}
public abstract static class BukkitAbstractTestType implements Keyed {
public static final BukkitAbstractTestType TEST_ONE = get("test-one");
public static final BukkitAbstractTestType TEST_TWO = get("test-two");
public static final BukkitAbstractTestType TEST_ONE = BukkitAbstractTestType.get("test-one");
public static final BukkitAbstractTestType TEST_TWO = BukkitAbstractTestType.get("test-two");
private static BukkitAbstractTestType get(String key) {
initAbstract = true;
if (registry == null) {
RegistryLoadOrderTest.initAbstract = true;
if (RegistryLoadOrderTest.registry == null) {
return null;
}
return (BukkitAbstractTestType) registry.get(new NamespacedKey("bukkit", key));
return (BukkitAbstractTestType) RegistryLoadOrderTest.registry.get(new NamespacedKey("bukkit", key));
}
}
@@ -142,7 +141,7 @@ public class RegistryLoadOrderTest {
@NotNull
@Override
public NamespacedKey getKey() {
return key;
return this.key;
}
}

View File

@@ -5,13 +5,10 @@ import com.google.common.base.Preconditions;
import java.util.logging.Logger;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.TagKey;
import net.minecraft.world.entity.EntityTypes;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.material.FluidType;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.craftbukkit.CraftLootTable;

View File

@@ -24,6 +24,6 @@ public final class LegacyHelper {
}
public static List<Material> getInvalidatedMaterials() {
return INVALIDATED_MATERIALS;
return LegacyHelper.INVALIDATED_MATERIALS;
}
}

View File

@@ -16,17 +16,17 @@ public final class Matchers {
private final int expected;
SameHash(T object) {
expected = object.hashCode();
this.expected = object.hashCode();
}
@Override
public boolean matches(Object item) {
return item.hashCode() == expected;
return item.hashCode() == this.expected;
}
@Override
public void describeTo(Description description) {
description.appendValue(expected);
description.appendValue(this.expected);
}
}
}

View File

@@ -4,66 +4,66 @@ import com.google.common.util.concurrent.MoreExecutors;
import java.util.List;
import java.util.Locale;
import net.minecraft.SharedConstants;
import net.minecraft.commands.CommandDispatcher;
import net.minecraft.commands.Commands;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.IRegistry;
import net.minecraft.core.IRegistryCustom;
import net.minecraft.core.LayeredRegistryAccess;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.server.DataPackResources;
import net.minecraft.server.DispenserRegistry;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.packs.EnumResourcePackType;
import net.minecraft.server.packs.repository.ResourcePackLoader;
import net.minecraft.server.packs.repository.ResourcePackRepository;
import net.minecraft.server.packs.repository.ResourcePackSourceVanilla;
import net.minecraft.server.packs.resources.IResourceManager;
import net.minecraft.server.ReloadableServerResources;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.Pack;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.tags.TagDataPack;
import net.minecraft.tags.TagLoader;
import net.minecraft.world.flag.FeatureFlagSet;
import net.minecraft.world.level.biome.BiomeBase;
import net.minecraft.world.level.biome.Biome;
import org.bukkit.Keyed;
import org.bukkit.NamespacedKey;
public final class RegistryHelper {
private static DataPackResources dataPack;
private static IRegistryCustom.Dimension registry;
private static IRegistry<BiomeBase> biomes;
private static ReloadableServerResources dataPack;
private static RegistryAccess.Frozen registry;
private static Registry<Biome> biomes;
private RegistryHelper() {
}
public static DataPackResources getDataPack() {
if (dataPack == null) {
throwError("dataPack");
public static ReloadableServerResources getDataPack() {
if (RegistryHelper.dataPack == null) {
RegistryHelper.throwError("dataPack");
}
return dataPack;
return RegistryHelper.dataPack;
}
public static IRegistryCustom.Dimension getRegistry() {
if (registry == null) {
throwError("registry");
public static RegistryAccess.Frozen getRegistry() {
if (RegistryHelper.registry == null) {
RegistryHelper.throwError("registry");
}
return registry;
return RegistryHelper.registry;
}
public static IRegistry<BiomeBase> getBiomes() {
if (biomes == null) {
throwError("biomes");
public static Registry<Biome> getBiomes() {
if (RegistryHelper.biomes == null) {
RegistryHelper.throwError("biomes");
}
return biomes;
return RegistryHelper.biomes;
}
public static IRegistryCustom.Dimension createRegistry(FeatureFlagSet featureFlagSet) {
ResourceManager ireloadableresourcemanager = createResourceManager(featureFlagSet);
public static RegistryAccess.Frozen createRegistry(FeatureFlagSet featureFlagSet) {
MultiPackResourceManager ireloadableresourcemanager = RegistryHelper.createResourceManager(featureFlagSet);
// add tags and loot tables for unit tests
LayeredRegistryAccess<RegistryLayer> layeredregistryaccess = RegistryLayer.createRegistryAccess();
List<IRegistry.a<?>> list = TagDataPack.loadTagsForExistingRegistries(ireloadableresourcemanager, layeredregistryaccess.getLayer(RegistryLayer.STATIC));
IRegistryCustom.Dimension iregistrycustom_dimension = layeredregistryaccess.getAccessForLoading(RegistryLayer.WORLDGEN);
List<HolderLookup.b<?>> list1 = TagDataPack.buildUpdatedLookups(iregistrycustom_dimension, list);
IRegistryCustom.Dimension iregistrycustom_dimension1 = RegistryDataLoader.load((IResourceManager) ireloadableresourcemanager, list1, RegistryDataLoader.WORLDGEN_REGISTRIES);
List<Registry.PendingTags<?>> list = TagLoader.loadTagsForExistingRegistries(ireloadableresourcemanager, layeredregistryaccess.getLayer(RegistryLayer.STATIC));
RegistryAccess.Frozen iregistrycustom_dimension = layeredregistryaccess.getAccessForLoading(RegistryLayer.WORLDGEN);
List<HolderLookup.RegistryLookup<?>> list1 = TagLoader.buildUpdatedLookups(iregistrycustom_dimension, list);
RegistryAccess.Frozen iregistrycustom_dimension1 = RegistryDataLoader.load((ResourceManager) ireloadableresourcemanager, list1, RegistryDataLoader.WORLDGEN_REGISTRIES);
LayeredRegistryAccess<RegistryLayer> layers = layeredregistryaccess.replaceFrom(RegistryLayer.WORLDGEN, iregistrycustom_dimension1);
return layers.compositeAccess().freeze();
@@ -71,23 +71,23 @@ public final class RegistryHelper {
public static void setup(FeatureFlagSet featureFlagSet) {
SharedConstants.tryDetectVersion();
DispenserRegistry.bootStrap();
Bootstrap.bootStrap();
ResourceManager ireloadableresourcemanager = createResourceManager(featureFlagSet);
MultiPackResourceManager ireloadableresourcemanager = RegistryHelper.createResourceManager(featureFlagSet);
// add tags and loot tables for unit tests
LayeredRegistryAccess<RegistryLayer> layeredregistryaccess = RegistryLayer.createRegistryAccess();
List<IRegistry.a<?>> list = TagDataPack.loadTagsForExistingRegistries(ireloadableresourcemanager, layeredregistryaccess.getLayer(RegistryLayer.STATIC));
IRegistryCustom.Dimension iregistrycustom_dimension = layeredregistryaccess.getAccessForLoading(RegistryLayer.WORLDGEN);
List<HolderLookup.b<?>> list1 = TagDataPack.buildUpdatedLookups(iregistrycustom_dimension, list);
IRegistryCustom.Dimension iregistrycustom_dimension1 = RegistryDataLoader.load((IResourceManager) ireloadableresourcemanager, list1, RegistryDataLoader.WORLDGEN_REGISTRIES);
List<Registry.PendingTags<?>> list = TagLoader.loadTagsForExistingRegistries(ireloadableresourcemanager, layeredregistryaccess.getLayer(RegistryLayer.STATIC));
RegistryAccess.Frozen iregistrycustom_dimension = layeredregistryaccess.getAccessForLoading(RegistryLayer.WORLDGEN);
List<HolderLookup.RegistryLookup<?>> list1 = TagLoader.buildUpdatedLookups(iregistrycustom_dimension, list);
RegistryAccess.Frozen iregistrycustom_dimension1 = RegistryDataLoader.load((ResourceManager) ireloadableresourcemanager, list1, RegistryDataLoader.WORLDGEN_REGISTRIES);
LayeredRegistryAccess<RegistryLayer> layers = layeredregistryaccess.replaceFrom(RegistryLayer.WORLDGEN, iregistrycustom_dimension1);
registry = layers.compositeAccess().freeze();
RegistryHelper.registry = layers.compositeAccess().freeze();
// Register vanilla pack
dataPack = DataPackResources.loadResources(ireloadableresourcemanager, layers, list, featureFlagSet, CommandDispatcher.ServerType.DEDICATED, 0, MoreExecutors.directExecutor(), MoreExecutors.directExecutor()).join();
RegistryHelper.dataPack = ReloadableServerResources.loadResources(ireloadableresourcemanager, layers, list, featureFlagSet, Commands.CommandSelection.DEDICATED, 0, MoreExecutors.directExecutor(), MoreExecutors.directExecutor()).join();
// Bind tags
dataPack.updateStaticRegistryTags();
RegistryHelper.dataPack.updateStaticRegistryTags();
// Biome shortcut
biomes = registry.lookupOrThrow(Registries.BIOME);
RegistryHelper.biomes = RegistryHelper.registry.lookupOrThrow(Registries.BIOME);
}
public static <T extends Keyed> Class<T> updateClass(Class<T> aClass, NamespacedKey key) {
@@ -104,12 +104,12 @@ public final class RegistryHelper {
return theClass;
}
private static ResourceManager createResourceManager(FeatureFlagSet featureFlagSet) {
private static MultiPackResourceManager createResourceManager(FeatureFlagSet featureFlagSet) {
// Populate available packs
ResourcePackRepository resourceRepository = ResourcePackSourceVanilla.createVanillaTrustedRepository();
PackRepository resourceRepository = ServerPacksSource.createVanillaTrustedRepository();
resourceRepository.reload();
// Set up resource manager
return new ResourceManager(EnumResourcePackType.SERVER_DATA, resourceRepository.getAvailablePacks().stream().filter(pack -> pack.getRequestedFeatures().isSubsetOf(featureFlagSet)).map(ResourcePackLoader::open).toList());
return new MultiPackResourceManager(PackType.SERVER_DATA, resourceRepository.getAvailablePacks().stream().filter(pack -> pack.getRequestedFeatures().isSubsetOf(featureFlagSet)).map(Pack::open).toList());
}
private static void throwError(String field) {

View File

@@ -24,11 +24,11 @@ public class AllFeaturesExtension extends BaseExtension {
}
public static <T extends Keyed> Registry<T> getRealRegistry(Class<T> clazz) {
return (Registry<T>) realRegistries.get(clazz);
return (Registry<T>) AllFeaturesExtension.realRegistries.get(clazz);
}
public static Map<Class<? extends Keyed>, Registry<?>> getRealRegistries() {
return realRegistries;
return AllFeaturesExtension.realRegistries;
}
@Override

View File

@@ -27,50 +27,50 @@ public abstract class BaseExtension implements BeforeAllCallback, BeforeEachCall
@Override
public final void beforeAll(ExtensionContext extensionContext) throws Exception {
if (!isTestCase(extensionContext)) {
if (!this.isTestCase(extensionContext)) {
return;
}
checkRunBeforeOnce(extensionContext);
this.checkRunBeforeOnce(extensionContext);
}
@Override
public final void beforeEach(ExtensionContext extensionContext) throws Exception {
if (!isTestCase(extensionContext)) {
if (!this.isTestCase(extensionContext)) {
return;
}
checkRunBeforeOnce(extensionContext);
runBeforeEach(extensionContext);
this.checkRunBeforeOnce(extensionContext);
this.runBeforeEach(extensionContext);
}
private boolean isTestCase(ExtensionContext extensionContext) {
if (currentlyRunning != null) {
return testSuite.equals(currentlyRunning);
if (BaseExtension.currentlyRunning != null) {
return this.testSuite.equals(BaseExtension.currentlyRunning);
}
Optional<String> runningTestSuite = extensionContext.getConfigurationParameter("TestSuite");
if (runningTestSuite.isPresent()) {
// We are inside a test suite, check if it is the test suite from this extension
if (!runningTestSuite.get().equals(testSuite)) {
if (!runningTestSuite.get().equals(this.testSuite)) {
return false;
}
currentlyRunning = testSuite;
logger.info("Running tests with environment: " + testSuite);
BaseExtension.currentlyRunning = this.testSuite;
this.logger.info("Running tests with environment: " + this.testSuite);
return true;
}
Set<String> tags = new HashSet<>(extensionContext.getTags());
tags.removeAll(IGNORE_TAGS);
tags.removeAll(BaseExtension.IGNORE_TAGS);
if (!tags.contains(testSuite)) {
if (!tags.contains(this.testSuite)) {
fail(String.format("""
Extension was triggered without the tag for the test suite being present. This should not happen.
Did you forget to add @Tag to a new environment annotation? Or maybe a spelling mistake?
Expected %s, but found:
%s""", testSuite, Joiner.on('\n').join(tags)));
%s""", this.testSuite, Joiner.on('\n').join(tags)));
return false; // Will never reach ):
}
@@ -89,18 +89,18 @@ public abstract class BaseExtension implements BeforeAllCallback, BeforeEachCall
return false; // Will never reach ):
}
currentlyRunning = testSuite;
logger.info("Running tests with environment: " + testSuite);
BaseExtension.currentlyRunning = this.testSuite;
this.logger.info("Running tests with environment: " + this.testSuite);
return true;
}
private void checkRunBeforeOnce(ExtensionContext extensionContext) {
if (run) {
if (BaseExtension.run) {
return;
}
init(extensionContext);
run = true;
this.init(extensionContext);
BaseExtension.run = true;
}
abstract void init(ExtensionContext extensionContext);

View File

@@ -4,7 +4,7 @@ import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.core.IRegistryCustom;
import net.minecraft.core.RegistryAccess;
import net.minecraft.world.flag.FeatureFlags;
import org.bukkit.Bukkit;
import org.bukkit.Keyed;
@@ -48,7 +48,7 @@ public class NormalExtension extends BaseExtension {
});
IRegistryCustom registry = mock(withSettings().stubOnly().defaultAnswer(DEFAULT_ANSWER));
RegistryAccess registry = mock(withSettings().stubOnly().defaultAnswer(NormalExtension.DEFAULT_ANSWER));
CraftRegistry.setMinecraftRegistry(registry);
}
@@ -58,7 +58,7 @@ public class NormalExtension extends BaseExtension {
private <T extends Keyed> Registry<T> createMockBukkitRegistry(Class<T> keyed) {
Map<NamespacedKey, T> mocks = new HashMap<>();
Registry<T> registry = mock(withSettings().stubOnly().defaultAnswer(DEFAULT_ANSWER));
Registry<T> registry = mock(withSettings().stubOnly().defaultAnswer(NormalExtension.DEFAULT_ANSWER));
doAnswer(invocation ->
mocks.computeIfAbsent(invocation.getArgument(0), k -> mock(RegistryHelper.updateClass(keyed, invocation.getArgument(0)), withSettings().stubOnly().defaultAnswer(DEFAULT_ANSWER)))

View File

@@ -24,7 +24,7 @@ public class ClassNodeArgumentProvider implements ArgumentsProvider, AnnotationC
this.excludedClasses = classNodeTest.excludedClasses();
this.excludedPackages = classNodeTest.excludedPackages();
for (int i = 0; i < excludedPackages.length; i++) {
for (int i = 0; i < this.excludedPackages.length; i++) {
this.excludedPackages[i] = this.excludedPackages[i].replace('.', '/');
}
}
@@ -32,16 +32,16 @@ public class ClassNodeArgumentProvider implements ArgumentsProvider, AnnotationC
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) throws Exception {
ClassReaderArgumentProvider classReaderArgumentProvider = new ClassReaderArgumentProvider();
classReaderArgumentProvider.accept(new ClassReaderArguments(classReaderClassType(), excludedClasses, excludedPackages));
classReaderArgumentProvider.accept(new ClassReaderArguments(this.classReaderClassType(), this.excludedClasses, this.excludedPackages));
return classReaderArgumentProvider.getClassReaders().map(this::toClassNode).map(Arguments::of);
}
private ClassReaderTest.ClassType[] classReaderClassType() {
ClassReaderTest.ClassType[] newValues = new ClassReaderTest.ClassType[classTypes.length];
ClassReaderTest.ClassType[] newValues = new ClassReaderTest.ClassType[this.classTypes.length];
for (int i = 0; i < classTypes.length; i++) {
newValues[i] = switch (classTypes[i]) {
for (int i = 0; i < this.classTypes.length; i++) {
newValues[i] = switch (this.classTypes[i]) {
case BUKKIT -> ClassReaderTest.ClassType.BUKKIT;
case CRAFT_BUKKIT -> ClassReaderTest.ClassType.CRAFT_BUKKIT;
case MINECRAFT_UNMODIFIED -> ClassReaderTest.ClassType.MINECRAFT_UNMODIFIED;

View File

@@ -52,34 +52,34 @@ public class ClassReaderArgumentProvider implements ArgumentsProvider, Annotatio
this.excludedClasses = classReaderTest.excludedClasses();
this.excludedPackages = classReaderTest.excludedPackages();
for (int i = 0; i < excludedPackages.length; i++) {
for (int i = 0; i < this.excludedPackages.length; i++) {
this.excludedPackages[i] = this.excludedPackages[i].replace('.', '/');
}
}
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) throws Exception {
return getClassReaders().map(Arguments::of);
return this.getClassReaders().map(Arguments::of);
}
public Stream<ClassReader> getClassReaders() {
assertNotEquals(CRAFT_BUKKIT_CLASSES, MINECRAFT_CLASSES, """
assertNotEquals(ClassReaderArgumentProvider.CRAFT_BUKKIT_CLASSES, ClassReaderArgumentProvider.MINECRAFT_CLASSES, """
The Minecraft and CraftBukkit uri point to the same directory / file.
Please make sure the CRAFT_BUKKIT_CLASSES points to the test class directory and MINECRAFT_CLASSES to the minecraft server jar.
""");
Stream<InputStream> result = Stream.empty();
if (contains(ClassReaderTest.ClassType.MINECRAFT_UNMODIFIED)) {
result = Stream.concat(result, readMinecraftClasses());
if (this.contains(ClassReaderTest.ClassType.MINECRAFT_UNMODIFIED)) {
result = Stream.concat(result, this.readMinecraftClasses());
}
if (contains(ClassReaderTest.ClassType.CRAFT_BUKKIT) || contains(ClassReaderTest.ClassType.MINECRAFT_MODIFIED)) {
result = Stream.concat(result, readCraftBukkitAndOrMinecraftModifiedClasses(contains(ClassReaderTest.ClassType.CRAFT_BUKKIT), contains(ClassReaderTest.ClassType.MINECRAFT_MODIFIED)));
if (this.contains(ClassReaderTest.ClassType.CRAFT_BUKKIT) || this.contains(ClassReaderTest.ClassType.MINECRAFT_MODIFIED)) {
result = Stream.concat(result, this.readCraftBukkitAndOrMinecraftModifiedClasses(this.contains(ClassReaderTest.ClassType.CRAFT_BUKKIT), this.contains(ClassReaderTest.ClassType.MINECRAFT_MODIFIED)));
}
if (contains(ClassReaderTest.ClassType.BUKKIT)) {
result = Stream.concat(result, readBukkitClasses());
if (this.contains(ClassReaderTest.ClassType.BUKKIT)) {
result = Stream.concat(result, this.readBukkitClasses());
}
return result.map(this::toClassReader);
@@ -94,7 +94,7 @@ public class ClassReaderArgumentProvider implements ArgumentsProvider, Annotatio
}
private boolean contains(ClassReaderTest.ClassType classType) {
for (ClassReaderTest.ClassType c : classTypes) {
for (ClassReaderTest.ClassType c : this.classTypes) {
if (c == classType) {
return true;
}
@@ -104,21 +104,21 @@ public class ClassReaderArgumentProvider implements ArgumentsProvider, Annotatio
}
private Stream<InputStream> readMinecraftClasses() {
return readJarFile(MINECRAFT_CLASSES, true);
return this.readJarFile(ClassReaderArgumentProvider.MINECRAFT_CLASSES, true);
}
private Stream<InputStream> readBukkitClasses() {
return readJarFile(BUKKIT_CLASSES, false);
return this.readJarFile(ClassReaderArgumentProvider.BUKKIT_CLASSES, false);
}
private Stream<InputStream> readJarFile(URI uri, boolean filterModified) {
try {
JarFile jarFile = new JarFile(new File(uri));
return jarFile.stream().onClose(() -> closeJarFile(jarFile))
return jarFile.stream().onClose(() -> this.closeJarFile(jarFile))
.filter(entry -> entry.getName().endsWith(".class"))
.filter(entry -> filterModifiedIfNeeded(entry, filterModified))
.filter(entry -> filterPackageNames(entry.getName()))
.filter(entry -> filterClass(entry.getName()))
.filter(entry -> this.filterModifiedIfNeeded(entry, filterModified))
.filter(entry -> this.filterPackageNames(entry.getName()))
.filter(entry -> this.filterClass(entry.getName()))
.map(entry -> {
try {
return jarFile.getInputStream(entry);
@@ -136,11 +136,11 @@ public class ClassReaderArgumentProvider implements ArgumentsProvider, Annotatio
return true;
}
return !new File(CRAFT_BUKKIT_CLASSES.resolve(entry.getName())).exists();
return !new File(ClassReaderArgumentProvider.CRAFT_BUKKIT_CLASSES.resolve(entry.getName())).exists();
}
private boolean filterPackageNames(String name) {
for (String packageName : excludedPackages) {
for (String packageName : this.excludedPackages) {
if (name.startsWith(packageName)) {
return false;
}
@@ -150,7 +150,7 @@ public class ClassReaderArgumentProvider implements ArgumentsProvider, Annotatio
}
private boolean filterClass(String name) {
for (Class<?> clazz : excludedClasses) {
for (Class<?> clazz : this.excludedClasses) {
if (name.equals(clazz.getName().replace('.', '/') + ".class")) {
return false;
}
@@ -161,13 +161,13 @@ public class ClassReaderArgumentProvider implements ArgumentsProvider, Annotatio
private Stream<InputStream> readCraftBukkitAndOrMinecraftModifiedClasses(boolean craftBukkit, boolean minecraftModified) {
try {
return Files.walk(Path.of(CRAFT_BUKKIT_CLASSES))
return Files.walk(Path.of(ClassReaderArgumentProvider.CRAFT_BUKKIT_CLASSES))
.map(Path::toFile)
.filter(File::isFile)
.filter(file -> file.getName().endsWith(".class"))
.filter(file -> shouldInclude(removeHomeDirectory(file), craftBukkit, minecraftModified))
.filter(file -> filterPackageNames(removeHomeDirectory(file)))
.filter(file -> filterClass(removeHomeDirectory(file)))
.filter(file -> this.shouldInclude(this.removeHomeDirectory(file), craftBukkit, minecraftModified))
.filter(file -> this.filterPackageNames(this.removeHomeDirectory(file)))
.filter(file -> this.filterClass(this.removeHomeDirectory(file)))
.map(file -> {
try {
return new FileInputStream(file);
@@ -181,7 +181,7 @@ public class ClassReaderArgumentProvider implements ArgumentsProvider, Annotatio
}
private String removeHomeDirectory(File file) {
return file.getAbsolutePath().substring(CRAFT_BUKKIT_CLASSES.getPath().length());
return file.getAbsolutePath().substring(ClassReaderArgumentProvider.CRAFT_BUKKIT_CLASSES.getPath().length());
}
private boolean shouldInclude(String name, boolean craftBukkit, boolean minecraftModified) {

View File

@@ -5,20 +5,16 @@ import java.util.List;
import java.util.stream.Stream;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.sounds.SoundEffect;
import net.minecraft.world.effect.MobEffectList;
import net.minecraft.world.entity.ai.attributes.AttributeBase;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.entity.animal.CatVariant;
import net.minecraft.world.entity.animal.FrogVariant;
import net.minecraft.world.entity.animal.WolfVariant;
import net.minecraft.world.entity.decoration.PaintingVariant;
import net.minecraft.world.entity.npc.VillagerProfession;
import net.minecraft.world.entity.npc.VillagerType;
import net.minecraft.world.inventory.Containers;
import net.minecraft.world.item.Instrument;
import net.minecraft.world.level.biome.BiomeBase;
import net.minecraft.world.level.block.entity.EnumBannerPatternType;
import net.minecraft.world.level.material.FluidType;
import net.minecraft.world.level.block.entity.BannerPattern;
import net.minecraft.world.level.saveddata.maps.MapDecorationType;
import org.bukkit.Art;
import org.bukkit.Fluid;
@@ -79,15 +75,15 @@ public class RegistriesArgumentProvider implements ArgumentsProvider {
static {
// Order: Bukkit class, Minecraft Registry key, CraftBukkit class, Minecraft class
register(Art.class, Registries.PAINTING_VARIANT, CraftArt.class, PaintingVariant.class);
register(Attribute.class, Registries.ATTRIBUTE, CraftAttribute.class, AttributeBase.class);
register(Biome.class, Registries.BIOME, CraftBiome.class, BiomeBase.class);
register(Attribute.class, Registries.ATTRIBUTE, CraftAttribute.class, net.minecraft.world.entity.ai.attributes.Attribute.class);
register(Biome.class, Registries.BIOME, CraftBiome.class, net.minecraft.world.level.biome.Biome.class);
register(Enchantment.class, Registries.ENCHANTMENT, CraftEnchantment.class, net.minecraft.world.item.enchantment.Enchantment.class);
register(Fluid.class, Registries.FLUID, CraftFluid.class, FluidType.class);
register(Fluid.class, Registries.FLUID, CraftFluid.class, net.minecraft.world.level.material.Fluid.class);
register(GameEvent.class, Registries.GAME_EVENT, CraftGameEvent.class, net.minecraft.world.level.gameevent.GameEvent.class);
register(MusicInstrument.class, Registries.INSTRUMENT, CraftMusicInstrument.class, Instrument.class);
register(MenuType.class, Registries.MENU, CraftMenuType.class, Containers.class);
register(PotionEffectType.class, Registries.MOB_EFFECT, CraftPotionEffectType.class, MobEffectList.class);
register(Sound.class, Registries.SOUND_EVENT, CraftSound.class, SoundEffect.class);
register(MenuType.class, Registries.MENU, CraftMenuType.class, net.minecraft.world.inventory.MenuType.class);
register(PotionEffectType.class, Registries.MOB_EFFECT, CraftPotionEffectType.class, MobEffect.class);
register(Sound.class, Registries.SOUND_EVENT, CraftSound.class, SoundEvent.class);
register(Structure.class, Registries.STRUCTURE, CraftStructure.class, net.minecraft.world.level.levelgen.structure.Structure.class);
register(StructureType.class, Registries.STRUCTURE_TYPE, CraftStructureType.class, net.minecraft.world.level.levelgen.structure.StructureType.class);
register(Villager.Type.class, Registries.VILLAGER_TYPE, CraftVillager.CraftType.class, VillagerType.class);
@@ -102,24 +98,24 @@ public class RegistriesArgumentProvider implements ArgumentsProvider {
register(Frog.Variant.class, Registries.FROG_VARIANT, CraftFrog.CraftVariant.class, FrogVariant.class);
register(Cat.Type.class, Registries.CAT_VARIANT, CraftCat.CraftType.class, CatVariant.class);
register(MapCursor.Type.class, Registries.MAP_DECORATION_TYPE, CraftMapCursor.CraftType.class, MapDecorationType.class);
register(PatternType.class, Registries.BANNER_PATTERN, CraftPatternType.class, EnumBannerPatternType.class);
register(PatternType.class, Registries.BANNER_PATTERN, CraftPatternType.class, BannerPattern.class);
}
private static void register(Class bukkit, ResourceKey registry, Class craft, Class minecraft) {
register(bukkit, registry, craft, minecraft, false);
RegistriesArgumentProvider.register(bukkit, registry, craft, minecraft, false);
}
private static void register(Class bukkit, ResourceKey registry, Class craft, Class minecraft, boolean newClass) {
DATA.add(Arguments.of(bukkit, registry, craft, minecraft, newClass));
RegistriesArgumentProvider.DATA.add(Arguments.of(bukkit, registry, craft, minecraft, newClass));
}
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) throws Exception {
return getData();
return RegistriesArgumentProvider.getData();
}
public static Stream<? extends Arguments> getData() {
return DATA.stream();
return RegistriesArgumentProvider.DATA.stream();
}
}

View File

@@ -17,12 +17,12 @@ public class RegistryArgumentProvider implements ArgumentsProvider, AnnotationCo
@Override
public void accept(RegistryTest registryTest) {
registryType = registryTest.value();
this.registryType = registryTest.value();
}
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) throws Exception {
return getValues(registryType);
return RegistryArgumentProvider.getValues(this.registryType);
}
public static Stream<? extends Arguments> getValues(Class<? extends Keyed> registryType) {