Files
purpur-heights/src/nativeTest/java/games/dmg/spigotheights/NativeBrewingTest.java
T
dmg 68d4a854c3
CI / build (push) Successful in 1m10s
CI / build (pull_request) Successful in 1m14s
fix(heights): support Purpur 26.3
2026-10-16 22:44:55 -04:00

424 lines
21 KiB
Java

package games.dmg.spigotheights;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;
import io.papermc.paper.plugin.manager.PaperPluginManagerImpl;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.Registries;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.item.crafting.RecipeManager;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BrewingStandBlockEntity;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Server;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.craftbukkit.inventory.CraftBrewingRecipe;
import org.bukkit.craftbukkit.inventory.CraftInventoryBrewer;
import org.bukkit.craftbukkit.inventory.CraftItemFactory;
import org.bukkit.craftbukkit.util.CraftMagicNumbers;
import org.bukkit.craftbukkit.util.CraftNamespacedKey;
import org.bukkit.event.HandlerList;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.BrewEvent;
import org.bukkit.entity.Player;
import org.bukkit.entity.AreaEffectCloud;
import org.bukkit.entity.ThrownPotion;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.entity.LingeringPotionSplashEvent;
import org.bukkit.event.entity.AreaEffectCloudApplyEvent;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionType;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.potion.PotionBrewer;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.Arguments;
/** Real build-2651 brewing ticks, items, metadata, recipes, event dispatch and ingredient consumption. */
class NativeBrewingTest {
private static PluginManager events;
private static Plugin plugin;
private PotionRecipes recipes;
private RecipeManager engine;
@BeforeAll
static void bootstrap() throws Exception {
NativeRuntime.bootstrap();
Server server = mock(Server.class);
when(server.getItemFactory()).thenAnswer(invocation -> CraftItemFactory.instance());
when(server.getUnsafe()).thenReturn(CraftMagicNumbers.INSTANCE);
when(server.getLogger()).thenReturn(Logger.getLogger("NativeBrewingTest"));
when(server.getName()).thenReturn("NativeBrewingTest");
when(server.getVersion()).thenReturn("26.3-2651");
when(server.getBukkitVersion()).thenReturn("26.3-2651");
when(server.isPrimaryThread()).thenReturn(true);
events = new PaperPluginManagerImpl(server, new SimpleCommandMap(server, new HashMap<>()), null);
when(server.getPluginManager()).thenReturn(events);
Bukkit.setServer(server);
plugin = mock(Plugin.class);
when(plugin.isEnabled()).thenReturn(true);
when(plugin.getName()).thenReturn("SpigotHeights");
when(plugin.getLogger()).thenReturn(Logger.getLogger("NativeBrewingTest"));
PluginDescriptionFile description = new PluginDescriptionFile("SpigotHeights", "test", "unused.Main");
when(plugin.getDescription()).thenReturn(description);
when(plugin.getPluginMeta()).thenReturn(description);
}
@BeforeEach
void registerActualRecipesAndListener() {
HandlerList.unregisterAll();
engine = NativeRuntime.recipes();
recipes = new PotionRecipes(null, new NamespacedKey("spigotheights", "stature_potion"), ItemStack::new);
PotionBrewer brewer = (PotionBrewer) Proxy.newProxyInstance(PotionBrewer.class.getClassLoader(),
new Class<?>[] {PotionBrewer.class}, (proxy, method, args) -> {
switch (method.getName()) {
case "addPotionMix" -> {
var mix = (io.papermc.paper.potion.PotionMix) args[0];
var recipe = new org.bukkit.inventory.BrewingRecipe(
mix.getKey(), mix.getResult(), mix.getInput(), mix.getIngredient());
engine.recipes.addRecipe(CraftBrewingRecipe.fromBukkitRecipe(recipe).toMinecraftRecipe());
engine.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
}
case "removePotionMix" -> {
engine.recipes.removeRecipe(CraftNamespacedKey.toResourceKey(
Registries.RECIPE, (NamespacedKey) args[0]));
engine.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
}
default -> throw new UnsupportedOperationException(method.getName());
}
return null;
});
recipes.registerBrewing(brewer);
events.registerEvents(new StatureBrewing(recipes), plugin);
}
@ParameterizedTest
@EnumSource(StaturePotion.class)
void purpur26_3ConvertsBaseLessStaturePotionsWithoutTheBuild2618Correction(StaturePotion kind) {
HandlerList.unregisterAll();
NativeStand stand = new NativeStand();
stand.inventory.setItem(0, recipes.create(kind));
stand.inventory.setIngredient(new ItemStack(Material.GUNPOWDER));
stand.completeCycle();
ItemStack result = stand.inventory.getItem(0);
assertEquals(Material.SPLASH_POTION, result.getType());
assertEquals(kind, recipes.identify(result));
assertTrue(stand.getItem(3).isEmpty());
}
@ParameterizedTest
@EnumSource(StaturePotion.class)
void gunpowderActuallyConvertsEveryAuthenticatedDrinkable(StaturePotion kind) {
NativeStand stand = new NativeStand();
stand.inventory.setItem(0, recipes.create(kind));
stand.inventory.setIngredient(new ItemStack(Material.GUNPOWDER));
stand.completeCycle();
ItemStack result = stand.inventory.getItem(0);
assertEquals(Material.SPLASH_POTION, result.getType(), "recognized recipe must actually convert");
assertEquals(kind, recipes.identify(result));
assertTrue(stand.getItem(3).isEmpty(), "one completed brew consumes one ingredient");
assertSplashApplies(result, kind);
}
@ParameterizedTest
@EnumSource(StaturePotion.class)
void dragonBreathConvertsExistingSplashIntoFunctionalLingering(StaturePotion kind) {
NativeStand stand = new NativeStand();
stand.inventory.setItem(0, recipes.create(kind, Material.SPLASH_POTION));
stand.inventory.setIngredient(new ItemStack(Material.DRAGON_BREATH));
stand.completeCycle();
ItemStack result = stand.inventory.getItem(0);
assertEquals(Material.LINGERING_POTION, result.getType());
assertEquals(kind, recipes.identify(result));
assertEquals(new ItemStack(Material.GLASS_BOTTLE), stand.inventory.getIngredient(),
"one successful conversion spends one dragon's breath and retains its bottle");
assertLingeringApplies(result, kind);
}
@ParameterizedTest
@EnumSource(StaturePotion.class)
void newlyBrewedSplashCanImmediatelyBeBrewedAgain(StaturePotion kind) {
NativeStand stand = new NativeStand();
stand.inventory.setItem(0, recipes.create(kind));
stand.inventory.setIngredient(new ItemStack(Material.GUNPOWDER));
stand.completeCycle();
assertEquals(Material.SPLASH_POTION, stand.inventory.getItem(0).getType());
stand.inventory.setIngredient(new ItemStack(Material.DRAGON_BREATH));
stand.completeCycle();
assertEquals(Material.LINGERING_POTION, stand.inventory.getItem(0).getType());
assertEquals(kind, recipes.identify(stand.inventory.getItem(0)));
assertEquals(new ItemStack(Material.GLASS_BOTTLE), stand.inventory.getIngredient());
assertEquals(18, stand.fuel);
}
@Test
void conflictingOutputCannotConsumeAnIngredientOrOverrideAnotherPlugin() {
events.registerEvent(BrewEvent.class, new Listener() {}, EventPriority.NORMAL,
(listener, event) -> ((BrewEvent) event).getResults().set(0, new ItemStack(Material.STONE)), plugin);
NativeStand stand = new NativeStand();
ItemStack original = recipes.create(StaturePotion.GROWTH);
stand.inventory.setItem(0, original);
stand.inventory.setIngredient(new ItemStack(Material.GUNPOWDER, 2));
stand.completeCycle();
assertEquals(2, stand.inventory.getIngredient().getAmount(), "failed conversion must not spend gunpowder");
assertEquals(original, stand.inventory.getItem(0), "conflict cancels the native transaction");
}
@ParameterizedTest
@EnumSource(value = EventPriority.class, names = {"LOW", "MONITOR"})
void cancellationBeforeOrAfterHeightsPreservesInventory(EventPriority priority) {
events.registerEvent(BrewEvent.class, new Listener() {}, priority,
(listener, event) -> ((BrewEvent) event).setCancelled(true), plugin);
NativeStand stand = new NativeStand();
ItemStack original = recipes.create(StaturePotion.SHIFTING);
stand.inventory.setItem(0, original);
stand.inventory.setIngredient(new ItemStack(Material.GUNPOWDER, 2));
stand.completeCycle();
assertEquals(original, stand.inventory.getItem(0));
assertEquals(2, stand.inventory.getIngredient().getAmount());
}
@Test
void missingOutputCancelsTheWholeMixedBatchWithoutLosingItems() {
events.registerEvent(BrewEvent.class, new Listener() {}, EventPriority.NORMAL,
(listener, event) -> ((BrewEvent) event).getResults().remove(2), plugin);
NativeStand stand = new NativeStand();
ItemStack first = recipes.create(StaturePotion.GROWTH);
ItemStack last = recipes.create(StaturePotion.DIMINUTION);
stand.inventory.setItem(0, first);
stand.inventory.setItem(2, last);
stand.inventory.setIngredient(new ItemStack(Material.GUNPOWDER));
stand.completeCycle();
assertEquals(first, stand.inventory.getItem(0));
assertEquals(last, stand.inventory.getItem(2));
assertEquals(1, stand.inventory.getIngredient().getAmount());
}
@Test
void oneIngredientConvertsMixedSlotsWithoutTouchingIneligiblePotions() {
NativeStand stand = new NativeStand();
stand.inventory.setItem(0, recipes.create(StaturePotion.GROWTH));
stand.inventory.setItem(1, recipes.create(StaturePotion.DIMINUTION));
ItemStack alreadySplash = recipes.create(StaturePotion.RESTORATION, Material.SPLASH_POTION);
stand.inventory.setItem(2, alreadySplash);
stand.inventory.setIngredient(new ItemStack(Material.GUNPOWDER, 2));
stand.completeCycle();
assertEquals(Material.SPLASH_POTION, stand.inventory.getItem(0).getType());
assertEquals(StaturePotion.GROWTH, recipes.identify(stand.inventory.getItem(0)));
assertEquals(Material.SPLASH_POTION, stand.inventory.getItem(1).getType());
assertEquals(StaturePotion.DIMINUTION, recipes.identify(stand.inventory.getItem(1)));
assertEquals(alreadySplash, stand.inventory.getItem(2));
assertEquals(1, stand.inventory.getIngredient().getAmount());
assertEquals(19, stand.fuel, "fuel accounting remains native");
}
@Test
void ordinaryAndNameOnlyPotionsRetainNativeBrewingAndNeverGainStatureIdentity() {
NativeStand stand = new NativeStand();
ItemStack ordinary = new ItemStack(Material.POTION);
PotionMeta meta = (PotionMeta) ordinary.getItemMeta();
meta.setBasePotionType(PotionType.HEALING);
meta.displayName(net.kyori.adventure.text.Component.text(StaturePotion.GROWTH.displayName()));
ordinary.setItemMeta(meta);
stand.inventory.setItem(0, ordinary);
stand.inventory.setItem(2, recipes.create(StaturePotion.SHIFTING));
stand.inventory.setIngredient(new ItemStack(Material.GUNPOWDER));
stand.completeCycle();
ItemStack result = stand.inventory.getItem(0);
assertEquals(Material.SPLASH_POTION, result.getType());
assertEquals(PotionType.HEALING, ((PotionMeta) result.getItemMeta()).getBasePotionType());
assertNull(recipes.identify(result));
assertEquals(StaturePotion.SHIFTING, recipes.identify(stand.inventory.getItem(2)));
}
@Test
void interruptedBrewDoesNotConvertOrSpendReplacementIngredient() {
NativeStand stand = new NativeStand();
ItemStack original = recipes.create(StaturePotion.RESTORATION);
stand.inventory.setItem(0, original);
stand.inventory.setIngredient(new ItemStack(Material.GUNPOWDER));
stand.tick();
assertEquals(400, stand.brewTime);
stand.inventory.setIngredient(new ItemStack(Material.SUGAR, 2));
stand.tick();
assertEquals(0, stand.brewTime);
assertEquals(original, stand.inventory.getItem(0));
assertEquals(new ItemStack(Material.SUGAR, 2), stand.inventory.getIngredient());
}
@Test
void validNativeOutputFromBaseTypedPotionIsNotRewritten() {
NativeStand stand = new NativeStand();
ItemStack input = recipes.create(StaturePotion.GROWTH);
PotionMeta meta = (PotionMeta) input.getItemMeta();
meta.setBasePotionType(PotionType.THICK);
input.setItemMeta(meta);
var name = net.kyori.adventure.text.Component.text("Other plugin's valid result");
events.registerEvent(BrewEvent.class, new Listener() {}, EventPriority.NORMAL, (listener, event) -> {
ItemStack result = ((BrewEvent) event).getResults().get(0);
assertEquals(Material.SPLASH_POTION, result.getType(), "base-typed items use the native custom mix");
result.editMeta(resultMeta -> resultMeta.displayName(name));
}, plugin);
stand.inventory.setItem(0, input);
stand.inventory.setIngredient(new ItemStack(Material.GUNPOWDER));
stand.completeCycle();
assertEquals(name, stand.inventory.getItem(0).getItemMeta().displayName());
assertEquals(StaturePotion.GROWTH, recipes.identify(stand.inventory.getItem(0)));
assertTrue(stand.getItem(3).isEmpty());
}
static java.util.stream.Stream<Arguments> conversionEdits() {
return java.util.stream.Stream.of(Material.GUNPOWDER, Material.DRAGON_BREATH)
.flatMap(ingredient -> java.util.stream.Stream.of(false, true)
.map(removeIdentity -> Arguments.of(ingredient, removeIdentity)));
}
@ParameterizedTest
@MethodSource("conversionEdits")
void nativeResultEditsRemainDetachedAndIdentityRemovalCannotSpendIngredients(
Material ingredient, boolean removeIdentity) {
events.registerEvent(BrewEvent.class, new Listener() {}, EventPriority.NORMAL, (listener, event) -> {
ItemStack result = ((BrewEvent) event).getResults().get(0);
result.editMeta(meta -> {
if (removeIdentity) {
meta.getPersistentDataContainer().remove(new NamespacedKey("spigotheights", "stature_potion"));
} else {
meta.displayName(net.kyori.adventure.text.Component.text("Other plugin's conflicting edit"));
}
});
}, plugin);
NativeStand stand = new NativeStand();
ItemStack original = recipes.create(StaturePotion.GROWTH,
ingredient == Material.GUNPOWDER ? Material.POTION : Material.SPLASH_POTION);
stand.inventory.setItem(0, original);
stand.inventory.setIngredient(new ItemStack(ingredient));
stand.completeCycle();
if (removeIdentity) {
assertEquals(new ItemStack(ingredient), stand.inventory.getIngredient(),
"identity removal cannot spend ingredients");
assertEquals(original, stand.inventory.getItem(0),
"cancelled identity removal must not mutate the input inventory");
} else {
assertEquals(ingredient == Material.GUNPOWDER ? null : new ItemStack(Material.GLASS_BOTTLE),
stand.inventory.getIngredient());
ItemStack result = stand.inventory.getItem(0);
assertEquals(ingredient == Material.GUNPOWDER ? Material.SPLASH_POTION : Material.LINGERING_POTION,
result.getType());
assertEquals(StaturePotion.GROWTH, recipes.identify(result));
assertEquals(net.kyori.adventure.text.Component.text("Other plugin's conflicting edit"),
result.getItemMeta().displayName());
assertEquals(StaturePotion.GROWTH, recipes.identify(original),
"native result edits must stay detached from the input object");
}
}
@Test
void purpur26_3NativeOutputDoesNotNeedTheCorrectionFactory() {
HandlerList.unregisterAll();
PotionRecipes brokenFactory = new PotionRecipes(null, new NamespacedKey("spigotheights", "stature_potion"),
material -> { throw new IllegalStateException("simulated item factory failure"); });
events.registerEvents(new StatureBrewing(brokenFactory), plugin);
NativeStand stand = new NativeStand();
ItemStack original = recipes.create(StaturePotion.GROWTH);
stand.inventory.setItem(0, original);
stand.inventory.setIngredient(new ItemStack(Material.GUNPOWDER));
stand.completeCycle();
assertEquals(Material.SPLASH_POTION, stand.inventory.getItem(0).getType());
assertEquals(StaturePotion.GROWTH, recipes.identify(stand.inventory.getItem(0)));
assertTrue(stand.getItem(3).isEmpty());
}
private void assertSplashApplies(ItemStack result, StaturePotion expected) {
List<StaturePotion> applied = new ArrayList<>();
ThrowableStatureListener effects = new ThrowableStatureListener(recipes,
new NamespacedKey("spigotheights", "cloud_kind"), (source, player, kind, done) -> {
applied.add(kind);
done.accept(true);
});
Player player = mock(Player.class);
when(player.getUniqueId()).thenReturn(UUID.randomUUID());
when(player.isOnline()).thenReturn(true);
ThrownPotion thrown = mock(ThrownPotion.class);
when(thrown.getUniqueId()).thenReturn(UUID.randomUUID());
when(thrown.getItem()).thenReturn(result);
when(thrown.getPersistentDataContainer()).thenReturn(new ItemStack(Material.STONE).getItemMeta().getPersistentDataContainer());
var event = new PotionSplashEvent(thrown, null, null, null, Map.of(player, 1.0));
effects.onSplash(event);
effects.onSplash(event);
assertEquals(List.of(expected), applied, "brewed item reaches the stature adapter exactly once");
}
private void assertLingeringApplies(ItemStack result, StaturePotion expected) {
List<StaturePotion> applied = new ArrayList<>();
ThrowableStatureListener effects = new ThrowableStatureListener(recipes,
new NamespacedKey("spigotheights", "cloud_kind"), (source, player, kind, done) -> {
applied.add(kind);
done.accept(true);
});
Player player = mock(Player.class);
when(player.getUniqueId()).thenReturn(UUID.randomUUID());
when(player.isOnline()).thenReturn(true);
ThrownPotion thrown = mock(ThrownPotion.class);
when(thrown.getItem()).thenReturn(result);
AreaEffectCloud cloud = mock(AreaEffectCloud.class);
when(cloud.getUniqueId()).thenReturn(UUID.randomUUID());
when(cloud.getPersistentDataContainer()).thenReturn(new ItemStack(Material.STONE).getItemMeta().getPersistentDataContainer());
var creation = new LingeringPotionSplashEvent(thrown, null, null, null, cloud);
effects.onLingering(creation);
assertTrue(creation.allowsEmptyCreation());
var application = new AreaEffectCloudApplyEvent(cloud, new ArrayList<>(List.of(player)));
effects.onCloud(application);
effects.onCloud(application);
assertEquals(List.of(expected), applied, "brewed cloud reaches the stature adapter exactly once");
}
private final class NativeStand extends BrewingStandBlockEntity {
private final CraftInventoryBrewer inventory = new CraftInventoryBrewer(this);
private final ServerLevel level = mock(ServerLevel.class);
NativeStand() {
super(BlockPos.ZERO, Blocks.BREWING_STAND.defaultBlockState());
when(level.recipeAccess()).thenReturn(engine);
fuel = 20;
}
@Override public InventoryHolder getOwner() { return () -> inventory; }
void completeCycle() {
tick();
assertEquals(400, brewTime, "native stand must start brewing");
for (int i = 0; i < 400; i++) {
tick();
}
assertEquals(0, brewTime);
}
void tick() {
BrewingStandBlockEntity.serverTick(level, BlockPos.ZERO, getBlockState(), this);
}
}
}