Adds some tests for the salvage helper
All checks were successful
EpicKnarvik97/Blacksmith/pipeline/head This commit looks good

This commit is contained in:
Kristian Knarvik 2023-01-14 15:10:40 +01:00
parent 8e5d4c7a61
commit 7cc2aef9d4
8 changed files with 173 additions and 25 deletions

16
pom.xml
View File

@ -35,6 +35,10 @@
<id>vault-repo</id> <id>vault-repo</id>
<url>https://nexus.hc.to/content/repositories/pub_releases</url> <url>https://nexus.hc.to/content/repositories/pub_releases</url>
</repository> </repository>
<repository>
<id>papermc</id>
<url>https://repo.papermc.io/repository/maven-public/</url>
</repository>
</repositories> </repositories>
<distributionManagement> <distributionManagement>
<repository> <repository>
@ -86,6 +90,18 @@
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.seeseemelk</groupId>
<artifactId>MockBukkit-v1.19</artifactId>
<version>2.144.3</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<!-- Build information --> <!-- Build information -->

View File

@ -19,9 +19,12 @@ import net.knarcraft.knarlib.formatting.Translator;
import net.knarcraft.knarlib.util.UpdateChecker; import net.knarcraft.knarlib.util.UpdateChecker;
import org.bukkit.command.PluginCommand; import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import java.io.File;
import java.util.logging.Level; import java.util.logging.Level;
/** /**
@ -34,6 +37,22 @@ public class BlacksmithPlugin extends JavaPlugin {
private static Translator translator; private static Translator translator;
private static StringFormatter stringFormatter; private static StringFormatter stringFormatter;
/**
* Constructor required for MockBukkit
*/
@SuppressWarnings("unused")
public BlacksmithPlugin() {
super();
}
/**
* Constructor required for MockBukkit
*/
@SuppressWarnings("unused")
protected BlacksmithPlugin(JavaPluginLoader loader, PluginDescriptionFile descriptionFile, File dataFolder, File file) {
super(loader, descriptionFile, dataFolder, file);
}
/** /**
* Gets an instance of the Blacksmith plugin * Gets an instance of the Blacksmith plugin
* *

View File

@ -2,9 +2,9 @@ package net.knarcraft.blacksmith.config;
import net.citizensnpcs.api.util.DataKey; import net.citizensnpcs.api.util.DataKey;
import net.knarcraft.blacksmith.BlacksmithPlugin; import net.knarcraft.blacksmith.BlacksmithPlugin;
import net.knarcraft.blacksmith.trait.BlacksmithTrait;
import net.knarcraft.blacksmith.util.ConfigHelper; import net.knarcraft.blacksmith.util.ConfigHelper;
import net.knarcraft.blacksmith.util.InputParsingHelper; import net.knarcraft.blacksmith.util.InputParsingHelper;
import net.knarcraft.blacksmith.util.ItemHelper;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -460,7 +460,7 @@ public class NPCSettings {
} }
Material material = InputParsingHelper.matchMaterial(item); Material material = InputParsingHelper.matchMaterial(item);
if (material != null && BlacksmithTrait.isRepairable(new ItemStack(material, 1))) { if (material != null && ItemHelper.isRepairable(new ItemStack(material, 1))) {
if (!blacklist) { if (!blacklist) {
reforgeAbleItems.add(material); reforgeAbleItems.add(material);
} else { } else {

View File

@ -11,11 +11,9 @@ import net.knarcraft.blacksmith.util.ItemHelper;
import net.knarcraft.knarlib.formatting.StringFormatter; import net.knarcraft.knarlib.formatting.StringFormatter;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.enchantments.EnchantmentTarget;
import org.bukkit.entity.LivingEntity; import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import java.util.Calendar; import java.util.Calendar;
import java.util.HashMap; import java.util.HashMap;
@ -180,7 +178,7 @@ public class BlacksmithTrait extends Trait {
//Refuse if not repairable, or if reforge-able items is set, but doesn't include the held item //Refuse if not repairable, or if reforge-able items is set, but doesn't include the held item
List<Material> reforgeAbleItems = config.getReforgeAbleItems(); List<Material> reforgeAbleItems = config.getReforgeAbleItems();
if ((!this.config.getRepairAnvils() || !ItemHelper.isAnvil(hand.getType(), false)) && if ((!this.config.getRepairAnvils() || !ItemHelper.isAnvil(hand.getType(), false)) &&
(!isRepairable(hand) || (!reforgeAbleItems.isEmpty() && !reforgeAbleItems.contains(hand.getType())))) { (!ItemHelper.isRepairable(hand) || (!reforgeAbleItems.isEmpty() && !reforgeAbleItems.contains(hand.getType())))) {
String invalidMessage = StringFormatter.replacePlaceholder(config.getInvalidItemMessage(), String invalidMessage = StringFormatter.replacePlaceholder(config.getInvalidItemMessage(),
"{title}", config.getBlacksmithTitle()); "{title}", config.getBlacksmithTitle());
sendNPCMessage(this.npc, player, invalidMessage); sendNPCMessage(this.npc, player, invalidMessage);
@ -225,14 +223,4 @@ public class BlacksmithTrait extends Trait {
player.getInventory().setItemInMainHand(null); player.getInventory().setItemInMainHand(null);
} }
/**
* Gets whether the given item is repairable
*
* @param item <p>The item to check</p>
* @return <p>True if the item is repairable</p>
*/
public static boolean isRepairable(ItemStack item) {
return item.getItemMeta() instanceof Damageable && EnchantmentTarget.BREAKABLE.includes(item);
}
} }

View File

@ -17,6 +17,16 @@ public final class ItemHelper {
} }
/**
* Gets whether the given item is repairable
*
* @param item <p>The item to check</p>
* @return <p>True if the item is repairable</p>
*/
public static boolean isRepairable(ItemStack item) {
return item.getItemMeta() instanceof Damageable && EnchantmentTarget.BREAKABLE.includes(item);
}
/** /**
* Gets the max durability of an item * Gets the max durability of an item
* *

View File

@ -1,8 +1,7 @@
package net.knarcraft.blacksmith.util; package net.knarcraft.blacksmith.util;
import net.knarcraft.blacksmith.trait.BlacksmithTrait;
import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe; import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.ShapedRecipe;
@ -24,17 +23,19 @@ public final class SalvageHelper {
* *
* <p>Note: Only items craft-able in a crafting table are salvageable. Netherite gear is therefore not salvageable.</p> * <p>Note: Only items craft-able in a crafting table are salvageable. Netherite gear is therefore not salvageable.</p>
* *
* @param server <p>The server to get recipes from</p>
* @param salvagedItem <p>The item stack to salvage</p> * @param salvagedItem <p>The item stack to salvage</p>
* @param ignoredSalvage <p>Any material which should not be returned as part of the salvage.</p>
* @return <p>The items to return to the user, or null if not salvageable</p> * @return <p>The items to return to the user, or null if not salvageable</p>
*/ */
public static List<ItemStack> getSalvage(ItemStack salvagedItem) { public static List<ItemStack> getSalvage(Server server, ItemStack salvagedItem, List<Material> ignoredSalvage) {
if (salvagedItem == null || salvagedItem.getAmount() < 1 || if (salvagedItem == null || salvagedItem.getAmount() < 1 ||
!BlacksmithTrait.isRepairable(salvagedItem)) { !ItemHelper.isRepairable(salvagedItem)) {
return null; return null;
} }
for (Recipe recipe : Bukkit.getServer().getRecipesFor(salvagedItem)) { for (Recipe recipe : server.getRecipesFor(salvagedItem)) {
List<ItemStack> salvage = getRecipeSalvage(recipe, salvagedItem); List<ItemStack> salvage = getRecipeSalvage(recipe, salvagedItem, ignoredSalvage);
if (salvage != null) { if (salvage != null) {
return salvage; return salvage;
} }
@ -48,9 +49,11 @@ public final class SalvageHelper {
* *
* @param recipe <p>The recipe to get salvage for</p> * @param recipe <p>The recipe to get salvage for</p>
* @param salvagedItem <p>The item to be salvaged</p> * @param salvagedItem <p>The item to be salvaged</p>
* @param ignoredSalvage <p>Any material which should not be returned as part of the salvage.</p>
* @return <p>A list of items, or null if not a valid type of recipe</p> * @return <p>A list of items, or null if not a valid type of recipe</p>
*/ */
private static List<ItemStack> getRecipeSalvage(Recipe recipe, ItemStack salvagedItem) { private static List<ItemStack> getRecipeSalvage(Recipe recipe, ItemStack salvagedItem,
List<Material> ignoredSalvage) {
List<ItemStack> ingredients; List<ItemStack> ingredients;
if (recipe instanceof ShapedRecipe shapedRecipe) { if (recipe instanceof ShapedRecipe shapedRecipe) {
ingredients = getIngredients(shapedRecipe); ingredients = getIngredients(shapedRecipe);
@ -63,6 +66,11 @@ public final class SalvageHelper {
//Make things easier by eliminating identical stacks //Make things easier by eliminating identical stacks
ingredients = combineStacks(ingredients); ingredients = combineStacks(ingredients);
//Purge any ignored salvage to only calculate salvage using the remaining items
if (ignoredSalvage != null) {
ingredients.removeIf((item) -> ignoredSalvage.contains(item.getType()));
}
//Make sure to give salvage for all items if a stack > 1 is provided //Make sure to give salvage for all items if a stack > 1 is provided
List<ItemStack> salvage = new ArrayList<>(); List<ItemStack> salvage = new ArrayList<>();
for (int i = 0; i < salvagedItem.getAmount(); i++) { for (int i = 0; i < salvagedItem.getAmount(); i++) {

View File

@ -0,0 +1,31 @@
package net.knarcraft.blacksmith;
import be.seeseemelk.mockbukkit.ServerMock;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.ShapedRecipe;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* A custom server mock specifically for making the SalvageHelperTest work
*/
public class CustomServerMock extends ServerMock {
public @NotNull List<Recipe> getRecipesFor(@NotNull ItemStack itemStack) {
List<Recipe> validRecipes = new ArrayList<>();
if (itemStack.getType() == Material.DIAMOND_PICKAXE) {
ShapedRecipe recipe = new ShapedRecipe(NamespacedKey.minecraft("diamond_pickaxe"), itemStack);
recipe.shape("ddd", "asa", "asa");
recipe.setIngredient('d', Material.DIAMOND);
recipe.setIngredient('s', Material.STICK);
validRecipes.add(recipe);
}
return validRecipes;
}
}

View File

@ -0,0 +1,76 @@
package net.knarcraft.blacksmith.util;
import be.seeseemelk.mockbukkit.MockBukkit;
import net.knarcraft.blacksmith.CustomServerMock;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* A test class to test salvaging
*/
public class SalvageHelperTest {
private static Server server;
@BeforeAll
public static void setUp() {
server = MockBukkit.mock(new CustomServerMock());
}
@Test
public void getNullForInvalidItemTest() {
//Assert that a non-reforge-able item will return null
assertNull(SalvageHelper.getSalvage(server, new ItemStack(Material.POTATO, 1), null));
}
@Test
public void getNullForLessThanOneItemTest() {
//Assert that 0 or 1 items will return null
assertNull(SalvageHelper.getSalvage(server, new ItemStack(Material.IRON_AXE, 0), null));
assertNull(SalvageHelper.getSalvage(server, new ItemStack(Material.IRON_SWORD, -1), null));
}
@Test
public void getFullSalvageTest() {
Set<ItemStack> expectedSalvage = new HashSet<>();
expectedSalvage.add(new ItemStack(Material.DIAMOND, 3));
expectedSalvage.add(new ItemStack(Material.STICK, 2));
ItemStack itemToSalvage = new ItemStack(Material.DIAMOND_PICKAXE, 1);
//Note: Conversion to sets makes sure the order doesn't matter
assertEquals(expectedSalvage, new HashSet<>(SalvageHelper.getSalvage(server, itemToSalvage, null)));
}
@Test
public void getNonFullSalvageTest() {
List<ItemStack> expectedSalvage = new ArrayList<>();
expectedSalvage.add(new ItemStack(Material.DIAMOND, 3));
expectedSalvage.add(new ItemStack(Material.STICK, 2));
ItemStack itemToSalvage = new ItemStack(Material.DIAMOND_PICKAXE, 1);
ItemMeta meta = itemToSalvage.getItemMeta();
Damageable damageable = (Damageable) meta;
if (damageable != null) {
damageable.setDamage(100);
}
itemToSalvage.setItemMeta(meta);
List<ItemStack> salvage = SalvageHelper.getSalvage(server, itemToSalvage, null);
//Assert that some items are given
assertNotEquals(salvage, new ArrayList<>());
//Assert that a damaged item won't give full salvage
assertNotEquals(expectedSalvage, salvage);
}
}