From 0d954aa13e516eaec74a8147d5078d78cd2aa630 Mon Sep 17 00:00:00 2001 From: Brendon Butler Date: Fri, 18 Aug 2023 14:30:41 -0400 Subject: [PATCH 01/11] Update pom version to 0.2-BETA for next version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f32c4e8..5cb8fcd 100644 --- a/pom.xml +++ b/pom.xml @@ -42,7 +42,7 @@ Shops net.sparkzz shops - 0.1-BETA + 0.2-BETA Location based shops plugin for Spigot ${spigot-api.version} https://shops.sparkzz.net/ From d0f89ea3228af853d2cdb0e71a9ffc958df0c379 Mon Sep 17 00:00:00 2001 From: Brendon Butler Date: Fri, 18 Aug 2023 14:30:41 -0400 Subject: [PATCH 02/11] Update pom version to 0.2-BETA for next version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f32c4e8..5cb8fcd 100644 --- a/pom.xml +++ b/pom.xml @@ -42,7 +42,7 @@ Shops net.sparkzz shops - 0.1-BETA + 0.2-BETA Location based shops plugin for Spigot ${spigot-api.version} https://shops.sparkzz.net/ From 7689571b5f2249bea508026b3b372a7c89986935 Mon Sep 17 00:00:00 2001 From: Brendon Butler Date: Fri, 18 Aug 2023 14:30:41 -0400 Subject: [PATCH 03/11] Update pom version to 0.2-BETA for next version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f32c4e8..5cb8fcd 100644 --- a/pom.xml +++ b/pom.xml @@ -42,7 +42,7 @@ Shops net.sparkzz shops - 0.1-BETA + 0.2-BETA Location based shops plugin for Spigot ${spigot-api.version} https://shops.sparkzz.net/ From b4cb46a78956cd680c145a8086ec662f42e33d3e Mon Sep 17 00:00:00 2001 From: Brendon Butler Date: Fri, 18 Aug 2023 18:56:50 -0400 Subject: [PATCH 04/11] update README for new Shops image --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0701faf..2591e30 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Shops plugin for Bukkit/Spigot 2022+ -![Shops social image](https://repository-images.githubusercontent.com/388618586/0d033997-0fcd-44db-a53d-c635f8bc38f5) +![Shops social image](https://repository-images.githubusercontent.com/388618586/2bc0f5a2-80f8-4cc7-859b-962e4d5e773d) **Depends on:** [Vault](https://github.com/MilkBowl/Vault) From bb6a2348aa8c134cdbb7e071903c7ebeaaa3c279 Mon Sep 17 00:00:00 2001 From: Brendon Butler Date: Wed, 23 Aug 2023 07:09:43 -0400 Subject: [PATCH 05/11] GH-24 implement default stores move identifyStore to Store class GH-27 fix leaving shop message appearing when not in a shop GH-28 fix browsing empty Store miscellaneous refactoring and cleanup --- .../java/net/sparkzz/command/ShopCommand.java | 5 +- .../java/net/sparkzz/command/SubCommand.java | 19 +--- .../net/sparkzz/command/sub/AddCommand.java | 2 +- .../sparkzz/command/sub/BrowseCommand.java | 10 +- .../net/sparkzz/command/sub/BuyCommand.java | 2 +- .../sparkzz/command/sub/CreateCommand.java | 1 - .../sparkzz/command/sub/DeleteCommand.java | 98 +++++++++---------- .../sparkzz/command/sub/DepositCommand.java | 2 +- .../sparkzz/command/sub/RemoveCommand.java | 2 +- .../net/sparkzz/command/sub/SellCommand.java | 2 +- .../sparkzz/command/sub/TransferCommand.java | 76 +++++++------- .../sparkzz/command/sub/UpdateCommand.java | 2 +- .../sparkzz/command/sub/WithdrawCommand.java | 2 +- .../net/sparkzz/event/EntranceListener.java | 3 +- src/main/java/net/sparkzz/shops/Shops.java | 9 ++ src/main/java/net/sparkzz/shops/Store.java | 59 +++++++++-- src/main/java/net/sparkzz/util/Config.java | 50 ++++++++++ .../util/InventoryManagementSystem.java | 7 +- src/main/java/net/sparkzz/util/Notifier.java | 1 + .../java/net/sparkzz/util/Transaction.java | 2 +- src/main/java/net/sparkzz/util/Warehouse.java | 15 ++- src/main/resources/config.yml | 3 + .../net/sparkzz/command/InfoCommandTest.java | 7 +- .../net/sparkzz/command/ShopCommandTest.java | 17 ++-- .../net/sparkzz/command/SubCommandTest.java | 10 +- .../sparkzz/command/sub/AddCommandTest.java | 17 ++-- .../command/sub/BrowseCommandTest.java | 18 ++-- .../sparkzz/command/sub/BuyCommandTest.java | 11 ++- .../command/sub/CreateCommandTest.java | 5 +- .../command/sub/DeleteCommandTest.java | 10 +- .../command/sub/DepositCommandTest.java | 17 ++-- .../command/sub/RemoveCommandTest.java | 15 +-- .../sparkzz/command/sub/SellCommandTest.java | 17 ++-- .../command/sub/TransferCommandTest.java | 7 +- .../command/sub/UpdateCommandTest.java | 11 ++- .../command/sub/WithdrawCommandTest.java | 9 +- .../sparkzz/event/EntranceListenerTest.java | 12 +-- .../java/net/sparkzz/shops/StoreTest.java | 34 +++---- .../java/net/sparkzz/util/CuboidTest.java | 2 +- .../util/InventoryManagementSystemTest.java | 19 ++-- .../java/net/sparkzz/util/NotifierTest.java | 2 +- .../net/sparkzz/util/TransactionTest.java | 9 +- src/test/resources/config.yml | 1 + 43 files changed, 377 insertions(+), 245 deletions(-) diff --git a/src/main/java/net/sparkzz/command/ShopCommand.java b/src/main/java/net/sparkzz/command/ShopCommand.java index 95db188..5ef68bc 100644 --- a/src/main/java/net/sparkzz/command/ShopCommand.java +++ b/src/main/java/net/sparkzz/command/ShopCommand.java @@ -22,6 +22,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -85,8 +86,8 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman .map(m -> m.toString().toLowerCase()).collect(Collectors.toList()); } - Store currentStore = InventoryManagementSystem.locateCurrentStore(((Player) sender)); - Set shopItems = (currentStore != null ? currentStore.getItems().keySet() : Collections.emptySet()); + Optional currentStore = InventoryManagementSystem.locateCurrentStore(((Player) sender)); + Set shopItems = (currentStore.isPresent() ? currentStore.get().getItems().keySet() : Collections.emptySet()); // Buy/Remove command autocomplete item list if (args[0].equalsIgnoreCase("buy") || args[0].equalsIgnoreCase("remove")) diff --git a/src/main/java/net/sparkzz/command/SubCommand.java b/src/main/java/net/sparkzz/command/SubCommand.java index 12d8e58..d14bd72 100644 --- a/src/main/java/net/sparkzz/command/SubCommand.java +++ b/src/main/java/net/sparkzz/command/SubCommand.java @@ -1,5 +1,6 @@ package net.sparkzz.command; +import net.sparkzz.shops.Shops; import net.sparkzz.shops.Store; import net.sparkzz.util.Notifiable; import org.bukkit.command.Command; @@ -8,7 +9,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; /** * Interface for sub command layout @@ -40,20 +40,7 @@ public abstract class SubCommand extends Notifiable { * @param nameOrUUID input name or UUID * @return the optional store if found or optional empty if not found or duplicates are found */ - protected Optional identifyStore(String nameOrUUID) { - Optional store = Optional.empty(); - - if (nameOrUUID.contains("~")) { - String[] input = nameOrUUID.split("~"); - - stores = Store.STORES.stream().filter(s -> s.getName().equalsIgnoreCase(input[0]) && s.getUUID().toString().equalsIgnoreCase(input[1])).collect(Collectors.toCollection(ArrayList::new)); - } else { - stores = Store.STORES.stream().filter(s -> s.getName().equalsIgnoreCase(nameOrUUID) || s.getUUID().toString().equalsIgnoreCase(nameOrUUID)).collect(Collectors.toCollection(ArrayList::new)); - } - - if (stores.size() == 1) - store = Optional.of(stores.get(0)); - - return store; + protected Optional identifyStore(String nameOrUUID) throws Shops.MultipleStoresMatchedException { + return Store.identifyStore(nameOrUUID); } } \ No newline at end of file diff --git a/src/main/java/net/sparkzz/command/sub/AddCommand.java b/src/main/java/net/sparkzz/command/sub/AddCommand.java index 90279a6..9f7772a 100644 --- a/src/main/java/net/sparkzz/command/sub/AddCommand.java +++ b/src/main/java/net/sparkzz/command/sub/AddCommand.java @@ -26,7 +26,7 @@ public boolean process(CommandSender sender, Command command, String label, Stri setArgsAsAttributes(args); Material material = (Material) setAttribute("material", Material.matchMaterial(args[1])); Player player = (Player) setAttribute("sender", sender); - Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player)); + Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player).orElse(null)); int quantity = (Integer) setAttribute("quantity", 0); String message = ""; diff --git a/src/main/java/net/sparkzz/command/sub/BrowseCommand.java b/src/main/java/net/sparkzz/command/sub/BrowseCommand.java index 108b3f2..a156540 100644 --- a/src/main/java/net/sparkzz/command/sub/BrowseCommand.java +++ b/src/main/java/net/sparkzz/command/sub/BrowseCommand.java @@ -8,8 +8,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import static net.sparkzz.util.Notifier.CipherKey.INVALID_PAGE_NUM; -import static net.sparkzz.util.Notifier.CipherKey.NO_STORE_FOUND; +import static net.sparkzz.util.Notifier.CipherKey.*; /** * Browse subcommand used for browsing items to a shop @@ -24,7 +23,7 @@ public boolean process(CommandSender sender, Command command, String label, Stri resetAttributes(); setArgsAsAttributes(args); Player player = (Player) setAttribute("sender", sender); - Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player)); + Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player).orElse(null)); if (store == null) { Notifier.process(player, NO_STORE_FOUND, getAttributes()); @@ -33,6 +32,11 @@ public boolean process(CommandSender sender, Command command, String label, Stri int pageNumber = (args.length > 1) ? Integer.parseInt(args[1]) : 1; + if (store.getItems().isEmpty()) { + Notifier.process(sender, STORE_NO_ITEMS, getAttributes()); + return true; + } + String page = Notifier.Paginator.buildBrowsePage(store, pageNumber); if (page == null) { diff --git a/src/main/java/net/sparkzz/command/sub/BuyCommand.java b/src/main/java/net/sparkzz/command/sub/BuyCommand.java index 72e8c40..82d7509 100644 --- a/src/main/java/net/sparkzz/command/sub/BuyCommand.java +++ b/src/main/java/net/sparkzz/command/sub/BuyCommand.java @@ -28,7 +28,7 @@ public boolean process(CommandSender sender, Command command, String label, Stri Material material = (Material) setAttribute("material", Material.matchMaterial(args[1])); Player player = (Player) setAttribute("sender", sender); int quantity = (Integer) setAttribute("quantity", 1); - Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player)); + Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player).orElse(null)); if (store == null) { Notifier.process(player, NO_STORE_FOUND, getAttributes()); diff --git a/src/main/java/net/sparkzz/command/sub/CreateCommand.java b/src/main/java/net/sparkzz/command/sub/CreateCommand.java index 1409729..0fb3f6d 100644 --- a/src/main/java/net/sparkzz/command/sub/CreateCommand.java +++ b/src/main/java/net/sparkzz/command/sub/CreateCommand.java @@ -104,7 +104,6 @@ public boolean process(CommandSender sender, Command command, String label, Stri double limitMaxY = (double) setAttribute("limit-max-y", maxDims[1]); double limitMaxZ = (double) setAttribute("limit-max-z", maxDims[2]); - // TODO: make 0 or negative limits ignore check if ((maxX - minX) < limitMinX || (maxY - minY) < limitMinY || (maxZ - minZ) < limitMinZ) { Notifier.process(sender, Notifier.CipherKey.STORE_CREATE_FAIL_MIN_DIMS, getAttributes()); return true; diff --git a/src/main/java/net/sparkzz/command/sub/DeleteCommand.java b/src/main/java/net/sparkzz/command/sub/DeleteCommand.java index 9e511d8..d122dad 100644 --- a/src/main/java/net/sparkzz/command/sub/DeleteCommand.java +++ b/src/main/java/net/sparkzz/command/sub/DeleteCommand.java @@ -25,65 +25,65 @@ public class DeleteCommand extends SubCommand { @Override public boolean process(CommandSender sender, Command command, String label, String[] args) throws NumberFormatException { - resetAttributes(); - setArgsAsAttributes(args); - Optional foundStore = identifyStore(args[1]); - setAttribute("sender", sender); - setAttribute("store", (foundStore.isPresent() ? foundStore.get() : args[1])); - - if (stores.size() > 1) { - Notifier.process(sender, STORE_MULTI_MATCH, getAttributes()); - return true; - } - - if (foundStore.isEmpty()) { - Notifier.process(sender, STORE_NO_STORE_FOUND, getAttributes()); - return true; - } - - boolean ignoreInv = false, ignoreFunds = false; + try { + resetAttributes(); + setArgsAsAttributes(args); + Optional foundStore = identifyStore(args[1]); + setAttribute("sender", sender); + setAttribute("store", (foundStore.isPresent() ? foundStore.get() : args[1])); + + if (foundStore.isEmpty()) { + Notifier.process(sender, STORE_NO_STORE_FOUND, getAttributes()); + return true; + } - // TODO: determine a way to check if a player can remove all items from the shop, if they can, remove them all - // TODO: add force flags (-f will ignore all inventory, then process) (-F will ignore all inventory and finances, then process) - if (args.length == 3) { - switch (args[2]) { - // soft force delete - case "-f" -> ignoreInv = true; - // hard force delete - case "-F" -> { - ignoreInv = true; - ignoreFunds = true; + boolean ignoreInv = false, ignoreFunds = false; + + // TODO: determine a way to check if a player can remove all items from the shop, if they can, remove them all + // TODO: add force flags (-f will ignore all inventory, then process) (-F will ignore all inventory and finances, then process) + if (args.length == 3) { + switch (args[2]) { + // soft force delete + case "-f" -> ignoreInv = true; + // hard force delete + case "-F" -> { + ignoreInv = true; + ignoreFunds = true; + } + default -> { + } } - default -> {} } - } - boolean canInsertAll = false; - Store store = foundStore.get(); - Player player = (Player) sender; + boolean canInsertAll = false; + Store store = foundStore.get(); + Player player = (Player) sender; - setAttribute("store", store.getName()); + setAttribute("store", store.getName()); - if (!ignoreInv) - canInsertAll = InventoryManagementSystem.canInsertAll(player, store.getItems().entrySet().stream() - .map(entry -> new ItemStack(entry.getKey(), (int) entry.getValue().getOrDefault("quantity", 0))) - .collect(Collectors.toList())); + if (!ignoreInv) + canInsertAll = InventoryManagementSystem.canInsertAll(player, store.getItems().entrySet().stream() + .map(entry -> new ItemStack(entry.getKey(), (int) entry.getValue().getOrDefault("quantity", 0))) + .collect(Collectors.toList())); - if (!ignoreInv && !canInsertAll) { - Notifier.process(sender, STORE_DELETE_INSUFFICIENT_INV_PLAYER, getAttributes()); - return true; - } + if (!ignoreInv && !canInsertAll) { + Notifier.process(sender, STORE_DELETE_INSUFFICIENT_INV_PLAYER, getAttributes()); + return true; + } - if (!ignoreFunds) { - Shops.getEconomy().depositPlayer(player, store.getBalance()); - store.setBalance(0); - } + if (!ignoreFunds) { + Shops.getEconomy().depositPlayer(player, store.getBalance()); + store.setBalance(0); + } - boolean success = Store.STORES.remove(store); + boolean success = Store.STORES.remove(store); - if (success) - Notifier.process(sender, STORE_DELETE_SUCCESS, getAttributes()); - else Notifier.process(sender, STORE_DELETE_FAIL, getAttributes()); + if (success) + Notifier.process(sender, STORE_DELETE_SUCCESS, getAttributes()); + else Notifier.process(sender, STORE_DELETE_FAIL, getAttributes()); + } catch (Shops.MultipleStoresMatchedException exception) { + Notifier.process(sender, STORE_MULTI_MATCH, getAttributes()); + } return true; } } \ No newline at end of file diff --git a/src/main/java/net/sparkzz/command/sub/DepositCommand.java b/src/main/java/net/sparkzz/command/sub/DepositCommand.java index ef7069a..76409ca 100644 --- a/src/main/java/net/sparkzz/command/sub/DepositCommand.java +++ b/src/main/java/net/sparkzz/command/sub/DepositCommand.java @@ -24,7 +24,7 @@ public boolean process(CommandSender sender, Command command, String label, Stri resetAttributes(); setArgsAsAttributes(args); Player player = (Player) setAttribute("sender", sender); - Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player)); + Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player).orElse(null)); double amount = (Double) setAttribute("amount", Double.parseDouble(args[1])); if (store == null) { diff --git a/src/main/java/net/sparkzz/command/sub/RemoveCommand.java b/src/main/java/net/sparkzz/command/sub/RemoveCommand.java index f655848..9e00331 100644 --- a/src/main/java/net/sparkzz/command/sub/RemoveCommand.java +++ b/src/main/java/net/sparkzz/command/sub/RemoveCommand.java @@ -26,7 +26,7 @@ public boolean process(CommandSender sender, Command command, String label, Stri setArgsAsAttributes(args); Material material = (Material) setAttribute("material", Material.matchMaterial(args[1])); Player player = (Player) setAttribute("sender", sender); - Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player)); + Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player).orElse(null)); if (store == null) { Notifier.process(player, NO_STORE_FOUND, getAttributes()); diff --git a/src/main/java/net/sparkzz/command/sub/SellCommand.java b/src/main/java/net/sparkzz/command/sub/SellCommand.java index 5d24da4..2216262 100644 --- a/src/main/java/net/sparkzz/command/sub/SellCommand.java +++ b/src/main/java/net/sparkzz/command/sub/SellCommand.java @@ -27,7 +27,7 @@ public boolean process(CommandSender sender, Command command, String label, Stri setArgsAsAttributes(args); Material material = (Material) setAttribute("material", Material.matchMaterial(args[1])); Player player = (Player) setAttribute("sender", sender); - Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player)); + Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player).orElse(null)); int quantity = (Integer) setAttribute("quantity", 1); if (store == null) { diff --git a/src/main/java/net/sparkzz/command/sub/TransferCommand.java b/src/main/java/net/sparkzz/command/sub/TransferCommand.java index 1e422ad..3b8c526 100644 --- a/src/main/java/net/sparkzz/command/sub/TransferCommand.java +++ b/src/main/java/net/sparkzz/command/sub/TransferCommand.java @@ -25,54 +25,54 @@ public class TransferCommand extends SubCommand { @Override public boolean process(CommandSender sender, Command command, String label, String[] args) throws NumberFormatException { - resetAttributes(); - setArgsAsAttributes(args); - setAttribute("sender", sender); - Optional foundStore = identifyStore(args[1]); - setAttribute("store", (foundStore.isPresent() ? foundStore.get() : args[1])); - - if (stores.size() > 1) { - Notifier.process(sender, STORE_MULTI_MATCH, getAttributes()); - return true; - } + try { + resetAttributes(); + setArgsAsAttributes(args); + setAttribute("sender", sender); + Optional foundStore; + foundStore = identifyStore(args[1]); + setAttribute("store", (foundStore.isPresent() ? foundStore.get() : args[1])); + + if (foundStore.isEmpty()) { + Notifier.process(sender, STORE_NO_STORE_FOUND, getAttributes()); + return true; + } - if (foundStore.isEmpty()) { - Notifier.process(sender, STORE_NO_STORE_FOUND, getAttributes()); - return true; - } + boolean isUUID = args[2].matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); - boolean isUUID = args[2].matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); + // TODO: remove mock references once Server mocking is updated to fix issues with getServer() + setAttribute("target", args[2]); + Server server = (!Shops.isTest()) ? Shops.getPlugin(Shops.class).getServer() : Shops.getMockServer(); + OfflinePlayer targetPlayer = (!isUUID) ? server.getPlayer(args[2]) : server.getOfflinePlayer(UUID.fromString(args[2])); - // TODO: remove mock references once Server mocking is updated to fix issues with getServer() - setAttribute("target", args[2]); - Server server = (!Shops.isTest()) ? Shops.getPlugin(Shops.class).getServer() : Shops.getMockServer(); - OfflinePlayer targetPlayer = (!isUUID) ? server.getPlayer(args[2]) : server.getOfflinePlayer(UUID.fromString(args[2])); + if (targetPlayer == null) { + Notifier.process(sender, PLAYER_NOT_FOUND, getAttributes()); + return true; + } - if (targetPlayer == null) { - Notifier.process(sender, PLAYER_NOT_FOUND, getAttributes()); - return true; - } + Store store = foundStore.get(); - Store store = foundStore.get(); + setAttribute("target", targetPlayer.getName()); - setAttribute("target", targetPlayer.getName()); + if (!sender.isOp()) { + int shopsOwned = 0; - if (!sender.isOp()) { - int shopsOwned = 0; + for (Store existingStore : Store.STORES) + if (existingStore.getOwner().equals(targetPlayer.getUniqueId())) { + shopsOwned++; + } - for (Store existingStore : Store.STORES) - if (existingStore.getOwner().equals(targetPlayer.getUniqueId())) { - shopsOwned++; + if (shopsOwned >= (int) setAttribute("max-stores", Config.getMaxOwnedStores())) { + Notifier.process(sender, Notifier.CipherKey.STORE_TRANSFER_FAIL_MAX_STORES, getAttributes()); + return true; } - - if (shopsOwned >= (int) setAttribute("max-stores", Config.getMaxOwnedStores())) { - Notifier.process(sender, Notifier.CipherKey.STORE_TRANSFER_FAIL_MAX_STORES, getAttributes()); - return true; } - } - store.setOwner(targetPlayer.getUniqueId()); - Notifier.process(sender, STORE_TRANSFER_SUCCESS, getAttributes()); + store.setOwner(targetPlayer.getUniqueId()); + Notifier.process(sender, STORE_TRANSFER_SUCCESS, getAttributes()); + } catch (Shops.MultipleStoresMatchedException exception) { + Notifier.process(sender, STORE_MULTI_MATCH, getAttributes()); + } return true; } -} \ No newline at end of file +} diff --git a/src/main/java/net/sparkzz/command/sub/UpdateCommand.java b/src/main/java/net/sparkzz/command/sub/UpdateCommand.java index 04ff2cb..78942b9 100644 --- a/src/main/java/net/sparkzz/command/sub/UpdateCommand.java +++ b/src/main/java/net/sparkzz/command/sub/UpdateCommand.java @@ -31,7 +31,7 @@ public boolean process(CommandSender sender, Command command, String label, Stri resetAttributes(); setArgsAsAttributes(args); Player player = (Player) setAttribute("sender", sender); - Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player)); + Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player).orElse(null)); if (args.length >= 8 && args[1].equalsIgnoreCase("location")) { switch (args.length) { diff --git a/src/main/java/net/sparkzz/command/sub/WithdrawCommand.java b/src/main/java/net/sparkzz/command/sub/WithdrawCommand.java index 2930346..c7f5ba1 100644 --- a/src/main/java/net/sparkzz/command/sub/WithdrawCommand.java +++ b/src/main/java/net/sparkzz/command/sub/WithdrawCommand.java @@ -24,7 +24,7 @@ public boolean process(CommandSender sender, Command command, String label, Stri resetAttributes(); setArgsAsAttributes(args); Player player = (Player) setAttribute("sender", sender); - Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player)); + Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player).orElse(null)); double amount = (Double) setAttribute("amount", (args[1].equalsIgnoreCase("all")) ? store.getBalance() : Double.parseDouble(args[1])); if (store == null) { diff --git a/src/main/java/net/sparkzz/event/EntranceListener.java b/src/main/java/net/sparkzz/event/EntranceListener.java index d935785..77b6ea0 100644 --- a/src/main/java/net/sparkzz/event/EntranceListener.java +++ b/src/main/java/net/sparkzz/event/EntranceListener.java @@ -46,8 +46,9 @@ public void onPlayerMove(PlayerMoveEvent event) { playerStoreStatus.put(player, true); Notifier.process(player, Notifier.CipherKey.STORE_WELCOME_MSG, getAttributes()); } else if (!isInShop && playerStoreStatus.getOrDefault(player, true)) { + if (playerStoreStatus.containsKey(player)) + Notifier.process(player, Notifier.CipherKey.STORE_GOODBYE_MSG, getAttributes()); playerStoreStatus.put(player, false); - Notifier.process(player, Notifier.CipherKey.STORE_GOODBYE_MSG, getAttributes()); } } } diff --git a/src/main/java/net/sparkzz/shops/Shops.java b/src/main/java/net/sparkzz/shops/Shops.java index eb001bd..752e461 100644 --- a/src/main/java/net/sparkzz/shops/Shops.java +++ b/src/main/java/net/sparkzz/shops/Shops.java @@ -143,4 +143,13 @@ public static Server getMockServer() { public static void setMockServer(Server mockServer) { server = mockServer; } + + /** + * Exception for matching multiple Stores when expecting a single Store + */ + public static class MultipleStoresMatchedException extends RuntimeException { + public MultipleStoresMatchedException(String message) { + super(message); + } + } } \ No newline at end of file diff --git a/src/main/java/net/sparkzz/shops/Store.java b/src/main/java/net/sparkzz/shops/Store.java index c6ee15b..1a1c79b 100644 --- a/src/main/java/net/sparkzz/shops/Store.java +++ b/src/main/java/net/sparkzz/shops/Store.java @@ -1,15 +1,21 @@ package net.sparkzz.shops; +import net.sparkzz.util.Config; import net.sparkzz.util.Cuboid; import org.bukkit.Material; +import org.bukkit.World; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Setting; import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; +import java.util.stream.Collectors; /** * The Store class is instantiable and serialized/deserialized around the data.shops file @@ -21,7 +27,11 @@ public class Store { * This List contains all stores that have been created */ public static final ArrayList STORES = new ArrayList<>(); - private static Store defaultStore; + + /** + * This Map contains all default stores per world + */ + public static final Map<@Nullable World, Store> DEFAULT_STORES = new HashMap<>(); @Setting private boolean infFunds = false; @Setting private boolean infStock = false; @@ -80,21 +90,51 @@ public Store(String name, UUID owner, Cuboid cuboidLocation) { } /** - * Gets the default store + * Gets the default store based on the input world + * + * @param world the world to check for the default store + * @return the default store based on the world + */ + public static Optional getDefaultStore(@Nullable World world) { + Optional nullDefaultStore = Optional.ofNullable(DEFAULT_STORES.get(null)); + + return nullDefaultStore.isPresent() ? nullDefaultStore : Optional.ofNullable(DEFAULT_STORES.get(world)); + } + + /** + * The identifyStore method is a common method for identifying a store based on a string name, UUID or a combination + * using the format name~UUID * - * @return the default store + * @param nameOrUUID input name or UUID + * @return the optional store if found or optional empty if not found or duplicates are found */ - public static Store getDefaultStore() { - return defaultStore; + public static Optional identifyStore(String nameOrUUID) throws Shops.MultipleStoresMatchedException { + List identifiedStores; + Optional store = Optional.empty(); + + if (nameOrUUID.contains("~")) { + String[] input = nameOrUUID.split("~"); + + identifiedStores = STORES.stream().filter(s -> s.getName().equalsIgnoreCase(input[0]) && s.getUUID().toString().equalsIgnoreCase(input[1])).collect(Collectors.toCollection(ArrayList::new)); + } else { + identifiedStores = STORES.stream().filter(s -> s.getName().equalsIgnoreCase(nameOrUUID) || s.getUUID().toString().equalsIgnoreCase(nameOrUUID)).collect(Collectors.toCollection(ArrayList::new)); + } + + if (identifiedStores.size() == 1) + store = Optional.of(identifiedStores.get(0)); + else if (identifiedStores.size() > 1) throw new Shops.MultipleStoresMatchedException("Multiple Stores matched"); + + return store; } /** - * Sets the default store + * Sets the default store(s) per world (1 default store per world) * * @param store the default store to be set */ - public static void setDefaultStore(Store store) { - defaultStore = store; + public static void setDefaultStore(World world, Store store) { + DEFAULT_STORES.put(world, store); + Config.setDefaultStore(world, store); } /** @@ -146,7 +186,8 @@ public double getBuyPrice(Material material) { /** * Gets the cuboid location of the store - * @return + * + * @return the cuboid location of the store */ public Cuboid getCuboidLocation() { return cuboidLocation; diff --git a/src/main/java/net/sparkzz/util/Config.java b/src/main/java/net/sparkzz/util/Config.java index 264d667..7b47f37 100644 --- a/src/main/java/net/sparkzz/util/Config.java +++ b/src/main/java/net/sparkzz/util/Config.java @@ -1,13 +1,16 @@ package net.sparkzz.util; import net.sparkzz.shops.Shops; +import net.sparkzz.shops.Store; import org.bukkit.Bukkit; import org.bukkit.World; +import org.jetbrains.annotations.Nullable; import org.spongepowered.configurate.CommentedConfigurationNode; import org.spongepowered.configurate.serialize.SerializationException; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.logging.Logger; /** @@ -153,6 +156,27 @@ public static List getOffLimitsCuboids() { return cuboids; } + /** + * Gets the default Store for the input world + * + * @param world the world to get the default Store from + * @return the default Store for the input world + */ + public static Optional getDefaultStore(@Nullable World world) { + CommentedConfigurationNode defaults = rootNode.node("store").node("default"); + + if (defaults.hasChild("null")) + return Store.identifyStore(defaults.node("null").getString()); + + if (defaults.hasChild(world.getName())) { + return Store.identifyStore(defaults.node(world.getName()).getString()); + } else if (defaults.hasChild(world.getUID())) { + return Store.identifyStore(defaults.node(world.getUID()).getString()); + } + + return Optional.empty(); + } + /** * Gets the custom response message to be sent to the player in place of the defaults * @@ -184,6 +208,32 @@ public static void addOffLimitsArea(Cuboid cuboid) { } } + /** + * Sets the default Store for a selected world + * + * @param world the world to have the Store associated with + * @param store the Store to be associated with the input world + */ + public static void setDefaultStore(@Nullable World world, @Nullable Store store) { + try { + CommentedConfigurationNode defaults = rootNode.node("store", "default"); + + if (store == null) { + defaults.removeChild((world == null) ? "'null'" : world.getName()); + return; + } + + if (world == null) { + defaults.node("'null'", store.getUUID()); + return; + } + + defaults.node(world.getName()).set(store.getUUID()); + } catch (SerializationException exception) { + log.warning(String.format("Unable to set default store: (World: %s, Store: %s)", world, store)); + } + } + /** * Sets the maximum dimensions * diff --git a/src/main/java/net/sparkzz/util/InventoryManagementSystem.java b/src/main/java/net/sparkzz/util/InventoryManagementSystem.java index ac4c0cf..b2bc1fc 100644 --- a/src/main/java/net/sparkzz/util/InventoryManagementSystem.java +++ b/src/main/java/net/sparkzz/util/InventoryManagementSystem.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.ListIterator; import java.util.Map; +import java.util.Optional; /** * Helper class to manage player and store inventory @@ -171,12 +172,12 @@ public static int getAvailableSpace(Store store, Material material) { * @param player the player to have its location checked for the current store * @return the store the player is currently located in */ - public static Store locateCurrentStore(Player player) { - Store store = Store.getDefaultStore(); + public static Optional locateCurrentStore(Player player) { + Optional store = Store.getDefaultStore(player.getWorld()); for (Store currentStore : Store.STORES) { if (currentStore.getCuboidLocation() != null && currentStore.getCuboidLocation().isPlayerWithin(player)) { - store = currentStore; + store = Optional.of(currentStore); break; } } diff --git a/src/main/java/net/sparkzz/util/Notifier.java b/src/main/java/net/sparkzz/util/Notifier.java index 05d625d..b76428d 100644 --- a/src/main/java/net/sparkzz/util/Notifier.java +++ b/src/main/java/net/sparkzz/util/Notifier.java @@ -194,6 +194,7 @@ public enum CipherKey { STORE_DELETE_INSUFFICIENT_INV_PLAYER("§cYou don't have enough inventory space to delete the store, please try removing items first or use the '-f' flag to ignore inventory!"), STORE_GOODBYE_MSG("§9We hope to see you again!"), STORE_MULTI_MATCH("§cMultiple stores matched, please specify the store's UUID!"), + STORE_NO_ITEMS("§cThis store is currently empty!"), STORE_NO_STORE_FOUND("§cCould not find a store with the name and/or UUID of: §6{store}§c!"), STORE_TRANSFER_FAIL_MAX_STORES("§c{target} can't have any more stores!§f Maximum stores: {max-stores}."), STORE_TRANSFER_SUCCESS("§aYou have successfully transferred §6{store}§a to player §6{target}§a!"), diff --git a/src/main/java/net/sparkzz/util/Transaction.java b/src/main/java/net/sparkzz/util/Transaction.java index a163279..6e3a8ab 100644 --- a/src/main/java/net/sparkzz/util/Transaction.java +++ b/src/main/java/net/sparkzz/util/Transaction.java @@ -40,7 +40,7 @@ public Transaction(Player player, ItemStack itemStack, TransactionType type) { setAttribute("material", itemStack.getType()); setAttribute("quantity", itemStack.getAmount()); - store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player)); + store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player).orElse(null)); cost = (double) setAttribute("cost", switch (type) { case PURCHASE -> (store.getBuyPrice(itemStack.getType()) * itemStack.getAmount()); case SALE -> (store.getSellPrice(itemStack.getType()) * itemStack.getAmount()); diff --git a/src/main/java/net/sparkzz/util/Warehouse.java b/src/main/java/net/sparkzz/util/Warehouse.java index 3d0f7cd..f0299b3 100644 --- a/src/main/java/net/sparkzz/util/Warehouse.java +++ b/src/main/java/net/sparkzz/util/Warehouse.java @@ -33,6 +33,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.logging.Logger; import java.util.stream.DoubleStream; @@ -132,9 +133,19 @@ private static void loadStores() { for (CommentedConfigurationNode currentNode : storeConfig.node("stores").childrenList()) STORES.add(storeMapper.load(currentNode)); + Optional nullDefaultStore = Config.getDefaultStore(Bukkit.getWorld("null")); + + if (nullDefaultStore.isPresent()) { + Store.setDefaultStore(null, nullDefaultStore.get()); + } else { + for (World world : Bukkit.getWorlds()) { + Optional defaultStoreForWorld = Config.getDefaultStore(world); + + defaultStoreForWorld.ifPresent(store -> Store.setDefaultStore(world, store)); + } + } + log.info(String.format("%d %s loaded", STORES.size(), (STORES.size() == 1) ? "shop" : "shops")); - if (!STORES.isEmpty()) - Store.setDefaultStore(STORES.get(0)); // TODO: remove once stores are dynamically loaded } catch (SerializationException e) { throw new RuntimeException(e); } diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 683331a..29b45b3 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -1,4 +1,7 @@ store: + default: [] # remove square brackets if setting default store(s) per world +# 'null': d19ba2a1-0a24-4977-baee-638ee15f2ccf +# world: a307b2a8-cc58-4bc1-8ee4-910053ac99d2 max-owned-stores: 1 min-dimensions: x: 3 diff --git a/src/test/java/net/sparkzz/command/InfoCommandTest.java b/src/test/java/net/sparkzz/command/InfoCommandTest.java index 71cce16..13d9ae5 100644 --- a/src/test/java/net/sparkzz/command/InfoCommandTest.java +++ b/src/test/java/net/sparkzz/command/InfoCommandTest.java @@ -37,19 +37,20 @@ static void setUp() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); plugin = MockBukkit.load(Shops.class); + loadConfig(); mrSparkzz = server.addPlayer("MrSparkzz"); player2 = server.addPlayer(); mrSparkzz.setOp(true); - Store.setDefaultStore(new Store("BetterBuy", mrSparkzz.getUniqueId())); + Store.setDefaultStore(mrSparkzz.getWorld(), new Store("BetterBuy", mrSparkzz.getUniqueId())); } @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } diff --git a/src/test/java/net/sparkzz/command/ShopCommandTest.java b/src/test/java/net/sparkzz/command/ShopCommandTest.java index bd43574..7ec5873 100644 --- a/src/test/java/net/sparkzz/command/ShopCommandTest.java +++ b/src/test/java/net/sparkzz/command/ShopCommandTest.java @@ -43,6 +43,7 @@ static void setUp() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); mrSparkzz = server.addPlayer("MrSparkzz"); player = server.addPlayer(); @@ -55,9 +56,9 @@ static void setUp() { @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } @@ -69,14 +70,14 @@ class OnTabCompleteTests { @BeforeEach void setUpShops() { - Store.setDefaultStore(new Store("BetterBuy", mrSparkzz.getUniqueId())); + Store.setDefaultStore(mrSparkzz.getWorld(), new Store("BetterBuy", mrSparkzz.getUniqueId())); new Store("DiscountPlus", mrSparkzz.getUniqueId()); new Store("DiscountMinus", mrSparkzz.getUniqueId()); } @AfterEach void tearDownShops() { - Store.setDefaultStore(null); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } @@ -140,7 +141,7 @@ void testShopTabComplete_Add2Args() { @DisplayName("Test Shop - 2 args - buy tab complete") @Order(24) void testShopTabComplete_Buy2Args() { - Set shopItems = InventoryManagementSystem.locateCurrentStore(mrSparkzz).getItems().keySet(); + Set shopItems = InventoryManagementSystem.locateCurrentStore(mrSparkzz).get().getItems().keySet(); List expectedOptions = Arrays.stream(shopItems.toArray()) .map(m -> m.toString().toLowerCase()).toList(); @@ -154,7 +155,7 @@ void testShopTabComplete_Buy2Args() { @DisplayName("Test Shop - 2 args - remove tab complete") @Order(25) void testShopTabComplete_Remove2Args() { - Set shopItems = InventoryManagementSystem.locateCurrentStore(mrSparkzz).getItems().keySet(); + Set shopItems = InventoryManagementSystem.locateCurrentStore(mrSparkzz).get().getItems().keySet(); List expectedOptions = Arrays.stream(shopItems.toArray()) .map(m -> m.toString().toLowerCase()).toList(); @@ -168,7 +169,7 @@ void testShopTabComplete_Remove2Args() { @DisplayName("Test Shop - 2 args - update tab complete when op") @Order(26) void testShopTabComplete_Update2Args_WhenOp() { - Set shopItems = InventoryManagementSystem.locateCurrentStore(mrSparkzz).getItems().keySet(); + Set shopItems = InventoryManagementSystem.locateCurrentStore(mrSparkzz).get().getItems().keySet(); List expectedOptions = Arrays.stream(shopItems.toArray()) .map(m -> m.toString().toLowerCase()).collect(Collectors.toList()); @@ -183,7 +184,7 @@ void testShopTabComplete_Update2Args_WhenOp() { @DisplayName("Test Shop - 2 args - update tab complete when not op") @Order(27) void testShopTabComplete_Update2Args_WhenNotOp() { - Set shopItems = InventoryManagementSystem.locateCurrentStore(player).getItems().keySet(); + Set shopItems = InventoryManagementSystem.locateCurrentStore(player).get().getItems().keySet(); List expectedOptions = Arrays.stream(shopItems.toArray()) .map(m -> m.toString().toLowerCase()).collect(Collectors.toList()); diff --git a/src/test/java/net/sparkzz/command/SubCommandTest.java b/src/test/java/net/sparkzz/command/SubCommandTest.java index 86fbd48..10377b7 100644 --- a/src/test/java/net/sparkzz/command/SubCommandTest.java +++ b/src/test/java/net/sparkzz/command/SubCommandTest.java @@ -19,8 +19,7 @@ import java.util.Optional; -import static net.sparkzz.shops.TestHelper.printMessage; -import static net.sparkzz.shops.TestHelper.printSuccessMessage; +import static net.sparkzz.shops.TestHelper.*; import static org.junit.jupiter.api.Assertions.assertEquals; @SuppressWarnings("SpellCheckingInspection") @@ -39,18 +38,19 @@ static void setUp() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); PlayerMock mrSparkzz = server.addPlayer("MrSparkzz"); mrSparkzz.setOp(true); - Store.setDefaultStore(store = new Store("BetterBuy", mrSparkzz.getUniqueId())); + Store.setDefaultStore(mrSparkzz.getWorld(), store = new Store("BetterBuy", mrSparkzz.getUniqueId())); } @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } diff --git a/src/test/java/net/sparkzz/command/sub/AddCommandTest.java b/src/test/java/net/sparkzz/command/sub/AddCommandTest.java index 40f10b0..0f705b4 100644 --- a/src/test/java/net/sparkzz/command/sub/AddCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/AddCommandTest.java @@ -33,22 +33,23 @@ static void setUpAddCommand() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); mrSparkzz = server.addPlayer("MrSparkzz"); player2 = server.addPlayer(); mrSparkzz.setOp(true); - Store.setDefaultStore(new Store("BetterBuy", mrSparkzz.getUniqueId())); - Store.getDefaultStore().getItems().clear(); - Store.getDefaultStore().addItem(emeralds.getType(), 10, -1, 2D, 1.5D); - Store.getDefaultStore().addFunds(100); + Store.setDefaultStore(mrSparkzz.getWorld(), new Store("BetterBuy", mrSparkzz.getUniqueId())); + Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().clear(); + Store.getDefaultStore(mrSparkzz.getWorld()).get().addItem(emeralds.getType(), 10, -1, 2D, 1.5D); + Store.getDefaultStore(mrSparkzz.getWorld()).get().addFunds(100); } @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); } @BeforeEach @@ -82,7 +83,7 @@ void testAddCommand_AddOne() { performCommand(mrSparkzz, "shop add emerald 1"); assertEquals(String.format("%sYou have successfully added %s%s%s to the shop!", GREEN, GOLD, (quantity > 0) ? String.valueOf(quantity) + GREEN + " of " + GOLD + material : material, GREEN), mrSparkzz.nextMessage()); assertEquals(63, Objects.requireNonNull(mrSparkzz.getInventory().getItem(0)).getAmount()); - assertEquals(11, Store.getDefaultStore().getItems().get(material).get("quantity").intValue()); + assertEquals(11, Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().get(material).get("quantity").intValue()); printSuccessMessage("add command test - add 1"); } @@ -97,7 +98,7 @@ void testAddCommand_AddAll() { performCommand(mrSparkzz, "shop add emerald all"); assertEquals(String.format("%sYou have successfully added %s%s%s to the shop!", GREEN, GOLD, (quantity > 0) ? String.valueOf(quantity) + GREEN + " of " + GOLD + material : material, GREEN), mrSparkzz.nextMessage()); assertFalse(mrSparkzz.getInventory().contains(material)); - assertEquals(11, Store.getDefaultStore().getItems().get(material).get("quantity").intValue()); + assertEquals(11, Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().get(material).get("quantity").intValue()); printSuccessMessage("add command test - add all"); } diff --git a/src/test/java/net/sparkzz/command/sub/BrowseCommandTest.java b/src/test/java/net/sparkzz/command/sub/BrowseCommandTest.java index c4078da..00a3d11 100644 --- a/src/test/java/net/sparkzz/command/sub/BrowseCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/BrowseCommandTest.java @@ -6,7 +6,11 @@ import net.sparkzz.shops.Shops; import net.sparkzz.shops.Store; import net.sparkzz.shops.mocks.MockVault; +import net.sparkzz.util.Notifier; +import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.WorldCreator; import org.bukkit.plugin.PluginDescriptionFile; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; @@ -19,7 +23,6 @@ import org.junit.jupiter.api.TestMethodOrder; import static net.sparkzz.shops.TestHelper.*; -import static org.bukkit.ChatColor.RED; import static org.junit.jupiter.api.Assertions.assertEquals; @SuppressWarnings("SpellCheckingInspection") @@ -33,27 +36,30 @@ public class BrowseCommandTest { static void setUp() { printMessage("==[ TEST BROWSE COMMAND ]=="); ServerMock server = MockBukkit.getOrCreateMock(); + World world = server.createWorld(WorldCreator.name("world")); MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); mrSparkzz = server.addPlayer("MrSparkzz"); player2 = server.addPlayer(); mrSparkzz.setOp(true); + mrSparkzz.setLocation(new Location(world, 0, 0, 0)); } @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); } @BeforeEach void setUpShopItems() { Store store; - Store.setDefaultStore((store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); + Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); store.addItem(Material.EMERALD, 3, 64, 24.5, 12); store.addItem(Material.ACACIA_LOG, 2018, -1, 2, 1); @@ -79,7 +85,7 @@ void tearDownStore() { @Order(1) void testBrowseShop_Permissions() { performCommand(player2, "shop browse"); - assertEquals(String.format("%sYou do not have permission to use this command!", RED), player2.nextMessage()); + assertEquals(Notifier.compose(Notifier.CipherKey.NO_PERMS_CMD, null), player2.nextMessage()); printSuccessMessage("browse command permission check"); } @@ -109,7 +115,7 @@ void testBrowseShop() { @DisplayName("Test Browse - main functionality - invalid shop") @Order(2) void testBrowse_InvalidShop() { - Store.setDefaultStore(null); + Store.DEFAULT_STORES.clear(); performCommand(mrSparkzz, "shop browse"); assertEquals("§cYou are not currently in a store!", mrSparkzz.nextMessage()); printSuccessMessage("browse command test - invalid shop"); diff --git a/src/test/java/net/sparkzz/command/sub/BuyCommandTest.java b/src/test/java/net/sparkzz/command/sub/BuyCommandTest.java index 46be776..fc1b01c 100644 --- a/src/test/java/net/sparkzz/command/sub/BuyCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/BuyCommandTest.java @@ -39,26 +39,27 @@ static void setUp() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); mrSparkzz = server.addPlayer("MrSparkzz"); player2 = server.addPlayer(); mrSparkzz.setOp(true); - Store.setDefaultStore((store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); + Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); } @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } @BeforeEach void setUpBuyCommand() { - Store.getDefaultStore().getItems().clear(); - Store.getDefaultStore().addItem(emeralds.getType(), emeralds.getAmount(), -1, 2D, 1.5D); + Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().clear(); + Store.getDefaultStore(mrSparkzz.getWorld()).get().addItem(emeralds.getType(), emeralds.getAmount(), -1, 2D, 1.5D); // TODO: Shops.getEconomy().depositPlayer(mrSparkzz, 50); } diff --git a/src/test/java/net/sparkzz/command/sub/CreateCommandTest.java b/src/test/java/net/sparkzz/command/sub/CreateCommandTest.java index 1d2510d..48bd3cb 100644 --- a/src/test/java/net/sparkzz/command/sub/CreateCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/CreateCommandTest.java @@ -51,10 +51,9 @@ static void setUp() { @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); unLoadConfig(); + Store.DEFAULT_STORES.clear(); } @AfterEach @@ -64,7 +63,7 @@ void tearDownStore() { @BeforeEach void setUpStore() { - Store.setDefaultStore(new Store("BetterBuy", mrSparkzz.getUniqueId(), new Cuboid(world, -50, 10, -25, -100, 60, -50))); + Store.setDefaultStore(mrSparkzz.getWorld(), new Store("BetterBuy", mrSparkzz.getUniqueId(), new Cuboid(world, -50, 10, -25, -100, 60, -50))); } @Test diff --git a/src/test/java/net/sparkzz/command/sub/DeleteCommandTest.java b/src/test/java/net/sparkzz/command/sub/DeleteCommandTest.java index 933d4ab..4f0f7a2 100644 --- a/src/test/java/net/sparkzz/command/sub/DeleteCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/DeleteCommandTest.java @@ -6,6 +6,7 @@ import net.sparkzz.shops.Shops; import net.sparkzz.shops.Store; import net.sparkzz.shops.mocks.MockVault; +import net.sparkzz.util.Notifier; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.inventory.ItemStack; @@ -35,19 +36,20 @@ static void setUp() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); mrSparkzz = server.addPlayer("MrSparkzz"); player2 = server.addPlayer(); mrSparkzz.setOp(true); - Store.setDefaultStore(new Store("BetterBuy", mrSparkzz.getUniqueId())); + Store.setDefaultStore(mrSparkzz.getWorld(), (new Store("BetterBuy", mrSparkzz.getUniqueId()))); } @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } @@ -67,7 +69,7 @@ void tearDownStore() { @Order(1) void testDeleteShop_Permissions() { performCommand(player2, "shop delete DollHairStore"); - assertEquals(String.format("%sYou do not have permission to use this command!", RED), player2.nextMessage()); + assertEquals(Notifier.compose(Notifier.CipherKey.NO_PERMS_CMD, null), player2.nextMessage()); printSuccessMessage("delete command permission check"); } diff --git a/src/test/java/net/sparkzz/command/sub/DepositCommandTest.java b/src/test/java/net/sparkzz/command/sub/DepositCommandTest.java index 6585804..315e823 100644 --- a/src/test/java/net/sparkzz/command/sub/DepositCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/DepositCommandTest.java @@ -6,11 +6,13 @@ import net.sparkzz.shops.Shops; import net.sparkzz.shops.Store; import net.sparkzz.shops.mocks.MockVault; +import net.sparkzz.util.Notifier; import org.bukkit.plugin.PluginDescriptionFile; import org.junit.jupiter.api.*; import static net.sparkzz.shops.TestHelper.*; -import static org.bukkit.ChatColor.*; +import static org.bukkit.ChatColor.GOLD; +import static org.bukkit.ChatColor.GREEN; import static org.junit.jupiter.api.Assertions.assertEquals; @SuppressWarnings("SpellCheckingInspection") @@ -28,26 +30,27 @@ static void setUp() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); mrSparkzz = server.addPlayer("MrSparkzz"); player2 = server.addPlayer(); mrSparkzz.setOp(true); - Store.setDefaultStore((store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); + Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); } @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } @BeforeEach void setUpDepositCommand() { // TODO: Shops.getEconomy().depositPlayer(mrSparkzz, 150); - Store.getDefaultStore().setBalance(25); + Store.getDefaultStore(mrSparkzz.getWorld()).get().setBalance(25); } @AfterEach @@ -61,7 +64,7 @@ void tearDownWithdrawCommand() { @Order(1) void testWithdrawCommand_Permissions() { performCommand(player2, "shop deposit 100"); - assertEquals(String.format("%sYou do not have permission to use this command!", RED), player2.nextMessage()); + assertEquals(Notifier.compose(Notifier.CipherKey.NO_PERMS_CMD, null), player2.nextMessage()); printSuccessMessage("deposit command permission check"); } @@ -74,7 +77,7 @@ void testDepositCommand() { performCommand(mrSparkzz, "shop deposit " + amount); assertEquals(String.format("%sYou have successfully deposited %s%s%s to the shop!", GREEN, GOLD, amount, GREEN), mrSparkzz.nextMessage()); - assertEquals(125, Store.getDefaultStore().getBalance()); + assertEquals(125, Store.getDefaultStore(mrSparkzz.getWorld()).get().getBalance()); assertEquals(50, Shops.getEconomy().getBalance(mrSparkzz)); printSuccessMessage("deposit command test"); } diff --git a/src/test/java/net/sparkzz/command/sub/RemoveCommandTest.java b/src/test/java/net/sparkzz/command/sub/RemoveCommandTest.java index e9b0723..a76a81f 100644 --- a/src/test/java/net/sparkzz/command/sub/RemoveCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/RemoveCommandTest.java @@ -41,21 +41,22 @@ static void setUpRemoveCommand() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); mrSparkzz = server.addPlayer("MrSparkzz"); player2 = server.addPlayer(); mrSparkzz.setOp(true); - Store.setDefaultStore(new Store("BetterBuy", mrSparkzz.getUniqueId())); - Store.getDefaultStore().getItems().clear(); - Store.getDefaultStore().addItem(emeralds.getType(), 0, -1, 2D, 1.5D); + Store.setDefaultStore(mrSparkzz.getWorld(), new Store("BetterBuy", mrSparkzz.getUniqueId())); + Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().clear(); + Store.getDefaultStore(mrSparkzz.getWorld()).get().addItem(emeralds.getType(), 0, -1, 2D, 1.5D); } @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } @@ -78,7 +79,7 @@ void testRemoveCommand_RemoveOne() { performCommand(mrSparkzz, "shop remove emerald 1"); assertEquals(String.format("%sYou have successfully removed %s%s%s from the shop!", GREEN, GOLD, material, GREEN), mrSparkzz.nextMessage()); assertEquals(63, Objects.requireNonNull(mrSparkzz.getInventory().getItem(0)).getAmount()); - assertEquals(11, Store.getDefaultStore().getItems().get(material).get("quantity").intValue()); + assertEquals(11, Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().get(material).get("quantity").intValue()); printSuccessMessage("remove command test - remove 1 of type from shop"); } @@ -90,7 +91,7 @@ void testRemoveCommand_RemoveAll() { performCommand(mrSparkzz, "shop remove emerald"); assertEquals(String.format("%sYou have successfully removed %s%s%s from the store!", GREEN, GOLD, material, GREEN), mrSparkzz.nextMessage()); - assertNull(Store.getDefaultStore().getItems().get(material)); + assertNull(Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().get(material)); printSuccessMessage("remove command test - remove all of type from shop"); } diff --git a/src/test/java/net/sparkzz/command/sub/SellCommandTest.java b/src/test/java/net/sparkzz/command/sub/SellCommandTest.java index 61f5924..33b12c6 100644 --- a/src/test/java/net/sparkzz/command/sub/SellCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/SellCommandTest.java @@ -31,33 +31,34 @@ static void setUp() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); mrSparkzz = server.addPlayer("MrSparkzz"); player2 = server.addPlayer(); mrSparkzz.setOp(true); - Store.setDefaultStore((store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); + Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); } @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } @BeforeEach void setUpSellCommand() { - Store.getDefaultStore().addItem(emeralds.getType(), 0, -1, 2D, 1.5D); - Store.getDefaultStore().setBalance(100); + Store.getDefaultStore(mrSparkzz.getWorld()).get().addItem(emeralds.getType(), 0, -1, 2D, 1.5D); + Store.getDefaultStore(mrSparkzz.getWorld()).get().setBalance(100); mrSparkzz.getInventory().addItem(emeralds); // TODO: Shops.getEconomy().depositPlayer(mrSparkzz, 50); } @AfterEach void tearDownShop() { - Store.getDefaultStore().getItems().clear(); + Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().clear(); } @Test @@ -76,12 +77,12 @@ void testSellCommand_Permissions() { void testSellCommand() { Material material = emeralds.getType(); int quantity = 1; - double price = Store.getDefaultStore().getSellPrice(material); + double price = Store.getDefaultStore(mrSparkzz.getWorld()).get().getSellPrice(material); performCommand(mrSparkzz, "shop sell emerald " + quantity); assertEquals(String.format("%sSuccess! You have sold %s%s%s of %s%s%s for %s$%.2f%s.", GREEN, GOLD, quantity, GREEN, GOLD, material, GREEN, GOLD, price * quantity, GREEN), mrSparkzz.nextMessage()); - assertEquals(25, Store.getDefaultStore().getBalance()); + assertEquals(25, Store.getDefaultStore(mrSparkzz.getWorld()).get().getBalance()); assertEquals(150, Shops.getEconomy().getBalance(mrSparkzz)); printSuccessMessage("sell command test"); } diff --git a/src/test/java/net/sparkzz/command/sub/TransferCommandTest.java b/src/test/java/net/sparkzz/command/sub/TransferCommandTest.java index f0c3df7..2028cd2 100644 --- a/src/test/java/net/sparkzz/command/sub/TransferCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/TransferCommandTest.java @@ -36,6 +36,7 @@ static void setUpTransferCommand() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); Shops.setMockServer(server); mrSparkzz = server.addPlayer("MrSparkzz"); @@ -46,14 +47,14 @@ static void setUpTransferCommand() { @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); } @BeforeEach void setUpShop() { - Store.setDefaultStore((store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); + Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); } @AfterEach diff --git a/src/test/java/net/sparkzz/command/sub/UpdateCommandTest.java b/src/test/java/net/sparkzz/command/sub/UpdateCommandTest.java index a4b8ce7..3591096 100644 --- a/src/test/java/net/sparkzz/command/sub/UpdateCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/UpdateCommandTest.java @@ -7,6 +7,7 @@ import net.sparkzz.shops.Store; import net.sparkzz.shops.mocks.MockVault; import net.sparkzz.util.Cuboid; +import net.sparkzz.util.Notifier; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -16,7 +17,8 @@ import org.junit.jupiter.api.*; import static net.sparkzz.shops.TestHelper.*; -import static org.bukkit.ChatColor.*; +import static org.bukkit.ChatColor.GOLD; +import static org.bukkit.ChatColor.GREEN; import static org.junit.jupiter.api.Assertions.*; @SuppressWarnings("SpellCheckingInspection") @@ -36,6 +38,7 @@ static void setUp() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); mrSparkzz = server.addPlayer("MrSparkzz"); mrSparkzz.setOp(true); @@ -48,9 +51,9 @@ static void setUp() { @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); } @BeforeEach @@ -341,7 +344,7 @@ void tearDownPermissions() { void testUpdateCommand_Permissions() { cmdUse = false; performCommand(player, "shop update shop-name TestShop99"); - assertEquals(String.format("%sYou do not have permission to use this command!", RED), player.nextMessage()); + assertEquals(Notifier.compose(Notifier.CipherKey.NO_PERMS_CMD, null), player.nextMessage()); printSuccessMessage("update command permission check"); } diff --git a/src/test/java/net/sparkzz/command/sub/WithdrawCommandTest.java b/src/test/java/net/sparkzz/command/sub/WithdrawCommandTest.java index 491c34f..8f1c1c5 100644 --- a/src/test/java/net/sparkzz/command/sub/WithdrawCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/WithdrawCommandTest.java @@ -28,26 +28,27 @@ static void setUp() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); mrSparkzz = server.addPlayer("MrSparkzz"); player2 = server.addPlayer(); mrSparkzz.setOp(true); - Store.setDefaultStore((store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); + Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); } @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } @BeforeEach void setUpWithdrawCommand() { // TODO: Shops.getEconomy().depositPlayer(mrSparkzz, 50); - Store.getDefaultStore().setBalance(125); + Store.getDefaultStore(mrSparkzz.getWorld()).get().setBalance(125); } @AfterEach diff --git a/src/test/java/net/sparkzz/event/EntranceListenerTest.java b/src/test/java/net/sparkzz/event/EntranceListenerTest.java index 06e1881..173ede4 100644 --- a/src/test/java/net/sparkzz/event/EntranceListenerTest.java +++ b/src/test/java/net/sparkzz/event/EntranceListenerTest.java @@ -20,8 +20,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; -import static net.sparkzz.shops.TestHelper.printMessage; -import static net.sparkzz.shops.TestHelper.printSuccessMessage; +import static net.sparkzz.shops.TestHelper.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -40,6 +39,7 @@ static void setUp() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); World world = server.createWorld(WorldCreator.name("main-world")); otherWorld = server.createWorld(WorldCreator.name("other-world")); home = new Location(world, 0D, 0D, 0D); @@ -49,15 +49,15 @@ static void setUp() { mrSparkzz = server.addPlayer("MrSparkzz"); mrSparkzz.setLocation(new Location(world, 0D, 0D, 0D)); - Store.setDefaultStore(new Store("BetterBuy", mrSparkzz.getUniqueId(), new Cuboid(world, 10D, 10D, 10D, 20D, 20D, 20D))); - Store.setDefaultStore(new Store("WorstBuy", mrSparkzz.getUniqueId(), new Cuboid(null, 10D, 10D, 10D, 20D, 20D, 20D))); + Store.setDefaultStore(mrSparkzz.getWorld(), new Store("BetterBuy", mrSparkzz.getUniqueId(), new Cuboid(world, 10D, 10D, 10D, 20D, 20D, 20D))); + new Store("WorstBuy", mrSparkzz.getUniqueId(), new Cuboid(null, 10D, 10D, 10D, 20D, 20D, 20D)); } @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } diff --git a/src/test/java/net/sparkzz/shops/StoreTest.java b/src/test/java/net/sparkzz/shops/StoreTest.java index 3e78cb2..fb75b7f 100644 --- a/src/test/java/net/sparkzz/shops/StoreTest.java +++ b/src/test/java/net/sparkzz/shops/StoreTest.java @@ -18,8 +18,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; -import static net.sparkzz.shops.TestHelper.printMessage; -import static net.sparkzz.shops.TestHelper.printSuccessMessage; +import static net.sparkzz.shops.TestHelper.*; import static org.junit.jupiter.api.Assertions.assertEquals; @DisplayName("Entrance Listener") @@ -35,29 +34,30 @@ static void setUp() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); Shops.setMockServer(server); - Store.setDefaultStore(new Store("BetterBuy")); + Store.setDefaultStore(null, new Store("BetterBuy")); } @AfterAll static void tearDown() { - // Stop the mock server MockBukkit.unmock(); + unLoadConfig(); } @AfterEach void reset() { Store.STORES.clear(); - Store.setDefaultStore(new Store("BetterBuy")); + Store.setDefaultStore(null, new Store("BetterBuy")); } @Test @DisplayName("Test get buy price - material not in store") @Order(1) void testGetBuyPrice_MaterialNotInStore() { - assertEquals(-1D, Store.getDefaultStore().getBuyPrice(Material.BEEF)); + assertEquals(-1D, Store.getDefaultStore(null).get().getBuyPrice(Material.BEEF)); printSuccessMessage("get buy price test - material not in store"); } @@ -65,7 +65,7 @@ void testGetBuyPrice_MaterialNotInStore() { @DisplayName("Test get sell price - material not in shop") @Order(2) void testGetSellPrice_MaterialNotInStore() { - assertEquals(-1D, Store.getDefaultStore().getSellPrice(Material.BEEF)); + assertEquals(-1D, Store.getDefaultStore(null).get().getSellPrice(Material.BEEF)); printSuccessMessage("get sell price test - material not in store"); } @@ -73,8 +73,8 @@ void testGetSellPrice_MaterialNotInStore() { @DisplayName("Test removing funds - more than store balance") @Order(3) void testRemoveFunds_MoreThanStoreBalance() { - Store.getDefaultStore().removeFunds(10D); - assertEquals(0D, Store.getDefaultStore().getBalance()); + Store.getDefaultStore(null).get().removeFunds(10D); + assertEquals(0D, Store.getDefaultStore(null).get().getBalance()); printSuccessMessage("remove funds - more than stpre balance"); } @@ -82,9 +82,9 @@ void testRemoveFunds_MoreThanStoreBalance() { @DisplayName("Test removing funds") @Order(4) void testRemoveFunds() { - Store.getDefaultStore().setBalance(15.52D); - Store.getDefaultStore().removeFunds(10D); - assertEquals(5.52D, Store.getDefaultStore().getBalance()); + Store.getDefaultStore(null).get().setBalance(15.52D); + Store.getDefaultStore(null).get().removeFunds(10D); + assertEquals(5.52D, Store.getDefaultStore(null).get().getBalance()); printSuccessMessage("remove funds"); } @@ -92,9 +92,9 @@ void testRemoveFunds() { @DisplayName("Test removing item stack") @Order(5) void testRemoveItemStack() { - Store.getDefaultStore().addItem(new ItemStack(Material.SNOWBALL, 20)); - Store.getDefaultStore().removeItem(new ItemStack(Material.SNOWBALL, 15)); - assertEquals(5, Store.getDefaultStore().getAttributes(Material.SNOWBALL).get("quantity")); + Store.getDefaultStore(null).get().addItem(new ItemStack(Material.SNOWBALL, 20)); + Store.getDefaultStore(null).get().removeItem(new ItemStack(Material.SNOWBALL, 15)); + assertEquals(5, Store.getDefaultStore(null).get().getAttributes(Material.SNOWBALL).get("quantity")); printSuccessMessage("remove item stack"); } @@ -104,8 +104,8 @@ void testRemoveItemStack() { void testSetCuboidLocation() { World world = server.createWorld(WorldCreator.name("world")); Cuboid cuboid = new Cuboid(world, 1D, 1D, 1D, 2D, 2D, 2D); - Store.getDefaultStore().setCuboidLocation(cuboid); - assertEquals(cuboid, Store.getDefaultStore().getCuboidLocation()); + Store.getDefaultStore(null).get().setCuboidLocation(cuboid); + assertEquals(cuboid, Store.getDefaultStore(null).get().getCuboidLocation()); printSuccessMessage("set cuboid location"); } } diff --git a/src/test/java/net/sparkzz/util/CuboidTest.java b/src/test/java/net/sparkzz/util/CuboidTest.java index 96b0216..022bafc 100644 --- a/src/test/java/net/sparkzz/util/CuboidTest.java +++ b/src/test/java/net/sparkzz/util/CuboidTest.java @@ -44,7 +44,7 @@ void setUpCuboids() { @AfterAll static void tearDown() { MockBukkit.unmock(); - Store.setDefaultStore(null); + Store.DEFAULT_STORES.clear(); } @Test diff --git a/src/test/java/net/sparkzz/util/InventoryManagementSystemTest.java b/src/test/java/net/sparkzz/util/InventoryManagementSystemTest.java index 2c3841b..789b4bb 100644 --- a/src/test/java/net/sparkzz/util/InventoryManagementSystemTest.java +++ b/src/test/java/net/sparkzz/util/InventoryManagementSystemTest.java @@ -22,8 +22,7 @@ import java.util.List; -import static net.sparkzz.shops.TestHelper.printMessage; -import static net.sparkzz.shops.TestHelper.printSuccessMessage; +import static net.sparkzz.shops.TestHelper.*; import static org.junit.jupiter.api.Assertions.*; @SuppressWarnings("SpellCheckingInspection") @@ -44,24 +43,26 @@ static void setUp() { MockBukkit.loadWith(MockVault.class, new PluginDescriptionFile("Vault", "MOCK", "net.sparkzz.shops.mocks.MockVault")); MockBukkit.load(Shops.class); + loadConfig(); mrSparkzz = server.addPlayer("MrSparkzz"); mrSparkzz.setOp(true); - Store.setDefaultStore(store = new Store("BetterBuy", mrSparkzz.getUniqueId())); + Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); secondaryStore = new Store("SecondaryStore", mrSparkzz.getUniqueId(), new Cuboid(server.getWorld("world"), -20D, -20D, -20D, 20D, 20D, 20D)); } @AfterAll static void tearDown() { MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } @BeforeEach void setUpIMS() { - Store.setDefaultStore(store); + Store.setDefaultStore(null, store); store.addItem(emeralds.getType(), emeralds.getAmount(), 128, 1, 1); } @@ -249,7 +250,7 @@ void testGetAvailableSpace_Store_MaxQuantityNegative() { void testIdentifyStore_WithinSecondaryStore() { mrSparkzz.setLocation(new Location(server.getWorld("world"), 0D, 0D, 0D)); - assertEquals(secondaryStore, InventoryManagementSystem.locateCurrentStore(mrSparkzz)); + assertEquals(secondaryStore, InventoryManagementSystem.locateCurrentStore(mrSparkzz).orElse(null)); printSuccessMessage("IMS - identify store - within secondary store"); } @@ -259,7 +260,7 @@ void testIdentifyStore_WithinSecondaryStore() { void testIdentifyStore_NotWithinSecondaryStore() { mrSparkzz.setLocation(new Location(server.getWorld("world"), 21D, 0D, 0D)); - assertEquals(store, InventoryManagementSystem.locateCurrentStore(mrSparkzz)); + assertEquals(store, InventoryManagementSystem.locateCurrentStore(mrSparkzz).orElse(null)); printSuccessMessage("IMS - identify store - within default store"); } @@ -268,10 +269,10 @@ void testIdentifyStore_NotWithinSecondaryStore() { @Order(20) void testIdentifyStore_NotWithinAnyStore() { mrSparkzz.setLocation(new Location(server.getWorld("not-a-world"), 0D, 0D, 0D)); - Store.setDefaultStore(null); + Store.DEFAULT_STORES.clear(); System.out.println(mrSparkzz.getWorld()); - assertNull(InventoryManagementSystem.locateCurrentStore(mrSparkzz)); + assertNull(InventoryManagementSystem.locateCurrentStore(mrSparkzz).orElse(null)); printSuccessMessage("IMS - identify store - not within secondary store"); } } diff --git a/src/test/java/net/sparkzz/util/NotifierTest.java b/src/test/java/net/sparkzz/util/NotifierTest.java index cb19e40..b6ae487 100644 --- a/src/test/java/net/sparkzz/util/NotifierTest.java +++ b/src/test/java/net/sparkzz/util/NotifierTest.java @@ -46,7 +46,7 @@ static void setUp() { @AfterAll static void tearDown() { MockBukkit.unmock(); - Store.setDefaultStore(null); + Store.DEFAULT_STORES.clear(); unLoadConfig(); } diff --git a/src/test/java/net/sparkzz/util/TransactionTest.java b/src/test/java/net/sparkzz/util/TransactionTest.java index caee186..f7704e7 100644 --- a/src/test/java/net/sparkzz/util/TransactionTest.java +++ b/src/test/java/net/sparkzz/util/TransactionTest.java @@ -11,8 +11,7 @@ import org.bukkit.plugin.PluginDescriptionFile; import org.junit.jupiter.api.*; -import static net.sparkzz.shops.TestHelper.printMessage; -import static net.sparkzz.shops.TestHelper.printSuccessMessage; +import static net.sparkzz.shops.TestHelper.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -37,15 +36,17 @@ static void setUp() { mrSparkzz = server.addPlayer("MrSparkzz"); player = server.addPlayer(); + loadConfig(); mrSparkzz.setOp(true); - Store.setDefaultStore(store = new Store("BetterBuy", mrSparkzz.getUniqueId())); + Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); } @AfterAll static void tearDownAll() { MockBukkit.unmock(); - Store.setDefaultStore(null); + unLoadConfig(); + Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } diff --git a/src/test/resources/config.yml b/src/test/resources/config.yml index 8ee988f..8caa99d 100644 --- a/src/test/resources/config.yml +++ b/src/test/resources/config.yml @@ -1,4 +1,5 @@ store: + default: [] max-owned-stores: 2 min-dimensions: x: 3 From 9e16c0e45f8bc44612a5ba63ac53a9a593c0166a Mon Sep 17 00:00:00 2001 From: Brendon Butler Date: Wed, 23 Aug 2023 08:18:41 -0400 Subject: [PATCH 06/11] add additional tests to improve coverage update assertions in modified classes to utilize Notifier instead of raw text --- .../sparkzz/command/sub/WithdrawCommand.java | 2 +- .../sparkzz/command/sub/BuyCommandTest.java | 45 +++++++----- .../command/sub/DepositCommandTest.java | 34 +++++---- .../command/sub/RemoveCommandTest.java | 70 +++++++++++++++---- .../sparkzz/command/sub/SellCommandTest.java | 42 +++++++---- .../command/sub/WithdrawCommandTest.java | 33 ++++++--- 6 files changed, 155 insertions(+), 71 deletions(-) diff --git a/src/main/java/net/sparkzz/command/sub/WithdrawCommand.java b/src/main/java/net/sparkzz/command/sub/WithdrawCommand.java index c7f5ba1..689fecd 100644 --- a/src/main/java/net/sparkzz/command/sub/WithdrawCommand.java +++ b/src/main/java/net/sparkzz/command/sub/WithdrawCommand.java @@ -25,7 +25,7 @@ public boolean process(CommandSender sender, Command command, String label, Stri setArgsAsAttributes(args); Player player = (Player) setAttribute("sender", sender); Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player).orElse(null)); - double amount = (Double) setAttribute("amount", (args[1].equalsIgnoreCase("all")) ? store.getBalance() : Double.parseDouble(args[1])); + double amount = (Double) setAttribute("amount", (args[1].equalsIgnoreCase("all")) ? (store == null) ? 0 : store.getBalance() : Double.parseDouble(args[1])); if (store == null) { Notifier.process(player, NO_STORE_FOUND, getAttributes()); diff --git a/src/test/java/net/sparkzz/command/sub/BuyCommandTest.java b/src/test/java/net/sparkzz/command/sub/BuyCommandTest.java index fc1b01c..2eda09d 100644 --- a/src/test/java/net/sparkzz/command/sub/BuyCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/BuyCommandTest.java @@ -6,21 +6,17 @@ import net.sparkzz.shops.Shops; import net.sparkzz.shops.Store; import net.sparkzz.shops.mocks.MockVault; +import net.sparkzz.util.Notifier; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginDescriptionFile; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.*; + +import java.util.Collections; +import java.util.Map; import static net.sparkzz.shops.TestHelper.*; -import static org.bukkit.ChatColor.RED; +import static net.sparkzz.util.Notifier.CipherKey.*; import static org.junit.jupiter.api.Assertions.assertEquals; @SuppressWarnings("SpellCheckingInspection") @@ -63,12 +59,17 @@ void setUpBuyCommand() { // TODO: Shops.getEconomy().depositPlayer(mrSparkzz, 50); } + @AfterEach + void tearDownEach() { + mrSparkzz.getInventory().clear(); + } + @Test @DisplayName("Test Buy - permissions") @Order(1) void testBuyCommand_Permissions() { performCommand(player2, "shop buy emerald 1"); - assertEquals(String.format("%sYou do not have permission to use this command!", RED), player2.nextMessage()); + assertEquals(Notifier.compose(NO_PERMS_CMD, null), player2.nextMessage()); printSuccessMessage("buy command permission check"); } @@ -78,7 +79,7 @@ void testBuyCommand_Permissions() { @Order(2) void testBuyCommand() { performCommand(mrSparkzz, "shop buy emerald 12"); - assertEquals("§aSuccess! You have purchased §612§a of §6EMERALD§a for §624§a.", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(BUY_SUCCESS, Map.of("quantity", 12, "material", Material.EMERALD, "cost", 24)), mrSparkzz.nextMessage()); assertEquals(24, store.getBalance()); assertEquals(26, Shops.getEconomy().getBalance(mrSparkzz)); printSuccessMessage("buy command test"); @@ -89,7 +90,7 @@ void testBuyCommand() { @Order(3) void testBuyCommand_BelowMinimum() { performCommand(mrSparkzz, "shop buy emerald -1"); - assertEquals("§cInvalid quantity (-1)!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(INVALID_QUANTITY, Collections.singletonMap("quantity", -1)), mrSparkzz.nextMessage()); assertEquals(0, store.getBalance()); // TODO: assertEquals(50, Shops.getEconomy().getBalance(mrSparkzz)); printSuccessMessage("buy command test - below minimum amount"); @@ -100,7 +101,7 @@ void testBuyCommand_BelowMinimum() { @Order(4) void testBuyCommand_AboveMaximum() { performCommand(mrSparkzz, "shop buy emerald 2305"); - assertEquals("§cInvalid quantity (2305)!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(INVALID_QUANTITY, Collections.singletonMap("quantity", 2305)), mrSparkzz.nextMessage()); assertEquals(0, store.getBalance()); // TODO: assertEquals(50, Shops.getEconomy().getBalance(mrSparkzz)); printSuccessMessage("buy command test - above maximum amount"); @@ -111,7 +112,7 @@ void testBuyCommand_AboveMaximum() { @Order(4) void testBuyCommand_InvalidMaterial() { performCommand(mrSparkzz, "shop buy emeral 10"); - assertEquals("§cInvalid material (emeral)!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(INVALID_MATERIAL, Collections.singletonMap("material", "emeral")), mrSparkzz.nextMessage()); assertEquals("/shop [buy|sell|browse]", mrSparkzz.nextMessage()); assertEquals(0, store.getBalance()); // TODO: assertEquals(50, Shops.getEconomy().getBalance(mrSparkzz)); @@ -123,9 +124,21 @@ void testBuyCommand_InvalidMaterial() { @Order(5) void testBuyCommand_QueryPrice() { performCommand(mrSparkzz, "shop buy emerald"); - assertEquals("§9Price: §a2.0", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(PRICE, Collections.singletonMap("cost", 2D)), mrSparkzz.nextMessage()); assertEquals(0, store.getBalance()); // TODO: assertEquals(50, Shops.getEconomy().getBalance(mrSparkzz)); printSuccessMessage("buy command test - query price"); } + + @Test + @DisplayName("Test Buy - main functionality - no store") + @Order(6) + void testBuyCommand_NoStore() { + Store.DEFAULT_STORES.clear(); + performCommand(mrSparkzz, "shop buy emerald 2"); + assertEquals(Notifier.compose(Notifier.CipherKey.NO_STORE_FOUND, null), mrSparkzz.nextMessage()); + assertEquals(0, store.getBalance()); + // TODO: assertEquals(50, Shops.getEconomy().getBalance(mrSparkzz)); + printSuccessMessage("buy command test - no store"); + } } \ No newline at end of file diff --git a/src/test/java/net/sparkzz/command/sub/DepositCommandTest.java b/src/test/java/net/sparkzz/command/sub/DepositCommandTest.java index 315e823..e00053f 100644 --- a/src/test/java/net/sparkzz/command/sub/DepositCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/DepositCommandTest.java @@ -10,9 +10,10 @@ import org.bukkit.plugin.PluginDescriptionFile; import org.junit.jupiter.api.*; +import java.util.Collections; + import static net.sparkzz.shops.TestHelper.*; -import static org.bukkit.ChatColor.GOLD; -import static org.bukkit.ChatColor.GREEN; +import static net.sparkzz.util.Notifier.CipherKey.*; import static org.junit.jupiter.api.Assertions.assertEquals; @SuppressWarnings("SpellCheckingInspection") @@ -36,27 +37,26 @@ static void setUp() { player2 = server.addPlayer(); mrSparkzz.setOp(true); - Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); } @AfterAll static void tearDown() { MockBukkit.unmock(); unLoadConfig(); - Store.DEFAULT_STORES.clear(); - Store.STORES.clear(); } @BeforeEach void setUpDepositCommand() { + Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); // TODO: Shops.getEconomy().depositPlayer(mrSparkzz, 150); Store.getDefaultStore(mrSparkzz.getWorld()).get().setBalance(25); } @AfterEach void tearDownWithdrawCommand() { + Store.DEFAULT_STORES.clear(); + Store.STORES.clear(); player2.setOp(false); - store.setInfiniteFunds(false); } @Test @@ -73,10 +73,8 @@ void testWithdrawCommand_Permissions() { @DisplayName("Test Deposit - main functionality - deposit 100") @Order(2) void testDepositCommand() { - double amount = 100; - - performCommand(mrSparkzz, "shop deposit " + amount); - assertEquals(String.format("%sYou have successfully deposited %s%s%s to the shop!", GREEN, GOLD, amount, GREEN), mrSparkzz.nextMessage()); + performCommand(mrSparkzz, "shop deposit 100"); + assertEquals(Notifier.compose(DEPOSIT_SUCCESS, Collections.singletonMap("amount", 100D)), mrSparkzz.nextMessage()); assertEquals(125, Store.getDefaultStore(mrSparkzz.getWorld()).get().getBalance()); assertEquals(50, Shops.getEconomy().getBalance(mrSparkzz)); printSuccessMessage("deposit command test"); @@ -100,7 +98,7 @@ void testDepositCommand_InvalidAmount() { void testDepositCommand_NotOwner() { player2.setOp(true); performCommand(player2, "shop deposit 100"); - assertEquals("§cYou are not the owner of this store, you cannot perform this command!", player2.nextMessage()); + assertEquals(Notifier.compose(NOT_OWNER, null), player2.nextMessage()); // TODO: assertEquals(150, Shops.getEconomy().getBalance(mrSparkzz)); assertEquals(25, store.getBalance()); printSuccessMessage("deposit command test - not the owner"); @@ -112,7 +110,7 @@ void testDepositCommand_NotOwner() { @Order(5) void testDepositCommand_InsufficientFunds() { performCommand(mrSparkzz, "shop deposit 200"); - assertEquals("§cYou have insufficient funds!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(INSUFFICIENT_FUNDS_PLAYER, null), mrSparkzz.nextMessage()); assertEquals(125, Shops.getEconomy().getBalance(mrSparkzz)); assertEquals(25, store.getBalance()); printSuccessMessage("deposit command test - insufficient funds"); @@ -124,9 +122,19 @@ void testDepositCommand_InsufficientFunds() { void testDepositCommand_InfiniteFunds() { store.setInfiniteFunds(true); performCommand(mrSparkzz, "shop deposit 15"); - assertEquals("§aThis store has infinite funds, depositing funds isn't necessary!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(DEPOSIT_INF_FUNDS, null), mrSparkzz.nextMessage()); // TODO: assertEquals(125, Shops.getEconomy().getBalance(mrSparkzz)); assertEquals(25, store.getBalance()); printSuccessMessage("deposit command test - shop has infinite funds"); } + + @Test + @DisplayName("Test Deposit - main functionality - no store") + @Order(7) + void testDepositCommand_NoStore() { + Store.DEFAULT_STORES.clear(); + performCommand(mrSparkzz, "shop deposit 100"); + assertEquals(Notifier.compose(Notifier.CipherKey.NO_STORE_FOUND, null), mrSparkzz.nextMessage()); + printSuccessMessage("deposit command test - no store"); + } } diff --git a/src/test/java/net/sparkzz/command/sub/RemoveCommandTest.java b/src/test/java/net/sparkzz/command/sub/RemoveCommandTest.java index a76a81f..a37a136 100644 --- a/src/test/java/net/sparkzz/command/sub/RemoveCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/RemoveCommandTest.java @@ -6,22 +6,26 @@ import net.sparkzz.shops.Shops; import net.sparkzz.shops.Store; import net.sparkzz.shops.mocks.MockVault; +import net.sparkzz.util.Notifier; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginDescriptionFile; import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import java.util.Collections; +import java.util.Map; import java.util.Objects; import static net.sparkzz.shops.TestHelper.*; -import static org.bukkit.ChatColor.*; +import static net.sparkzz.util.Notifier.CipherKey.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -47,15 +51,23 @@ static void setUpRemoveCommand() { player2 = server.addPlayer(); mrSparkzz.setOp(true); - Store.setDefaultStore(mrSparkzz.getWorld(), new Store("BetterBuy", mrSparkzz.getUniqueId())); - Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().clear(); - Store.getDefaultStore(mrSparkzz.getWorld()).get().addItem(emeralds.getType(), 0, -1, 2D, 1.5D); } @AfterAll static void tearDown() { MockBukkit.unmock(); unLoadConfig(); + } + + @BeforeEach + void setUp() { + Store.setDefaultStore(mrSparkzz.getWorld(), new Store("BetterBuy", mrSparkzz.getUniqueId())); + Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().clear(); + Store.getDefaultStore(mrSparkzz.getWorld()).get().addItem(emeralds.getType(), emeralds.getAmount(), -1, 2D, 1.5D); + } + + @AfterEach + void tearDownEach() { Store.DEFAULT_STORES.clear(); Store.STORES.clear(); } @@ -65,21 +77,20 @@ static void tearDown() { @Order(1) void testRemoveCommand_Permissions() { performCommand(player2, "shop remove acacia_log 1"); - assertEquals(String.format("%sYou do not have permission to use this command!", RED), player2.nextMessage()); + assertEquals(Notifier.compose(NO_PERMS_CMD, null), player2.nextMessage()); printSuccessMessage("remove command permission check"); } @Test - @Disabled("Disabled until MockBukkit is updated to load plugins properly (or I find a new solution)") @DisplayName("Test Remove - main functionality - remove 1") @Order(2) void testRemoveCommand_RemoveOne() { Material material = emeralds.getType(); performCommand(mrSparkzz, "shop remove emerald 1"); - assertEquals(String.format("%sYou have successfully removed %s%s%s from the shop!", GREEN, GOLD, material, GREEN), mrSparkzz.nextMessage()); - assertEquals(63, Objects.requireNonNull(mrSparkzz.getInventory().getItem(0)).getAmount()); - assertEquals(11, Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().get(material).get("quantity").intValue()); + assertEquals(Notifier.compose(REMOVE_SUCCESS_QUANTITY, Map.of("material", Material.EMERALD, "quantity", 1)), mrSparkzz.nextMessage()); + assertEquals(1, Objects.requireNonNull(mrSparkzz.getInventory().getItem(0)).getAmount()); + assertEquals(63, Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().get(material).get("quantity").intValue()); printSuccessMessage("remove command test - remove 1 of type from shop"); } @@ -90,18 +101,17 @@ void testRemoveCommand_RemoveAll() { Material material = emeralds.getType(); performCommand(mrSparkzz, "shop remove emerald"); - assertEquals(String.format("%sYou have successfully removed %s%s%s from the store!", GREEN, GOLD, material, GREEN), mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(REMOVE_SUCCESS, Collections.singletonMap("material", Material.EMERALD)), mrSparkzz.nextMessage()); assertNull(Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().get(material)); printSuccessMessage("remove command test - remove all of type from shop"); } @Test - @Disabled("Disabled until MockBukkit is updated to load plugins properly (or I find a new solution)") @DisplayName("Test Remove - material not found in shop") @Order(4) void testRemoveCommand_NoMaterial() { - performCommand(mrSparkzz, "shop remove emerald 1"); - assertEquals(String.format("%sThis material doesn't currently exist in the shop, use `/shop add %s` to add this item", RED, Material.EMERALD), mrSparkzz.nextMessage()); + performCommand(mrSparkzz, "shop remove stick 1"); + assertEquals(Notifier.compose(MATERIAL_MISSING_STORE, Collections.singletonMap("material", Material.STICK)), mrSparkzz.nextMessage()); printSuccessMessage("remove command test - material doesn't exist"); } @@ -110,7 +120,37 @@ void testRemoveCommand_NoMaterial() { @Order(5) void testRemoveCommand_InvalidMaterial() { performCommand(mrSparkzz, "shop remove emeral 1"); - assertEquals("§cInvalid material (emeral)!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(INVALID_MATERIAL, Collections.singletonMap("material", "emeral")), mrSparkzz.nextMessage()); + assertEquals("/shop [buy|sell|browse]", mrSparkzz.nextMessage()); printSuccessMessage("remove command test - invalid material"); } + + @Test + @DisplayName("Test Remove - main functionality - no store") + @Order(6) + void testRemoveCommand_NoStore() { + Store.DEFAULT_STORES.clear(); + performCommand(mrSparkzz, "shop remove emerald 1"); + assertEquals(Notifier.compose(Notifier.CipherKey.NO_STORE_FOUND, null), mrSparkzz.nextMessage()); + printSuccessMessage("remove command test - no store"); + } + + @Test + @DisplayName("Test Remove - main functionality - insufficient inventory store") + @Order(7) + void testRemoveCommand_InsufficientInventoryStore() { + performCommand(mrSparkzz, "shop remove emerald 1000"); + assertEquals(Notifier.compose(INSUFFICIENT_INV_STORE, Collections.singletonMap("material", Material.EMERALD)), mrSparkzz.nextMessage()); + printSuccessMessage("remove command test - insufficient inventory store"); + } + + @Test + @DisplayName("Test Remove - main functionality - insufficient inventory player") + @Order(8) + void testRemoveCommand_InsufficientInventoryPlayer() { + mrSparkzz.getInventory().addItem(new ItemStack(Material.MILK_BUCKET, 2304)); + performCommand(mrSparkzz, "shop remove emerald 64"); + assertEquals(Notifier.compose(REMOVE_INSUFFICIENT_INV_PLAYER, Collections.singletonMap("material", Material.EMERALD)), mrSparkzz.nextMessage()); + printSuccessMessage("remove command test - insufficient inventory player"); + } } diff --git a/src/test/java/net/sparkzz/command/sub/SellCommandTest.java b/src/test/java/net/sparkzz/command/sub/SellCommandTest.java index 33b12c6..43722f0 100644 --- a/src/test/java/net/sparkzz/command/sub/SellCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/SellCommandTest.java @@ -6,13 +6,17 @@ import net.sparkzz.shops.Shops; import net.sparkzz.shops.Store; import net.sparkzz.shops.mocks.MockVault; +import net.sparkzz.util.Notifier; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginDescriptionFile; import org.junit.jupiter.api.*; +import java.util.Collections; +import java.util.Map; + import static net.sparkzz.shops.TestHelper.*; -import static org.bukkit.ChatColor.*; +import static net.sparkzz.util.Notifier.CipherKey.*; import static org.junit.jupiter.api.Assertions.assertEquals; @SuppressWarnings("SpellCheckingInspection") @@ -50,6 +54,7 @@ static void tearDown() { @BeforeEach void setUpSellCommand() { + Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().clear(); Store.getDefaultStore(mrSparkzz.getWorld()).get().addItem(emeralds.getType(), 0, -1, 2D, 1.5D); Store.getDefaultStore(mrSparkzz.getWorld()).get().setBalance(100); mrSparkzz.getInventory().addItem(emeralds); @@ -57,8 +62,8 @@ void setUpSellCommand() { } @AfterEach - void tearDownShop() { - Store.getDefaultStore(mrSparkzz.getWorld()).get().getItems().clear(); + void tearDownEach() { + mrSparkzz.getInventory().clear(); } @Test @@ -66,7 +71,7 @@ void tearDownShop() { @Order(1) void testSellCommand_Permissions() { performCommand(player2, "shop sell emerald 1"); - assertEquals(String.format("%sYou do not have permission to use this command!", RED), player2.nextMessage()); + assertEquals(Notifier.compose(NO_PERMS_CMD, null), player2.nextMessage()); printSuccessMessage("sell command permission check"); } @@ -75,13 +80,8 @@ void testSellCommand_Permissions() { @DisplayName("Test Sell - main functionality - sell 1") @Order(2) void testSellCommand() { - Material material = emeralds.getType(); - int quantity = 1; - double price = Store.getDefaultStore(mrSparkzz.getWorld()).get().getSellPrice(material); - - performCommand(mrSparkzz, "shop sell emerald " + quantity); - assertEquals(String.format("%sSuccess! You have sold %s%s%s of %s%s%s for %s$%.2f%s.", - GREEN, GOLD, quantity, GREEN, GOLD, material, GREEN, GOLD, price * quantity, GREEN), mrSparkzz.nextMessage()); + performCommand(mrSparkzz, "shop sell emerald 1"); + assertEquals(Notifier.compose(SELL_SUCCESS, Map.of("quantity", 1, "material", Material.EMERALD, "cost", 1.5D)), mrSparkzz.nextMessage()); assertEquals(25, Store.getDefaultStore(mrSparkzz.getWorld()).get().getBalance()); assertEquals(150, Shops.getEconomy().getBalance(mrSparkzz)); printSuccessMessage("sell command test"); @@ -92,7 +92,7 @@ void testSellCommand() { @Order(3) void testSellCommand_BelowMinimum() { performCommand(mrSparkzz, "shop sell emerald -1"); - assertEquals("§cInvalid quantity (-1)!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(INVALID_QUANTITY, Collections.singletonMap("quantity", -1)), mrSparkzz.nextMessage()); assertEquals(100, store.getBalance()); // TODO: assertEquals(0, Shops.getEconomy().getBalance(mrSparkzz)); printSuccessMessage("sell command test - below minimum amount"); @@ -103,7 +103,7 @@ void testSellCommand_BelowMinimum() { @Order(4) void testSellCommand_AboveMaximum() { performCommand(mrSparkzz, "shop sell emerald 2305"); - assertEquals("§cInvalid quantity (2305)!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(INVALID_QUANTITY, Collections.singletonMap("quantity", 2305)), mrSparkzz.nextMessage()); assertEquals(100, store.getBalance()); // TODO: assertEquals(0, Shops.getEconomy().getBalance(mrSparkzz)); printSuccessMessage("sell command test - above maximum amount"); @@ -114,7 +114,7 @@ void testSellCommand_AboveMaximum() { @Order(5) void testSellCommand_InvalidMaterial() { performCommand(mrSparkzz, "shop sell emeral 1"); - assertEquals("§cInvalid material (emeral)!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(INVALID_MATERIAL, Collections.singletonMap("material", "emeral")), mrSparkzz.nextMessage()); assertEquals("/shop [buy|sell|browse]", mrSparkzz.nextMessage()); assertEquals(100, store.getBalance()); // TODO: assertEquals(0, Shops.getEconomy().getBalance(mrSparkzz)); @@ -126,9 +126,21 @@ void testSellCommand_InvalidMaterial() { @Order(6) void testSellCommand_QueryPrice() { performCommand(mrSparkzz, "shop sell emerald"); - assertEquals("§9Price: §a1.5", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(PRICE, Collections.singletonMap("cost", 1.5D)), mrSparkzz.nextMessage()); assertEquals(100, store.getBalance()); // TODO: assertEquals(0, Shops.getEconomy().getBalance(mrSparkzz)); printSuccessMessage("sell command test - query price"); } + + @Test + @DisplayName("Test Sell - main functionality - no store") + @Order(7) + void testSellCommand_NoStore() { + Store.DEFAULT_STORES.clear(); + performCommand(mrSparkzz, "shop sell emerald 2"); + assertEquals(Notifier.compose(Notifier.CipherKey.NO_STORE_FOUND, null), mrSparkzz.nextMessage()); + assertEquals(100, store.getBalance()); + // TODO: assertEquals(0, Shops.getEconomy().getBalance(mrSparkzz)); + printSuccessMessage("sell command test - no store"); + } } diff --git a/src/test/java/net/sparkzz/command/sub/WithdrawCommandTest.java b/src/test/java/net/sparkzz/command/sub/WithdrawCommandTest.java index 8f1c1c5..0879248 100644 --- a/src/test/java/net/sparkzz/command/sub/WithdrawCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/WithdrawCommandTest.java @@ -6,11 +6,14 @@ import net.sparkzz.shops.Shops; import net.sparkzz.shops.Store; import net.sparkzz.shops.mocks.MockVault; +import net.sparkzz.util.Notifier; import org.bukkit.plugin.PluginDescriptionFile; import org.junit.jupiter.api.*; +import java.util.Collections; + import static net.sparkzz.shops.TestHelper.*; -import static org.bukkit.ChatColor.*; +import static net.sparkzz.util.Notifier.CipherKey.*; import static org.junit.jupiter.api.Assertions.assertEquals; @SuppressWarnings("SpellCheckingInspection") @@ -34,25 +37,25 @@ static void setUp() { player2 = server.addPlayer(); mrSparkzz.setOp(true); - Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); } @AfterAll static void tearDown() { MockBukkit.unmock(); unLoadConfig(); - Store.DEFAULT_STORES.clear(); - Store.STORES.clear(); } @BeforeEach void setUpWithdrawCommand() { + Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); // TODO: Shops.getEconomy().depositPlayer(mrSparkzz, 50); Store.getDefaultStore(mrSparkzz.getWorld()).get().setBalance(125); } @AfterEach void tearDownWithdrawCommand() { + Store.DEFAULT_STORES.clear(); + Store.STORES.clear(); player2.setOp(false); } @@ -61,7 +64,7 @@ void tearDownWithdrawCommand() { @Order(1) void testWithdrawCommand_Permissions() { performCommand(player2, "shop withdraw 100"); - assertEquals(String.format("%sYou do not have permission to use this command!", RED), player2.nextMessage()); + assertEquals(Notifier.compose(NO_PERMS_CMD, null), player2.nextMessage()); printSuccessMessage("withdraw command permission check"); } @@ -70,10 +73,8 @@ void testWithdrawCommand_Permissions() { @DisplayName("Test Withdraw - main functionality - withdraw 100") @Order(2) void testWithdrawCommand() { - double amount = 100; - - performCommand(mrSparkzz, "shop withdraw " + amount); - assertEquals(String.format("%sYou have successfully withdrawn %s%s%s from the shop!", GREEN, GOLD, amount, GREEN), mrSparkzz.nextMessage()); + performCommand(mrSparkzz, "shop withdraw 100"); + assertEquals(Notifier.compose(WITHDRAW_SUCCESS, Collections.singletonMap("amount", 100D)), mrSparkzz.nextMessage()); assertEquals(25, store.getBalance()); assertEquals(150, Shops.getEconomy().getBalance(mrSparkzz)); printSuccessMessage("withdraw command test"); @@ -96,7 +97,7 @@ void testWithdrawCommand_InvalidAmount() { void testWithdrawCommand_NotOwner() { player2.setOp(true); performCommand(player2, "shop withdraw 100"); - assertEquals("§cYou are not the owner of this store, you cannot perform this command!", player2.nextMessage()); + assertEquals(Notifier.compose(NOT_OWNER, null), player2.nextMessage()); assertEquals(125, store.getBalance()); printSuccessMessage("withdraw command test - not the owner"); } @@ -106,8 +107,18 @@ void testWithdrawCommand_NotOwner() { @Order(5) void testWithdrawCommand_InsufficientFunds() { performCommand(mrSparkzz, "shop withdraw 200"); - assertEquals("§cThe store has insufficient funds!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(INSUFFICIENT_FUNDS_STORE, null), mrSparkzz.nextMessage()); assertEquals(125, store.getBalance()); printSuccessMessage("withdraw command test - insufficient funds"); } + + @Test + @DisplayName("Test Withdraw - main functionality - no store") + @Order(6) + void testWithdrawCommand_NoStore() { + Store.DEFAULT_STORES.clear(); + performCommand(mrSparkzz, "shop withdraw all"); + assertEquals(Notifier.compose(Notifier.CipherKey.NO_STORE_FOUND, null), mrSparkzz.nextMessage()); + printSuccessMessage("withdraw command test - no store"); + } } From 2967812255548e97ebce671189c6e33e6cbb67fd Mon Sep 17 00:00:00 2001 From: Brendon Butler Date: Wed, 23 Aug 2023 21:03:48 -0400 Subject: [PATCH 07/11] add additional tests to improve coverage update assertions in modified classes to utilize Notifier instead of raw text --- src/main/java/net/sparkzz/util/Config.java | 23 +- .../sparkzz/command/sub/AddCommandTest.java | 24 +- .../command/sub/CreateCommandTest.java | 211 +++++++++++++++++- .../command/sub/RemoveCommandTest.java | 2 +- .../java/net/sparkzz/shops/StoreTest.java | 2 +- .../java/net/sparkzz/util/ConfigTest.java | 41 +++- src/test/resources/config.yml | 1 - 7 files changed, 279 insertions(+), 25 deletions(-) diff --git a/src/main/java/net/sparkzz/util/Config.java b/src/main/java/net/sparkzz/util/Config.java index 7b47f37..76e7a26 100644 --- a/src/main/java/net/sparkzz/util/Config.java +++ b/src/main/java/net/sparkzz/util/Config.java @@ -163,15 +163,21 @@ public static List getOffLimitsCuboids() { * @return the default Store for the input world */ public static Optional getDefaultStore(@Nullable World world) { + if (!rootNode.node("store").hasChild("default")) + return Optional.empty(); + CommentedConfigurationNode defaults = rootNode.node("store").node("default"); - if (defaults.hasChild("null")) - return Store.identifyStore(defaults.node("null").getString()); + if (defaults.hasChild("'null'")) + return Store.identifyStore(defaults.node("'null'").getString()); + + String name = (world == null) ? "'null'" : world.getName(); + String uuid = (world == null) ? "'null'" : world.getUID().toString(); - if (defaults.hasChild(world.getName())) { - return Store.identifyStore(defaults.node(world.getName()).getString()); - } else if (defaults.hasChild(world.getUID())) { - return Store.identifyStore(defaults.node(world.getUID()).getString()); + if (defaults.hasChild(uuid)) { + return Store.identifyStore(defaults.node(uuid).getString()); + } else if (defaults.hasChild(name)) { + return Store.identifyStore(defaults.node(name).getString()); } return Optional.empty(); @@ -196,6 +202,7 @@ public static void addOffLimitsArea(Cuboid cuboid) { try { CommentedConfigurationNode offLimitsNode = rootNode.node("store", "off-limits"); List offLimitsAreas = offLimitsNode.getList(String.class); + if (offLimitsAreas == null) offLimitsAreas = new ArrayList<>(); @@ -223,8 +230,8 @@ public static void setDefaultStore(@Nullable World world, @Nullable Store store) return; } - if (world == null) { - defaults.node("'null'", store.getUUID()); + if (world == null || world.getName().equalsIgnoreCase("null")) { + defaults.node("'null'").set(store.getUUID().toString()); return; } diff --git a/src/test/java/net/sparkzz/command/sub/AddCommandTest.java b/src/test/java/net/sparkzz/command/sub/AddCommandTest.java index 0f705b4..747a44e 100644 --- a/src/test/java/net/sparkzz/command/sub/AddCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/AddCommandTest.java @@ -6,14 +6,18 @@ import net.sparkzz.shops.Shops; import net.sparkzz.shops.Store; import net.sparkzz.shops.mocks.MockVault; +import net.sparkzz.util.Notifier; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginDescriptionFile; import org.junit.jupiter.api.*; +import java.util.Collections; import java.util.Objects; import static net.sparkzz.shops.TestHelper.*; +import static net.sparkzz.util.Notifier.CipherKey.INVALID_MATERIAL; +import static net.sparkzz.util.Notifier.CipherKey.MATERIAL_MISSING_STORE; import static org.bukkit.ChatColor.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -103,13 +107,12 @@ void testAddCommand_AddAll() { } @Test - @Disabled("Disabled until MockBukkit is updated to load plugins properly (or I find a new solution)") @DisplayName("Test Add - material not found in shop") @Order(4) void testAddCommand_NoMaterial() { - mrSparkzz.getInventory().addItem(new ItemStack(Material.EMERALD, 64)); - performCommand(mrSparkzz, "shop add emerald 1"); - assertEquals("§cThis material doesn't currently exist in the shop, use `/shop add emerald` to add this item", mrSparkzz.nextMessage()); + mrSparkzz.getInventory().addItem(new ItemStack(Material.STICK, 64)); + performCommand(mrSparkzz, "shop add stick 1"); + assertEquals(Notifier.compose(MATERIAL_MISSING_STORE, Collections.singletonMap("material", Material.STICK)), mrSparkzz.nextMessage()); printSuccessMessage("add command - material doesn't exist"); } @@ -118,7 +121,18 @@ void testAddCommand_NoMaterial() { @Order(5) void testRemoveCommand_InvalidMaterial() { performCommand(mrSparkzz, "shop add emeral 1"); - assertEquals("§cInvalid material (emeral)!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(INVALID_MATERIAL, Collections.singletonMap("material", "emeral")), mrSparkzz.nextMessage()); + assertEquals("/shop [buy|sell|browse]", mrSparkzz.nextMessage()); printSuccessMessage("remove command test - invalid material"); } + + @Test + @DisplayName("Test Add - main functionality - no store") + @Order(6) + void testDepositCommand_NoStore() { + Store.DEFAULT_STORES.clear(); + performCommand(mrSparkzz, "shop add emerald 1"); + assertEquals(Notifier.compose(Notifier.CipherKey.NO_STORE_FOUND, null), mrSparkzz.nextMessage()); + printSuccessMessage("add command test - no store"); + } } diff --git a/src/test/java/net/sparkzz/command/sub/CreateCommandTest.java b/src/test/java/net/sparkzz/command/sub/CreateCommandTest.java index 48bd3cb..1cab33f 100644 --- a/src/test/java/net/sparkzz/command/sub/CreateCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/CreateCommandTest.java @@ -6,7 +6,10 @@ import net.sparkzz.shops.Shops; import net.sparkzz.shops.Store; import net.sparkzz.shops.mocks.MockVault; +import net.sparkzz.util.Config; import net.sparkzz.util.Cuboid; +import net.sparkzz.util.Notifier; +import org.bukkit.Location; import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.plugin.PluginDescriptionFile; @@ -20,8 +23,11 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import java.util.Collections; +import java.util.Map; + import static net.sparkzz.shops.TestHelper.*; -import static org.bukkit.ChatColor.*; +import static net.sparkzz.util.Notifier.CipherKey.*; import static org.junit.jupiter.api.Assertions.assertEquals; @SuppressWarnings("SpellCheckingInspection") @@ -29,6 +35,8 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class CreateCommandTest { + private static double previousMaxVolume, previousMinVolume; + private static double[] previousMaxDimensions; private static PlayerMock mrSparkzz, player2; private static World world; @@ -47,6 +55,10 @@ static void setUp() { player2 = server.addPlayer(); mrSparkzz.setOp(true); + mrSparkzz.setLocation(new Location(world, 0D, 0D, 0D)); + previousMaxDimensions = Config.getMaxDimensions(); + previousMinVolume = Config.getMinVolume(); + previousMaxVolume = Config.getMaxVolume(); } @AfterAll @@ -59,6 +71,9 @@ static void tearDown() { @AfterEach void tearDownStore() { Store.STORES.clear(); + Config.setMaxDimensions(previousMaxDimensions[0], previousMaxDimensions[1], previousMaxDimensions[2]); + Config.setMinVolume(previousMinVolume); + Config.setMaxVolume(previousMaxVolume); } @BeforeEach @@ -71,7 +86,7 @@ void setUpStore() { @Order(1) void testCreateShop_Permissions() { performCommand(player2, "shop create TestShop"); - assertEquals(String.format("%sYou do not have permission to use this command!", RED), player2.nextMessage()); + assertEquals(Notifier.compose(NO_PERMS_CMD, null), player2.nextMessage()); printSuccessMessage("create command permission check"); } @@ -80,7 +95,7 @@ void testCreateShop_Permissions() { @Order(2) void testCreateShop() { performCommand(mrSparkzz, "shop create TestShop"); - assertEquals(String.format("%sYou have successfully created %s%s%s!", GREEN, GOLD, "TestShop", GREEN), mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(STORE_CREATE_SUCCESS, Collections.singletonMap("store", "TestShop")), mrSparkzz.nextMessage()); printSuccessMessage("create command test - creation of TestShop"); } @@ -89,7 +104,7 @@ void testCreateShop() { @Order(3) void testCreateShop_ForAnotherPlayer() { performCommand(mrSparkzz, String.format("shop create TestShop %s", player2.getName())); - assertEquals(String.format("§aYou have successfully created §6TestShop§a for §6%s§a!", player2.getName()), mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(STORE_CREATE_SUCCESS_OTHER_PLAYER, Map.of("store", "TestShop", "target", player2.getName())), mrSparkzz.nextMessage()); printSuccessMessage("create command test - creation of TestShop for Player0"); } @@ -99,7 +114,7 @@ void testCreateShop_ForAnotherPlayer() { void testCreateShop_ForAnotherPlayerByUUID() { // TODO: create MockPermissions to add specific permissions to a player mock performCommand(mrSparkzz, String.format("shop create TestShop %s", player2.getUniqueId())); - assertEquals(String.format("§aYou have successfully created §6TestShop§a for §6%s§a!", player2.getUniqueId()), mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(STORE_CREATE_SUCCESS_OTHER_PLAYER, Map.of("store", "TestShop", "target", player2.getUniqueId())), mrSparkzz.nextMessage()); printSuccessMessage("create command test - creation of TestShop for Player0 by UUID"); } @@ -108,7 +123,7 @@ void testCreateShop_ForAnotherPlayerByUUID() { @Order(5) void testCreateCommand_NoTargetPlayer() { performCommand(mrSparkzz, "shop create BetterBuy Player99"); - assertEquals("§cPlayer (Player99) not found!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(PLAYER_NOT_FOUND, Collections.singletonMap("target", "Player99")), mrSparkzz.nextMessage()); printSuccessMessage("create command test - target player not found"); } @@ -117,7 +132,7 @@ void testCreateCommand_NoTargetPlayer() { @Order(6) void testCreateCommand_CuboidShop() { performCommand(mrSparkzz, "shop create BetterBuy 10.5 8 -23 15 0 -37"); - assertEquals("§aYou have successfully created §6BetterBuy§a!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(STORE_CREATE_SUCCESS, Collections.singletonMap("store", "BetterBuy")), mrSparkzz.nextMessage()); printSuccessMessage("create command test - cuboid shop"); } @@ -126,7 +141,187 @@ void testCreateCommand_CuboidShop() { @Order(7) void testCreateCommand_CuboidShop_OtherPlayer() { performCommand(mrSparkzz, String.format("shop create TestShop %s 10.5 8 -23 15 0 -37", player2.getUniqueId())); - assertEquals(String.format("§aYou have successfully created §6TestShop§a for §6%s§a!", player2.getUniqueId()), mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(STORE_CREATE_SUCCESS_OTHER_PLAYER, Map.of("store", "TestShop", "target", player2.getUniqueId())), mrSparkzz.nextMessage()); printSuccessMessage("create command test - cuboid shop for other player"); } + + @Test + @DisplayName("Test Create - main functionality - max stores") + @Order(8) + void testCreateCommand_MaxStores() { + new Store("store2", mrSparkzz.getUniqueId()); + new Store("store3", mrSparkzz.getUniqueId()); + new Store("store4", mrSparkzz.getUniqueId()); + new Store("store5", mrSparkzz.getUniqueId()); + performCommand(mrSparkzz, "shop create TestShop"); + assertEquals(Notifier.compose(STORE_CREATE_FAIL_MAX_STORES, Collections.singletonMap("max-stores", Config.getMaxOwnedStores())), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - max stores"); + } + + @Test + @DisplayName("Test Create - main functionality - off-limits area") + @Order(9) + void testCreateCommand_CuboidShop_OffLimitsArea() { + performCommand(mrSparkzz, "shop create TestShop 4 0 4 16 5 16"); + assertEquals(Notifier.compose(STORE_CREATE_FAIL_OFFLIMITS, null), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - off-limits area"); + } + + @Test + @DisplayName("Test Create - main functionality - overlaps other store") + @Order(10) + void testCreateCommand_CuboidShop_OverlapsExisting() { + new Store("GuardShop", player2.getUniqueId(), new Cuboid(world, 200, 200, 200, 220, 220, 220)); + performCommand(mrSparkzz, "shop create TestShop 205 205 205 208 208 208"); + assertEquals(Notifier.compose(STORE_CREATE_FAIL_OVERLAPS, null), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - off-limits area"); + } + + @Test + @DisplayName("Test Create - limits - under minimum X") + @Order(20) + void testCreateCommand_Limits_UnderMinimumX() { + performCommand(mrSparkzz, "shop create TestShop 10 12 16 11 20 40"); + double[] minimum = Config.getMinDimensions(); + assertEquals(Notifier.compose(STORE_CREATE_FAIL_MIN_DIMS, Map.of( + "limit-min-x", minimum[0], + "limit-min-y", minimum[1], + "limit-min-z", minimum[2] + )), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - limits - under minimum x"); + } + + @Test + @DisplayName("Test Create - limits - under minimum Y") + @Order(21) + void testCreateCommand_Limits_UnderMinimumY() { + performCommand(mrSparkzz, "shop create TestShop 10 12 16 20 13 40"); + double[] minimum = Config.getMinDimensions(); + assertEquals(Notifier.compose(STORE_CREATE_FAIL_MIN_DIMS, Map.of( + "limit-min-x", minimum[0], + "limit-min-y", minimum[1], + "limit-min-z", minimum[2] + )), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - limits - under minimum y"); + } + + @Test + @DisplayName("Test Create - limits - under minimum Z") + @Order(22) + void testCreateCommand_Limits_UnderMinimumZ() { + performCommand(mrSparkzz, "shop create TestShop 10 12 16 20 20 17"); + double[] minimum = Config.getMinDimensions(); + assertEquals(Notifier.compose(STORE_CREATE_FAIL_MIN_DIMS, Map.of( + "limit-min-x", minimum[0], + "limit-min-y", minimum[1], + "limit-min-z", minimum[2] + )), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - limits - under minimum z"); + } + + @Test + @DisplayName("Test Create - limits - over maximum X") + @Order(23) + void testCreateCommand_Limits_OverMinimumX() { + performCommand(mrSparkzz, "shop create TestShop 10 12 16 100 20 40"); + double[] maximum = Config.getMaxDimensions(); + assertEquals(Notifier.compose(STORE_CREATE_FAIL_MAX_DIMS, Map.of( + "limit-max-x", maximum[0], + "limit-max-y", maximum[1], + "limit-max-z", maximum[2] + )), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - limits - over maximum x"); + } + + @Test + @DisplayName("Test Create - limits - over maximum Y") + @Order(24) + void testCreateCommand_Limits_OverMinimumY() { + performCommand(mrSparkzz, "shop create TestShop 10 12 16 20 100 40"); + double[] maximum = Config.getMaxDimensions(); + assertEquals(Notifier.compose(STORE_CREATE_FAIL_MAX_DIMS, Map.of( + "limit-max-x", maximum[0], + "limit-max-y", maximum[1], + "limit-max-z", maximum[2] + )), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - limits - over maximum y"); + } + + @Test + @DisplayName("Test Create - limits - over maximum Z") + @Order(25) + void testCreateCommand_Limits_OverMinimumZ() { + performCommand(mrSparkzz, "shop create TestShop 10 12 16 20 20 100"); + double[] maximum = Config.getMaxDimensions(); + assertEquals(Notifier.compose(STORE_CREATE_FAIL_MAX_DIMS, Map.of( + "limit-max-x", maximum[0], + "limit-max-y", maximum[1], + "limit-max-z", maximum[2] + )), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - limits - over maximum z"); + } + + @Test + @DisplayName("Test Create - limits - zero maximum X") + @Order(26) + void testCreateCommand_Limits_ZeroMaximumX() { + Config.setMaxDimensions(0D, 0D ,0D); + Config.setMaxVolume(27000D); + performCommand(mrSparkzz, "shop create TestShop 120 120 120 150 150 150"); + assertEquals(Notifier.compose(STORE_CREATE_SUCCESS, Collections.singletonMap("store", "TestShop")), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - limits - zero maximum x"); + } + + @Test + @DisplayName("Test Create - limits - zero maximum Y") + @Order(26) + void testCreateCommand_Limits_ZeroMaximumY() { + Config.setMaxDimensions(35D, 0D ,0D); + Config.setMaxVolume(27000D); + performCommand(mrSparkzz, "shop create TestShop 120 120 120 150 150 150"); + assertEquals(Notifier.compose(STORE_CREATE_SUCCESS, Collections.singletonMap("store", "TestShop")), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - limits - zero maximum y"); + } + + @Test + @DisplayName("Test Create - limits - zero maximum Z") + @Order(26) + void testCreateCommand_Limits_ZeroMaximumZ() { + Config.setMaxDimensions(35D, 35D ,0D); + Config.setMaxVolume(27000D); + performCommand(mrSparkzz, "shop create TestShop 120 120 120 150 150 150"); + assertEquals(Notifier.compose(STORE_CREATE_SUCCESS, Collections.singletonMap("store", "TestShop")), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - limits - zero maximum z"); + } + + @Test + @DisplayName("Test Create - limits - minimum volume") + @Order(27) + void testCreateCommand_Limits_MinimumVolume() { + Config.setMinVolume(28D); + performCommand(mrSparkzz, "shop create TestShop 120 120 120 123 123 123"); + assertEquals(Notifier.compose(STORE_CREATE_FAIL_MIN_VOL, Collections.singletonMap("limit-min-vol", Config.getMinVolume())), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - limits - minimum volume"); + } + + @Test + @DisplayName("Test Create - limits - maximum volume") + @Order(28) + void testCreateCommand_Limits_MaximumVolume() { + Config.setMaxVolume(20D); + performCommand(mrSparkzz, "shop create TestShop 120 120 120 123 123 123"); + assertEquals(Notifier.compose(STORE_CREATE_FAIL_MAX_VOL, Collections.singletonMap("limit-max-vol", Config.getMaxVolume())), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - limits - maximum volume"); + } + + @Test + @DisplayName("Test Create - main functionality - zero max volume") + @Order(29) + void testCreateCommand_Limits_ZeroMaxVolume() { + Config.setMaxDimensions(0D, 0D, 0D); + Config.setMaxVolume(0); + performCommand(mrSparkzz, "shop create TestShop 205 205 205 308 308 308"); + assertEquals(Notifier.compose(STORE_CREATE_SUCCESS, Collections.singletonMap("store", "TestShop")), mrSparkzz.nextMessage()); + printSuccessMessage("create command test - zero max volume"); + } } diff --git a/src/test/java/net/sparkzz/command/sub/RemoveCommandTest.java b/src/test/java/net/sparkzz/command/sub/RemoveCommandTest.java index a37a136..96d4602 100644 --- a/src/test/java/net/sparkzz/command/sub/RemoveCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/RemoveCommandTest.java @@ -107,7 +107,7 @@ void testRemoveCommand_RemoveAll() { } @Test - @DisplayName("Test Remove - material not found in shop") + @DisplayName("Test Remove - material not found in store") @Order(4) void testRemoveCommand_NoMaterial() { performCommand(mrSparkzz, "shop remove stick 1"); diff --git a/src/test/java/net/sparkzz/shops/StoreTest.java b/src/test/java/net/sparkzz/shops/StoreTest.java index fb75b7f..a2998f4 100644 --- a/src/test/java/net/sparkzz/shops/StoreTest.java +++ b/src/test/java/net/sparkzz/shops/StoreTest.java @@ -75,7 +75,7 @@ void testGetSellPrice_MaterialNotInStore() { void testRemoveFunds_MoreThanStoreBalance() { Store.getDefaultStore(null).get().removeFunds(10D); assertEquals(0D, Store.getDefaultStore(null).get().getBalance()); - printSuccessMessage("remove funds - more than stpre balance"); + printSuccessMessage("remove funds - more than store balance"); } @Test diff --git a/src/test/java/net/sparkzz/util/ConfigTest.java b/src/test/java/net/sparkzz/util/ConfigTest.java index 24c0903..31477ba 100644 --- a/src/test/java/net/sparkzz/util/ConfigTest.java +++ b/src/test/java/net/sparkzz/util/ConfigTest.java @@ -3,9 +3,11 @@ import be.seeseemelk.mockbukkit.MockBukkit; import be.seeseemelk.mockbukkit.ServerMock; import net.sparkzz.shops.Shops; +import net.sparkzz.shops.Store; import org.bukkit.World; import org.bukkit.WorldCreator; import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.MethodOrderer; @@ -17,22 +19,27 @@ import static net.sparkzz.shops.TestHelper.*; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; @DisplayName("Config Test") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class ConfigTest { + private static ServerMock server; + private static Store store, otherStore; private static World world, world_nether, world_the_end; @BeforeAll static void setUp() { printMessage("==[ TEST CONFIG ]=="); - ServerMock server = MockBukkit.getOrCreateMock(); + server = MockBukkit.getOrCreateMock(); MockBukkit.load(Shops.class); loadConfig(); world = server.createWorld(WorldCreator.name("world")); world_nether = server.createWorld(WorldCreator.name("world_nether")); world_the_end = server.createWorld(WorldCreator.name("world_the_end")); + store = new Store("TestStore"); + otherStore = new Store("TestStore2"); } @AfterAll @@ -50,7 +57,15 @@ static void tearDown() { Config.setMaxVolume(1024D); Config.setOffLimitsAreas(cuboids); Config.setMaxOwnedStores(2); + Config.setDefaultStore(null, null); unLoadConfig(); + Store.STORES.clear(); + Store.DEFAULT_STORES.clear(); + } + + @AfterEach + void resetConfig() { + Config.setDefaultStore(null, null); } @Test @@ -127,4 +142,28 @@ void testSetMaxOwnedStores() { assertEquals(5, Config.getMaxOwnedStores()); printSuccessMessage("setting maximum owned stores"); } + + @Test + @DisplayName("Test set default store for all worlds") + @Order(8) + void testGlobalDefaultStore() { + Config.setDefaultStore(world, otherStore); + Config.setDefaultStore(server.getWorld("null"), store); + assertTrue(Config.getDefaultStore(null).isPresent()); + assertEquals(store, Config.getDefaultStore(null).get()); + printSuccessMessage("setting default store for all world"); + } + + @Test + @DisplayName("Test set default store for specific worlds") + @Order(9) + void testDefaultStore_PerWorld() { + Config.setDefaultStore(world, store); + Config.setDefaultStore(world_nether, otherStore); + assertTrue(Config.getDefaultStore(world).isPresent()); + assertTrue(Config.getDefaultStore(world_nether).isPresent()); + assertEquals(store, Config.getDefaultStore(world).get()); + assertEquals(otherStore, Config.getDefaultStore(world_nether).get()); + printSuccessMessage("setting default store for specific world"); + } } diff --git a/src/test/resources/config.yml b/src/test/resources/config.yml index 8caa99d..8ee988f 100644 --- a/src/test/resources/config.yml +++ b/src/test/resources/config.yml @@ -1,5 +1,4 @@ store: - default: [] max-owned-stores: 2 min-dimensions: x: 3 From 4c53819c2d54312d83165e7414423fdcef16f526 Mon Sep 17 00:00:00 2001 From: Brendon Butler Date: Wed, 23 Aug 2023 21:49:38 -0400 Subject: [PATCH 08/11] fix default 'null' world not loading for all worlds fix Config and IMS tests --- src/main/java/net/sparkzz/util/Config.java | 12 ++++++------ src/main/java/net/sparkzz/util/Warehouse.java | 2 +- src/test/java/net/sparkzz/util/ConfigTest.java | 3 ++- .../util/InventoryManagementSystemTest.java | 15 +++++++++++++++ 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/main/java/net/sparkzz/util/Config.java b/src/main/java/net/sparkzz/util/Config.java index 76e7a26..013434d 100644 --- a/src/main/java/net/sparkzz/util/Config.java +++ b/src/main/java/net/sparkzz/util/Config.java @@ -168,11 +168,11 @@ public static Optional getDefaultStore(@Nullable World world) { CommentedConfigurationNode defaults = rootNode.node("store").node("default"); - if (defaults.hasChild("'null'")) - return Store.identifyStore(defaults.node("'null'").getString()); + if (defaults.hasChild("null")) + return Store.identifyStore(defaults.node("null").getString()); - String name = (world == null) ? "'null'" : world.getName(); - String uuid = (world == null) ? "'null'" : world.getUID().toString(); + String name = (world == null) ? "null" : world.getName(); + String uuid = (world == null) ? "null" : world.getUID().toString(); if (defaults.hasChild(uuid)) { return Store.identifyStore(defaults.node(uuid).getString()); @@ -226,12 +226,12 @@ public static void setDefaultStore(@Nullable World world, @Nullable Store store) CommentedConfigurationNode defaults = rootNode.node("store", "default"); if (store == null) { - defaults.removeChild((world == null) ? "'null'" : world.getName()); + defaults.removeChild((world == null) ? "null" : world.getName()); return; } if (world == null || world.getName().equalsIgnoreCase("null")) { - defaults.node("'null'").set(store.getUUID().toString()); + defaults.node("null").set(store.getUUID().toString()); return; } diff --git a/src/main/java/net/sparkzz/util/Warehouse.java b/src/main/java/net/sparkzz/util/Warehouse.java index f0299b3..651196e 100644 --- a/src/main/java/net/sparkzz/util/Warehouse.java +++ b/src/main/java/net/sparkzz/util/Warehouse.java @@ -145,7 +145,7 @@ private static void loadStores() { } } - log.info(String.format("%d %s loaded", STORES.size(), (STORES.size() == 1) ? "shop" : "shops")); + log.info(String.format("%d %s loaded", STORES.size(), (STORES.size() == 1) ? "store" : "stores")); } catch (SerializationException e) { throw new RuntimeException(e); } diff --git a/src/test/java/net/sparkzz/util/ConfigTest.java b/src/test/java/net/sparkzz/util/ConfigTest.java index 31477ba..2796d04 100644 --- a/src/test/java/net/sparkzz/util/ConfigTest.java +++ b/src/test/java/net/sparkzz/util/ConfigTest.java @@ -57,7 +57,6 @@ static void tearDown() { Config.setMaxVolume(1024D); Config.setOffLimitsAreas(cuboids); Config.setMaxOwnedStores(2); - Config.setDefaultStore(null, null); unLoadConfig(); Store.STORES.clear(); Store.DEFAULT_STORES.clear(); @@ -150,7 +149,9 @@ void testGlobalDefaultStore() { Config.setDefaultStore(world, otherStore); Config.setDefaultStore(server.getWorld("null"), store); assertTrue(Config.getDefaultStore(null).isPresent()); + assertTrue(Config.getDefaultStore(world).isPresent()); assertEquals(store, Config.getDefaultStore(null).get()); + assertEquals(store, Config.getDefaultStore(world).get()); printSuccessMessage("setting default store for all world"); } diff --git a/src/test/java/net/sparkzz/util/InventoryManagementSystemTest.java b/src/test/java/net/sparkzz/util/InventoryManagementSystemTest.java index 789b4bb..90d85d7 100644 --- a/src/test/java/net/sparkzz/util/InventoryManagementSystemTest.java +++ b/src/test/java/net/sparkzz/util/InventoryManagementSystemTest.java @@ -8,6 +8,7 @@ import net.sparkzz.shops.mocks.MockVault; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.WorldCreator; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginDescriptionFile; import org.junit.jupiter.api.AfterAll; @@ -48,6 +49,8 @@ static void setUp() { mrSparkzz = server.addPlayer("MrSparkzz"); mrSparkzz.setOp(true); + server.createWorld(WorldCreator.name("world")); + server.createWorld(WorldCreator.name("world_nether")); Store.setDefaultStore(mrSparkzz.getWorld(), (store = new Store("BetterBuy", mrSparkzz.getUniqueId()))); secondaryStore = new Store("SecondaryStore", mrSparkzz.getUniqueId(), new Cuboid(server.getWorld("world"), -20D, -20D, -20D, 20D, 20D, 20D)); } @@ -248,6 +251,7 @@ void testGetAvailableSpace_Store_MaxQuantityNegative() { @DisplayName("Test IMS - identify store - within secondary store") @Order(18) void testIdentifyStore_WithinSecondaryStore() { + Store.setDefaultStore(null, null); mrSparkzz.setLocation(new Location(server.getWorld("world"), 0D, 0D, 0D)); assertEquals(secondaryStore, InventoryManagementSystem.locateCurrentStore(mrSparkzz).orElse(null)); @@ -275,4 +279,15 @@ void testIdentifyStore_NotWithinAnyStore() { assertNull(InventoryManagementSystem.locateCurrentStore(mrSparkzz).orElse(null)); printSuccessMessage("IMS - identify store - not within secondary store"); } + + @Test + @DisplayName("Test IMS - identify store - inter-global default in another world") + @Order(21) + void testIdentifyStore_InterGlobalDefaultInAnotherWorld() { + mrSparkzz.setLocation(new Location(server.getWorld("world_nether"), 0D, 0D, 0D)); + + System.out.println(mrSparkzz.getWorld()); + assertEquals(store, InventoryManagementSystem.locateCurrentStore(mrSparkzz).orElse(null)); + printSuccessMessage("IMS - identify store - not within secondary store"); + } } From 00eeb1d9b09fbf6a645ce9712bfe34c22d018d54 Mon Sep 17 00:00:00 2001 From: Brendon Butler Date: Fri, 25 Aug 2023 17:15:52 -0400 Subject: [PATCH 09/11] GH-15 add permissions to autofill clean up tab complete by using switch statements and making cases modular with additional methods --- .../java/net/sparkzz/command/ShopCommand.java | 441 ++++++++++-------- .../sparkzz/command/sub/UpdateCommand.java | 7 +- src/main/java/net/sparkzz/util/Notifier.java | 1 + src/main/resources/plugin.yml | 4 + 4 files changed, 255 insertions(+), 198 deletions(-) diff --git a/src/main/java/net/sparkzz/command/ShopCommand.java b/src/main/java/net/sparkzz/command/ShopCommand.java index 5ef68bc..8b01ba5 100644 --- a/src/main/java/net/sparkzz/command/ShopCommand.java +++ b/src/main/java/net/sparkzz/command/ShopCommand.java @@ -11,8 +11,10 @@ import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; +import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.generator.WorldInfo; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -25,6 +27,7 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import java.util.stream.Stream; import static org.bukkit.ChatColor.RED; @@ -35,6 +38,8 @@ */ public class ShopCommand extends CommandManager { + private final Server server = (Shops.isTest() ? Shops.getMockServer() : Shops.getPlugin(Shops.class).getServer()); + private final Map subCommands = new HashMap<>() {{ put("add", new AddCommand()); put("browse", new BrowseCommand()); @@ -49,278 +54,320 @@ public class ShopCommand extends CommandManager { put("withdraw", new WithdrawCommand()); }}; - /** - * TabCompleter for generating suggestions when a player starts typing the /shop command - * - * @param sender the sender attempting the command - * @param command the command to be processed - * @param label the command label - * @param args the arguments following the command - * @return a list of options for the /shop command arguments - */ - // TODO: clean up this mess (reconfigure if-blocks/switches to be more efficient and less clunky - @Override - @SuppressWarnings("all") - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if (!(sender instanceof Player)) { - sender.sendMessage(String.format("%sOnly players can use this command!", RED)); - return new ArrayList<>(); - } - - if (args.length == 1) - return subCommands.keySet().stream().toList(); - - if (args.length == 2) { - if (args[0].equalsIgnoreCase("browse")) - return Collections.singletonList(""); + private List handleSecondArgs(CommandSender sender, String arg0) { + Optional currentStore = InventoryManagementSystem.locateCurrentStore(((Player) sender)); + Set shopItems = (currentStore.map(store -> store.getItems().keySet()).orElse(Collections.emptySet())); - if (args[0].equalsIgnoreCase("deposit")) - return Collections.singletonList(""); + return switch (arg0) { + case "add" -> { + Player player = (Player) sender; + ItemStack[] inventoryContents = player.getInventory().getContents(); - if (args[0].equalsIgnoreCase("withdraw")) - return List.of("", "all"); - - // Add command autocomplete item list - if (args[0].equalsIgnoreCase("add")) { - return Arrays.stream(Material.values()) - .map(m -> m.toString().toLowerCase()).collect(Collectors.toList()); + yield Arrays.stream(inventoryContents) + .filter(Objects::nonNull) + .filter(m -> sender.hasPermission("shops.cmd.add")) + .map(item -> item.getType().toString().toLowerCase()) + .toList(); } - - Optional currentStore = InventoryManagementSystem.locateCurrentStore(((Player) sender)); - Set shopItems = (currentStore.isPresent() ? currentStore.get().getItems().keySet() : Collections.emptySet()); - - // Buy/Remove command autocomplete item list - if (args[0].equalsIgnoreCase("buy") || args[0].equalsIgnoreCase("remove")) - return shopItems.stream().map(m -> m.toString().toLowerCase()).collect(Collectors.toList()); - - // provide a list of items witin the shop, along with some additional items based on permissions - if (args[0].equalsIgnoreCase("update")) { - ArrayList tempList = shopItems.stream().map(m -> m.toString().toLowerCase()).collect(Collectors.toCollection(ArrayList::new)); - if (((Player) sender).hasPermission("shops.update.inf-funds")) tempList.add("infinite-funds"); - if (((Player) sender).hasPermission("shops.update.inf-stock")) tempList.add("infinite-stock"); - tempList.add("shop-name"); - - return tempList; + case "browse" -> (sender.hasPermission("shops.cmd.browse") ? Collections.singletonList("") : new ArrayList()); + case "buy", "remove" -> shopItems.stream() + .filter(s -> (sender.hasPermission("shops.cmd." + arg0))) + .map(m -> m.toString().toLowerCase()).collect(Collectors.toList()); + case "create" -> (sender.hasPermission("shops.cmd.create") ? Collections.singletonList("") : new ArrayList()); + case "delete", "transfer" -> Store.STORES.stream() + .filter(s -> (sender.hasPermission("shops.cmd." + arg0)) && + s.getOwner().equals(((Player) sender).getUniqueId())) + .map(s -> String.format("%s~%s", s.getName(), s.getUUID())) + .toList(); + case "deposit" -> (sender.hasPermission("shops.cmd.deposit") ? Collections.singletonList("") : new ArrayList()); + case "withdraw" -> (sender.hasPermission("shops.cmd.withdraw") ? List.of("", "all") : new ArrayList()); + case "update" -> { + if (!sender.hasPermission("shops.cmd.update")) + yield Collections.emptyList(); + + ArrayList tempList = shopItems.stream() + .filter(m -> sender.hasPermission("shops.cmd.update")) + .map(m -> m.toString().toLowerCase()) + .collect(Collectors.toCollection(ArrayList::new)); + if (sender.hasPermission("shops.update.inf-funds")) tempList.add("infinite-funds"); + if (sender.hasPermission("shops.update.inf-stock")) tempList.add("infinite-stock"); + if (sender.hasPermission("shops.update.location")) tempList.add("location"); + tempList.add("store-name"); + + yield tempList; } - - // Sell command autocomplete item list - if (args[0].equalsIgnoreCase("sell")) - return Arrays.stream(((Player) sender).getInventory().getContents()) - .filter(Objects::nonNull).map(i -> i.getType().toString().toLowerCase()) - .collect(Collectors.toList()); - - if (args[0].equalsIgnoreCase("create")) - return Collections.singletonList(""); - - // Only display a list of shops that are owned by the player, and provide a list of "ShopName~UUID" - if (args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("transfer")) - return Store.STORES.stream().filter(s -> s.getOwner().equals(((Player) sender).getUniqueId())).map(s -> String.format("%s~%s", s.getName(), s.getUUID())).collect(Collectors.toCollection(ArrayList::new)); - } - - Server server = (Shops.isTest() ? Shops.getMockServer() : Shops.getPlugin(Shops.class).getServer()); - - if (args.length == 3) { - if (args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("sell")) - return List.of("[]", "all"); - - if (args[0].equalsIgnoreCase("add")) - return List.of("", "[]", "all"); - - if (args[0].equalsIgnoreCase("buy")) - return Collections.singletonList("[]"); - - if (args[0].equalsIgnoreCase("update")) { - List options; - - switch (args[1].toLowerCase()) { - case "infinite-funds", "infinite-stock" -> options = List.of("true", "false"); - case "shop-name" -> options = Collections.singletonList(""); - case "location" -> { - options = Store.STORES.stream().filter(s -> s.getOwner().equals(((Player) sender).getUniqueId())).map(s -> String.format("%s~%s", s.getName(), s.getUUID())).collect(Collectors.toCollection(ArrayList::new)); - options.addAll(Bukkit.getWorlds().stream().map(WorldInfo::getName).toList()); - } - default -> options = List.of("customer-buy-price", "customer-sell-price", "infinite-quantity", "max-quantity"); - }; - - return options; + case "sell" -> { + Player player = (Player) sender; + ItemStack[] inventoryContents = player.getInventory().getContents(); + + yield Arrays.stream(inventoryContents) + .filter(Objects::nonNull) + .filter(m -> player.hasPermission("shops.cmd.sell")) + .map(item -> item.getType().toString().toLowerCase()) + .toList(); } + default -> Collections.emptyList(); + }; + } - if (args[0].equalsIgnoreCase("transfer")) - return server.getOnlinePlayers().stream().map(p -> p.getName()).collect(Collectors.toList()); - - if (args[0].equalsIgnoreCase("create")) { - List options = server.getOnlinePlayers().stream().map(p -> p.getName()).collect(Collectors.toList()); + private List handleThirdArgs(CommandSender sender, String[] args) { + return switch (args[0]) { + case "add" -> (sender.hasPermission("shops.cmd.add") ? List.of("", "[]", "all") : new ArrayList()); + case "buy" -> (sender.hasPermission("shops.cmd.buy") ? Collections.singletonList("[]") : new ArrayList()); + case "create" -> { + List options = server.getOnlinePlayers().stream().map(HumanEntity::getName).collect(Collectors.toList()); options.add(""); - return options; + yield options; } - } + case "remove", "sell" -> (sender.hasPermission("shops.cmd." + args[0]) ? List.of("[]", "all") : new ArrayList()); + case "transfer" -> (sender.hasPermission("shops.cmd.transfer") ? server.getOnlinePlayers().stream().map(HumanEntity::getName).toList() : new ArrayList()); + case "update" -> { + List options = new ArrayList<>(); + + if (!sender.hasPermission("shops.cmd.update")) + yield options; + + if ((sender.hasPermission("shops.update.inf-funds") && args[1].equals("infinite-funds")) || + (sender.hasPermission("shops.update.inf-stock")) && args[1].equals("infinite-stock")) { + options = List.of("true", "false"); + } else if (args[1].equals("store-name")) { + options = Collections.singletonList(""); + } else if (args[1].equals("location")) { + yield Stream.concat(Store.STORES.stream() + .filter(s -> s.getOwner().equals(((Player) sender).getUniqueId())) + .map(s -> String.format("%s~%s", s.getName(), s.getUUID())), + Bukkit.getWorlds().stream().map(WorldInfo::getName) + ).toList(); + } else { + options = List.of("customer-buy-price", "customer-sell-price", "infinite-quantity", "max-quantity"); + } - if (args.length == 4) { - if (args[0].equalsIgnoreCase("add")) { - return Collections.singletonList(""); + yield options; } + default -> Collections.emptyList(); + }; + } + + private List handleFourthArgs(CommandSender sender, String[] args) { + return switch (args[0]) { + case "add" -> (sender.hasPermission("shops.cmd.add") ? Collections.singletonList("") : new ArrayList()); + case "create" -> { + if (!sender.hasPermission("shops.cmd.create")) + yield Collections.emptyList(); + + yield (server.getPlayer(args[2]) != null) ? Collections.singletonList("") : Collections.singletonList(""); + } + case "update" -> { + if (args[1].equals("location")) { + if (!sender.hasPermission("shops.cmd.update") || !sender.hasPermission("shops.update.location")) + yield Collections.emptyList(); - if (args[0].equalsIgnoreCase("update")) { - if (args[1].equalsIgnoreCase("location")) { - List stores = Store.STORES.stream().map(Store::getName).collect(Collectors.toList()); List options = Bukkit.getWorlds().stream().map(WorldInfo::getName).collect(Collectors.toList()); boolean containsWorld = Bukkit.getWorlds().stream().map(WorldInfo::getName).anyMatch(w -> w.equalsIgnoreCase(args[2]) || w.equalsIgnoreCase(args[3])); - boolean containsStore = stores.stream().anyMatch(s -> s.equalsIgnoreCase(args[2])); + boolean containsStore = Store.identifyStore(args[2]).isPresent(); if (containsWorld) - options = Collections.singletonList("x1"); - else if (!containsWorld && !containsStore) - options = Collections.singletonList("y1"); + options = Collections.singletonList(""); else if (!containsStore) - options.add("x1"); + options = Collections.singletonList(""); + else options.add(""); - return options; + yield options; } - return switch (args[2].toLowerCase()) { - case "infinite-quantity" -> List.of("true", "false"); - default -> Collections.singletonList(""); - }; + yield (args[2].equals("infinite-quantity") ? List.of("true", "false") : Collections.singletonList("")); } + default -> Collections.emptyList(); + }; + } - if (args[0].equalsIgnoreCase("create") && server.getPlayer(args[2]) != null) - return Collections.singletonList(""); - else if (args[0].equalsIgnoreCase("create")) - return Collections.singletonList(""); - } + private List handleFifthArgs(CommandSender sender, String[] args) { + return switch (args[0]) { + case "add" -> (sender.hasPermission("shops.cmd.add") ? Collections.singletonList("") : new ArrayList()); + case "create" -> { + if (!sender.hasPermission("shops.cmd.create")) + yield Collections.emptyList(); - if (args.length == 5 ) { - if (args[0].equalsIgnoreCase("add")) { - return Collections.singletonList(""); + yield (server.getPlayer(args[2]) != null) ? Collections.singletonList("") : Collections.singletonList(""); } + case "update" -> { + if (!sender.hasPermission("shops.cmd.update") || !sender.hasPermission("shops.update.location")) + yield Collections.emptyList(); - if (args[0].equalsIgnoreCase("create") && server.getPlayer(args[2]) != null) - return Collections.singletonList(""); - else if (args[0].equalsIgnoreCase("create")) - return Collections.singletonList(""); + List options = Collections.singletonList(""); - if (args[0].equalsIgnoreCase("update") && args[1].equalsIgnoreCase("location")) { - List stores = Store.STORES.stream().map(Store::getName).collect(Collectors.toList()); - List options = Collections.singletonList("x1"); - - boolean containsWorld = Bukkit.getWorlds().stream().map(WorldInfo::getName).anyMatch(w -> w.equalsIgnoreCase(args[2]) || w.equalsIgnoreCase(args[3])); - boolean containsStore = stores.stream().anyMatch(s -> s.equalsIgnoreCase(args[2])); + boolean containsWorld = Bukkit.getWorlds().stream().map(WorldInfo::getName).anyMatch(w -> + w.equalsIgnoreCase(args[2]) || w.equalsIgnoreCase(args[3])); + boolean containsStore = Store.identifyStore(args[2]).isPresent(); if (containsWorld && !containsStore) - options = Collections.singletonList("y1"); + options = Collections.singletonList(""); else if (!containsWorld && !containsStore) - options = Collections.singletonList("z1"); + options = Collections.singletonList(""); - return options; + yield options; } - } + default -> Collections.emptyList(); + }; + } - if (args.length == 6) { - if (args[0].equalsIgnoreCase("add")) { - return List.of("[]", "all"); - } + private List handleSixthArgs(CommandSender sender, String[] args) { + return switch (args[0]) { + case "add" -> (sender.hasPermission("shops.cmd.add") ? List.of("[]", "all") : new ArrayList()); + case "create" -> { + if (!sender.hasPermission("shops.cmd.create")) + yield Collections.emptyList(); - if (args[0].equalsIgnoreCase("create") && server.getPlayer(args[2]) != null) - return Collections.singletonList(""); - else if (args[0].equalsIgnoreCase("create")) - return Collections.singletonList(""); + yield (server.getPlayer(args[2]) != null) ? Collections.singletonList("") : Collections.singletonList(""); + } + case "update" -> { + if (!sender.hasPermission("shops.cmd.update") || !sender.hasPermission("shops.update.location")) + yield Collections.emptyList(); - if (args[0].equalsIgnoreCase("update") && args[1].equalsIgnoreCase("location")) { - List stores = Store.STORES.stream().map(Store::getName).collect(Collectors.toList()); - List options = Collections.singletonList("y1"); + List options = Collections.singletonList(""); boolean containsWorld = Bukkit.getWorlds().stream().map(WorldInfo::getName).anyMatch(w -> w.equalsIgnoreCase(args[2]) || w.equalsIgnoreCase(args[3])); - boolean containsStore = stores.stream().anyMatch(s -> s.equalsIgnoreCase(args[2])); + boolean containsStore = Store.identifyStore(args[2]).isPresent(); if (containsWorld && !containsStore) - options = Collections.singletonList("z1"); + options = Collections.singletonList(""); else if (!containsWorld && !containsStore) - options = Collections.singletonList("x2"); + options = Collections.singletonList(""); - return options; + yield options; } - } + default -> Collections.emptyList(); + }; + } - if (args.length == 7) { - if (args[0].equalsIgnoreCase("create") && server.getPlayer(args[2]) != null) - return Collections.singletonList(""); - else if (args.length == 7 && args[0].equalsIgnoreCase("create")) - return Collections.singletonList(""); + private List handleSeventhArgs(CommandSender sender, String[] args) { + return switch (args[0]) { + case "create" -> { + if (!sender.hasPermission("shops.cmd.create")) + yield Collections.emptyList(); - if (args[0].equalsIgnoreCase("update") && args[1].equalsIgnoreCase("location")) { - List stores = Store.STORES.stream().map(Store::getName).collect(Collectors.toList()); - List options = Collections.singletonList("z1"); + yield (server.getPlayer(args[2]) != null) ? Collections.singletonList("") : Collections.singletonList(""); + } + case "update" -> { + if (!sender.hasPermission("shops.cmd.update") || !sender.hasPermission("shops.update.location")) + yield Collections.emptyList(); + + List options = Collections.singletonList(""); boolean containsWorld = Bukkit.getWorlds().stream().map(WorldInfo::getName).anyMatch(w -> w.equalsIgnoreCase(args[2]) || w.equalsIgnoreCase(args[3])); - boolean containsStore = stores.stream().anyMatch(s -> s.equalsIgnoreCase(args[2])); + boolean containsStore = Store.identifyStore(args[2]).isPresent(); if (containsWorld && !containsStore) - options = Collections.singletonList("x2"); + options = Collections.singletonList(""); else if (!containsWorld && !containsStore) - options = Collections.singletonList("y2"); + options = Collections.singletonList(""); - return options; + yield options; } - } + default -> Collections.emptyList(); + }; + } + + private List handleEighthArgs(CommandSender sender, String[] args) { + return switch (args[0]) { + case "create" -> { + if (!sender.hasPermission("shops.cmd.create")) + yield Collections.emptyList(); - if (args.length == 8) { - if (args[0].equalsIgnoreCase("create") && server.getPlayer(args[2]) != null) - return Collections.singletonList(""); - else if (args[0].equalsIgnoreCase("create")) - return Collections.singletonList(""); + yield (server.getPlayer(args[2]) != null) ? Collections.singletonList("") : Collections.singletonList(""); + } + case "update" -> { + if (!sender.hasPermission("shops.cmd.update") || !sender.hasPermission("shops.update.location")) + yield Collections.emptyList(); - if (args[0].equalsIgnoreCase("update") && args[1].equalsIgnoreCase("location")) { - List stores = Store.STORES.stream().map(Store::getName).collect(Collectors.toList()); - List options = Collections.singletonList("x2"); + List options = Collections.singletonList(""); boolean containsWorld = Bukkit.getWorlds().stream().map(WorldInfo::getName).anyMatch(w -> w.equalsIgnoreCase(args[2]) || w.equalsIgnoreCase(args[3])); - boolean containsStore = stores.stream().anyMatch(s -> s.equalsIgnoreCase(args[2])); + boolean containsStore = Store.identifyStore(args[2]).isPresent(); if (containsWorld && !containsStore) - options = Collections.singletonList("y2"); + options = Collections.singletonList(""); else if (!containsWorld && !containsStore) - options = Collections.singletonList("z2"); + options = Collections.singletonList(""); - return options; + yield options; } - } + default -> Collections.emptyList(); + }; + } - if (args.length == 9) { - if (args[0].equalsIgnoreCase("create") && server.getPlayer(args[2]) != null) - return Collections.singletonList(""); + private List handleNinthArgs(CommandSender sender, String[] args) { + return switch (args[0]) { + case "create" -> (sender.hasPermission("shops.cmd.create") && server.getPlayer(args[2]) != null) + ? Collections.singletonList("") : Collections.emptyList(); + case "update" -> { + if (!sender.hasPermission("shops.cmd.update") || !sender.hasPermission("shops.update.location")) + yield Collections.emptyList(); - if (args[0].equalsIgnoreCase("update") && args[1].equalsIgnoreCase("location")) { - List stores = Store.STORES.stream().map(Store::getName).collect(Collectors.toList()); - List options = Collections.singletonList("y2"); + List options = Collections.singletonList(""); boolean containsWorld = Bukkit.getWorlds().stream().map(WorldInfo::getName).anyMatch(w -> w.equalsIgnoreCase(args[2]) || w.equalsIgnoreCase(args[3])); - boolean containsStore = stores.stream().anyMatch(s -> s.equalsIgnoreCase(args[2])); + boolean containsStore = Store.identifyStore(args[2]).isPresent(); if (containsWorld && !containsStore) - options = Collections.singletonList("z2"); + options = Collections.singletonList(""); else if (!containsWorld && !containsStore) options = Collections.emptyList(); - return options; + yield options; } - } + default -> Collections.emptyList(); + }; + } - if (args.length == 10 && args[0].equalsIgnoreCase("update") && args[1].equalsIgnoreCase("location")) { - List stores = Store.STORES.stream().map(Store::getName).collect(Collectors.toList()); - List options = Collections.singletonList("z2"); + /** + * TabCompleter for generating suggestions when a player starts typing the /shop command + * + * @param sender the sender attempting the command + * @param command the command to be processed + * @param label the command label + * @param args the arguments following the command + * @return a list of options for the /shop command arguments + */ + @Override + @SuppressWarnings("all") + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + if (!(sender instanceof Player)) { + sender.sendMessage(String.format("%sOnly players can use this command!", RED)); + return new ArrayList<>(); + } - boolean containsWorld = Bukkit.getWorlds().stream().map(WorldInfo::getName).anyMatch(w -> w.equalsIgnoreCase(args[2]) || w.equalsIgnoreCase(args[3])); - boolean containsStore = stores.stream().anyMatch(s -> s.equalsIgnoreCase(args[2])); + return switch (args.length) { + case 1 -> { + List subCommandsFiltered = subCommands.keySet().stream().filter(s -> { + return sender.hasPermission(String.format("shops.cmd.%s", s)); + }).collect(Collectors.toList()); - if ((containsWorld && !containsStore) || (!containsWorld && !containsStore)) - options = Collections.emptyList(); + yield subCommandsFiltered; + } + case 2 -> handleSecondArgs(sender, args[0].toLowerCase()); + case 3 -> handleThirdArgs(sender, Arrays.stream(args).map(s -> s.toLowerCase()).toArray(String[]::new)); + case 4 -> handleFourthArgs(sender, Arrays.stream(args).map(s -> s.toLowerCase()).toArray(String[]::new)); + case 5 -> handleFifthArgs(sender, Arrays.stream(args).map(s -> s.toLowerCase()).toArray(String[]::new)); + case 6 -> handleSixthArgs(sender, Arrays.stream(args).map(s -> s.toLowerCase()).toArray(String[]::new)); + case 7 -> handleSeventhArgs(sender, Arrays.stream(args).map(s -> s.toLowerCase()).toArray(String[]::new)); + case 8 -> handleEighthArgs(sender, Arrays.stream(args).map(s -> s.toLowerCase()).toArray(String[]::new)); + case 9 -> handleNinthArgs(sender, Arrays.stream(args).map(s -> s.toLowerCase()).toArray(String[]::new)); + case 10 -> { + if (!sender.hasPermission("shops.cmd.update") || !sender.hasPermission("shops.update.location")) + yield Collections.emptyList(); + + List options = Collections.singletonList(""); - return options; - } + boolean containsWorld = Bukkit.getWorlds().stream().map(WorldInfo::getName).anyMatch(w -> w.equalsIgnoreCase(args[2]) || w.equalsIgnoreCase(args[3])); + boolean containsStore = Store.identifyStore(args[2]).isPresent(); - return new ArrayList<>(); + yield ((containsWorld && !containsStore) || (!containsWorld && !containsStore)) ? Collections.emptyList() : options; + } + default -> Collections.emptyList(); + }; } /** diff --git a/src/main/java/net/sparkzz/command/sub/UpdateCommand.java b/src/main/java/net/sparkzz/command/sub/UpdateCommand.java index 78942b9..db3a383 100644 --- a/src/main/java/net/sparkzz/command/sub/UpdateCommand.java +++ b/src/main/java/net/sparkzz/command/sub/UpdateCommand.java @@ -34,6 +34,11 @@ public boolean process(CommandSender sender, Command command, String label, Stri Store store = (Store) setAttribute("store", InventoryManagementSystem.locateCurrentStore(player).orElse(null)); if (args.length >= 8 && args[1].equalsIgnoreCase("location")) { + if (!player.hasPermission("shops.update.location")) { + Notifier.process(sender, NO_PERMS_LOCATION, getAttributes()); + return true; + } + switch (args.length) { case 8 -> { if (store == null) { @@ -116,7 +121,7 @@ public boolean process(CommandSender sender, Command command, String label, Stri store.setInfiniteStock(Boolean.parseBoolean(args[2])); } - case "shop-name" -> store.setName(args[2]); + case "store-name" -> store.setName(args[2]); default -> { return false; } diff --git a/src/main/java/net/sparkzz/util/Notifier.java b/src/main/java/net/sparkzz/util/Notifier.java index b76428d..a7c38e0 100644 --- a/src/main/java/net/sparkzz/util/Notifier.java +++ b/src/main/java/net/sparkzz/util/Notifier.java @@ -169,6 +169,7 @@ public enum CipherKey { NO_PERMS_CREATE_OTHER("§cYou do not have permission to create stores for other players!"), NO_PERMS_INF_FUNDS("§cYou do not have permission to set infinite funds in your store!"), NO_PERMS_INF_STOCK("§cYou do not have permission to set infinite stock in your store!"), + NO_PERMS_LOCATION("§cYou do not have permission to set the location of your store!"), NO_STORE_FOUND("§cYou are not currently in a store!"), NOT_BUYING("§cThe store is not buying any of these at this time!"), NOT_BUYING_ANYMORE("§cThe Store is not buying any more of these at this time!"), diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 1bd452b..36a2897 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -78,9 +78,13 @@ permissions: children: shops.update.inf-funds: true shops.update.inf-stock: true + shops.update.location: true shops.update.inf-funds: description: Allows a player to update the infinite funds flag default: op shops.update.inf-stock: description: Allows a player to update the infinite stock flag default: op + shops.update.location: + description: Allows a player to update the location of their store + default: op From e402fe1e21bb1e39c3a35cceffd07f2222a2c6c6 Mon Sep 17 00:00:00 2001 From: Brendon Butler Date: Fri, 25 Aug 2023 17:27:59 -0400 Subject: [PATCH 10/11] GH-15 fix broken tests --- .../net/sparkzz/command/ShopCommandTest.java | 50 ++++++++++--------- .../command/sub/UpdateCommandTest.java | 4 +- 2 files changed, 29 insertions(+), 25 deletions(-) diff --git a/src/test/java/net/sparkzz/command/ShopCommandTest.java b/src/test/java/net/sparkzz/command/ShopCommandTest.java index 7ec5873..e69dfb6 100644 --- a/src/test/java/net/sparkzz/command/ShopCommandTest.java +++ b/src/test/java/net/sparkzz/command/ShopCommandTest.java @@ -129,8 +129,12 @@ void testShopTabComplete_Withdraw2Args() { @DisplayName("Test Shop - 2 args - add tab complete") @Order(23) void testShopTabComplete_Add2Args() { - List expectedOptions = Arrays.stream(Material.values()) - .map(m -> m.toString().toLowerCase()).toList(); + mrSparkzz.getInventory().addItem(new ItemStack(Material.EMERALD, 64)); + mrSparkzz.getInventory().addItem(new ItemStack(Material.STICK, 32)); + + List expectedOptions = Arrays.stream(mrSparkzz.getInventory().getContents()) + .filter(Objects::nonNull) + .map(s -> s.getType().toString().toLowerCase()).toList(); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop add "); assertEquals(expectedOptions, actualOptions); @@ -173,7 +177,7 @@ void testShopTabComplete_Update2Args_WhenOp() { List expectedOptions = Arrays.stream(shopItems.toArray()) .map(m -> m.toString().toLowerCase()).collect(Collectors.toList()); - expectedOptions.addAll(List.of("infinite-funds", "infinite-stock", "shop-name")); + expectedOptions.addAll(List.of("infinite-funds", "infinite-stock", "location", "store-name")); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update "); assertEquals(expectedOptions, actualOptions); @@ -188,7 +192,6 @@ void testShopTabComplete_Update2Args_WhenNotOp() { List expectedOptions = Arrays.stream(shopItems.toArray()) .map(m -> m.toString().toLowerCase()).collect(Collectors.toList()); - expectedOptions.add("shop-name"); List actualOptions = server.getCommandTabComplete(player, "shop update "); assertEquals(expectedOptions, actualOptions); @@ -312,7 +315,7 @@ void testShopTabComplete_Update3Args_InfiniteStock() { @Order(46) void testShopTabComplete_Update3Args_ShopName() { List expectedOptions = Collections.singletonList(""); - List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update shop-name "); + List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update store-name "); assertEquals(expectedOptions, actualOptions); printSuccessMessage("tab complete - \"shop update shop-name\""); @@ -401,7 +404,8 @@ void testShopTabComplete_Update4Args() { @DisplayName("Test Shop - 4 args - update location DiscountMinus tab complete") @Order(63) void testShopTabComplete_Update4Args_LocationWithStore() { - List expectedOptions = Bukkit.getWorlds().stream().map(WorldInfo::getName).toList(); + List expectedOptions = Bukkit.getWorlds().stream().map(WorldInfo::getName).collect(Collectors.toList()); + expectedOptions.add(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location DiscountMinus "); assertEquals(expectedOptions, actualOptions); @@ -412,7 +416,7 @@ void testShopTabComplete_Update4Args_LocationWithStore() { @DisplayName("Test Shop - 4 args - update location 10 tab complete") @Order(64) void testShopTabComplete_Update4Args_LocationWithoutStore() { - List expectedOptions = Collections.singletonList("y1"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location 10 "); assertEquals(expectedOptions, actualOptions); @@ -423,7 +427,7 @@ void testShopTabComplete_Update4Args_LocationWithoutStore() { @DisplayName("Test Shop - 4 args - update location world tab complete") @Order(65) void testShopTabComplete_Update4Args_LocationWithoutStoreWithWorld() { - List expectedOptions = Collections.singletonList("x1"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location world "); assertEquals(expectedOptions, actualOptions); @@ -489,7 +493,7 @@ void testShopTabComplete_Create5Args_Player() { @DisplayName("Test Shop - 5 args - update location DiscountMinus world tab complete") @Order(83) void testShopTabComplete_Update5Args_LocationWithStore() { - List expectedOptions = Collections.singletonList("x1"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location DiscountMinus world "); assertEquals(expectedOptions, actualOptions); @@ -500,7 +504,7 @@ void testShopTabComplete_Update5Args_LocationWithStore() { @DisplayName("Test Shop - 5 args - update location 10 20 tab complete") @Order(84) void testShopTabComplete_Update5Args_LocationWithoutStore() { - List expectedOptions = Collections.singletonList("z1"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location 10 20 "); assertEquals(expectedOptions, actualOptions); @@ -511,7 +515,7 @@ void testShopTabComplete_Update5Args_LocationWithoutStore() { @DisplayName("Test Shop - 5 args - update location world 10 tab complete") @Order(85) void testShopTabComplete_Update5Args_LocationWithoutStoreWithWorld() { - List expectedOptions = Collections.singletonList("y1"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location world 10 "); assertEquals(expectedOptions, actualOptions); @@ -577,7 +581,7 @@ void testShopTabComplete_Create6Args_Player() { @DisplayName("Test Shop - 6 args - update location DiscountMinus world 10 tab complete") @Order(105) void testShopTabComplete_Update6Args_LocationWithStore() { - List expectedOptions = Collections.singletonList("y1"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location DiscountMinus world 10 "); assertEquals(expectedOptions, actualOptions); @@ -588,7 +592,7 @@ void testShopTabComplete_Update6Args_LocationWithStore() { @DisplayName("Test Shop - 6 args - update location 10 20 30 tab complete") @Order(106) void testShopTabComplete_Update6Args_LocationWithoutStore() { - List expectedOptions = Collections.singletonList("x2"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location 10 20 30 "); assertEquals(expectedOptions, actualOptions); @@ -599,7 +603,7 @@ void testShopTabComplete_Update6Args_LocationWithoutStore() { @DisplayName("Test Shop - 6 args - update location world 10 20 tab complete") @Order(107) void testShopTabComplete_Update6Args_LocationWithoutStoreWithWorld() { - List expectedOptions = Collections.singletonList("z1"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location world 10 20 "); assertEquals(expectedOptions, actualOptions); @@ -632,7 +636,7 @@ void testShopTabComplete_Create7Args_Player() { @DisplayName("Test Shop - 7 args - update location DiscountMinus world 10 20 tab complete") @Order(112) void testShopTabComplete_Update7Args_LocationWithStore() { - List expectedOptions = Collections.singletonList("z1"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location DiscountMinus world 10 20 "); assertEquals(expectedOptions, actualOptions); @@ -643,7 +647,7 @@ void testShopTabComplete_Update7Args_LocationWithStore() { @DisplayName("Test Shop - 7 args - update location 10 20 30 40 tab complete") @Order(113) void testShopTabComplete_Update7Args_LocationWithoutStore() { - List expectedOptions = Collections.singletonList("y2"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location 10 20 30 40 "); assertEquals(expectedOptions, actualOptions); @@ -654,7 +658,7 @@ void testShopTabComplete_Update7Args_LocationWithoutStore() { @DisplayName("Test Shop - 7 args - update location world 10 20 30 tab complete") @Order(114) void testShopTabComplete_Update7Args_LocationWithoutStoreWithWorld() { - List expectedOptions = Collections.singletonList("x2"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location world 10 20 30 "); assertEquals(expectedOptions, actualOptions); @@ -687,7 +691,7 @@ void testShopTabComplete_Create8Args_Player() { @DisplayName("Test Shop - 8 args - update location DiscountMinus world 10 20 30 tab complete") @Order(122) void testShopTabComplete_Update8Args_LocationWithStore() { - List expectedOptions = Collections.singletonList("x2"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location DiscountMinus world 10 20 30 "); assertEquals(expectedOptions, actualOptions); @@ -698,7 +702,7 @@ void testShopTabComplete_Update8Args_LocationWithStore() { @DisplayName("Test Shop - 8 args - update location 10 20 30 40 50 tab complete") @Order(123) void testShopTabComplete_Update8Args_LocationWithoutStore() { - List expectedOptions = Collections.singletonList("z2"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location 10 20 30 40 50 "); assertEquals(expectedOptions, actualOptions); @@ -709,7 +713,7 @@ void testShopTabComplete_Update8Args_LocationWithoutStore() { @DisplayName("Test Shop - 8 args - update location world 10 20 30 40 tab complete") @Order(124) void testShopTabComplete_Update8Args_LocationWithoutStoreWithWorld() { - List expectedOptions = Collections.singletonList("y2"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location world 10 20 30 40 "); assertEquals(expectedOptions, actualOptions); @@ -731,7 +735,7 @@ void testShopTabComplete_Create9Args_Player() { @DisplayName("Test Shop - 9 args - update location DiscountMinus world 10 20 30 40 tab complete") @Order(131) void testShopTabComplete_Update9Args_LocationWithStore() { - List expectedOptions = Collections.singletonList("y2"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location DiscountMinus world 10 20 30 40 "); assertEquals(expectedOptions, actualOptions); @@ -742,7 +746,7 @@ void testShopTabComplete_Update9Args_LocationWithStore() { @DisplayName("Test Shop - 9 args - update location world 10 20 30 40 50 tab complete") @Order(132) void testShopTabComplete_Update9Args_LocationWithoutStoreWithWorld() { - List expectedOptions = Collections.singletonList("z2"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location world 10 20 30 40 50 "); assertEquals(expectedOptions, actualOptions); @@ -753,7 +757,7 @@ void testShopTabComplete_Update9Args_LocationWithoutStoreWithWorld() { @DisplayName("Test Shop - 10 args - update location DiscountMinus world 10 20 30 40 50 tab complete") @Order(140) void testShopTabComplete_Update10Args_LocationWithStore() { - List expectedOptions = Collections.singletonList("z2"); + List expectedOptions = Collections.singletonList(""); List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop update location DiscountMinus world 10 20 30 40 50 "); assertEquals(expectedOptions, actualOptions); diff --git a/src/test/java/net/sparkzz/command/sub/UpdateCommandTest.java b/src/test/java/net/sparkzz/command/sub/UpdateCommandTest.java index 3591096..13f8f13 100644 --- a/src/test/java/net/sparkzz/command/sub/UpdateCommandTest.java +++ b/src/test/java/net/sparkzz/command/sub/UpdateCommandTest.java @@ -133,8 +133,8 @@ void testUpdateCommand_InfStock() { @DisplayName("Test Update - main functionality - shop name") @Order(7) void testUpdateCommand_ShopName() { - performCommand(mrSparkzz, "shop update shop-name TestShop99"); - assertEquals(String.format("%sYou have successfully updated %s%s%s to %s%s%s in TestShop99!", GREEN, GOLD, "shop-name", GREEN, GOLD, "TestShop99", GREEN), mrSparkzz.nextMessage()); + performCommand(mrSparkzz, "shop update store-name TestShop99"); + assertEquals(String.format("%sYou have successfully updated %s%s%s to %s%s%s in TestShop99!", GREEN, GOLD, "store-name", GREEN, GOLD, "TestShop99", GREEN), mrSparkzz.nextMessage()); assertEquals("TestShop99", store.getName()); printSuccessMessage("update command test - update shop name"); } From 956d8df32c79321fc05c704528dbd73add3f0143 Mon Sep 17 00:00:00 2001 From: Brendon Butler Date: Fri, 25 Aug 2023 21:41:11 -0400 Subject: [PATCH 11/11] GH-15 add additional tests --- .../net/sparkzz/command/ShopCommandTest.java | 108 +++++++++++++++++- 1 file changed, 105 insertions(+), 3 deletions(-) diff --git a/src/test/java/net/sparkzz/command/ShopCommandTest.java b/src/test/java/net/sparkzz/command/ShopCommandTest.java index e69dfb6..c88a219 100644 --- a/src/test/java/net/sparkzz/command/ShopCommandTest.java +++ b/src/test/java/net/sparkzz/command/ShopCommandTest.java @@ -9,6 +9,7 @@ import net.sparkzz.shops.Store; import net.sparkzz.shops.mocks.MockVault; import net.sparkzz.util.InventoryManagementSystem; +import net.sparkzz.util.Notifier; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.generator.WorldInfo; @@ -62,6 +63,7 @@ static void tearDown() { Store.STORES.clear(); } + @SuppressWarnings("OptionalGetWithoutIsPresent") @Order(1) @Nested @DisplayName("OnTabComplete Tests") @@ -763,6 +765,106 @@ void testShopTabComplete_Update10Args_LocationWithStore() { assertEquals(expectedOptions, actualOptions); printSuccessMessage("tab complete - \"shop update location DiscountMinus world 10 20 30 40 50\""); } + + @Test + @DisplayName("Test Shop - 2 args - invalid option") + @Order(151) + void testShopTabComplete_2Args_InvalidOption() { + List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop invalid "); + + assertEquals(Collections.emptyList(), actualOptions); + printSuccessMessage("tab complete - \"shop invalid\""); + } + + @Test + @DisplayName("Test Shop - 3 args - invalid option") + @Order(152) + void testShopTabComplete_3Args_InvalidOption() { + List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop invalid 2 "); + + assertEquals(Collections.emptyList(), actualOptions); + printSuccessMessage("tab complete - \"shop invalid 2\""); + } + + @Test + @DisplayName("Test Shop - 4 args - invalid option") + @Order(153) + void testShopTabComplete_4Args_InvalidOption() { + List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop invalid 2 3 "); + + assertEquals(Collections.emptyList(), actualOptions); + printSuccessMessage("tab complete - \"shop invalid 2 3\""); + } + + @Test + @DisplayName("Test Shop - 5 args - invalid option") + @Order(154) + void testShopTabComplete_5Args_InvalidOption() { + List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop invalid 2 3 4 "); + + assertEquals(Collections.emptyList(), actualOptions); + printSuccessMessage("tab complete - \"shop invalid 2 3 4\""); + } + + @Test + @DisplayName("Test Shop - 6 args - invalid option") + @Order(155) + void testShopTabComplete_6Args_InvalidOption() { + List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop invalid 2 3 4 5 "); + + assertEquals(Collections.emptyList(), actualOptions); + printSuccessMessage("tab complete - \"shop invalid 2 3 4 5\""); + } + + @Test + @DisplayName("Test Shop - 7 args - invalid option") + @Order(156) + void testShopTabComplete_7Args_InvalidOption() { + List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop invalid 2 3 4 5 6 "); + + assertEquals(Collections.emptyList(), actualOptions); + printSuccessMessage("tab complete - \"shop invalid 2 3 4 5 6\""); + } + + @Test + @DisplayName("Test Shop - 8 args - invalid option") + @Order(157) + void testShopTabComplete_8Args_InvalidOption() { + List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop invalid 2 3 4 5 6 7 "); + + assertEquals(Collections.emptyList(), actualOptions); + printSuccessMessage("tab complete - \"shop invalid 2 3 4 5 6 7\""); + } + + @Test + @DisplayName("Test Shop - 9 args - invalid option") + @Order(158) + void testShopTabComplete_9Args_InvalidOption() { + List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop invalid 2 3 4 5 6 7 8 "); + + assertEquals(Collections.emptyList(), actualOptions); + printSuccessMessage("tab complete - \"shop invalid 2 3 4 5 6 7 8\""); + } + + @Test + @DisplayName("Test Shop - 10 args - invalid option") + @Order(159) + void testShopTabComplete_10Args_InvalidOption() { + List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop invalid 2 3 4 5 6 7 8 9 "); + + assertEquals(Collections.emptyList(), actualOptions); + printSuccessMessage("tab complete - \"shop invalid 2 3 4 5 6 7 8 9\""); + } + + @Test + @DisplayName("Test Shop - 11 args - invalid option") + @Order(160) + void testShopTabComplete_11Args_InvalidOption() { + List actualOptions = server.getCommandTabComplete(mrSparkzz, "shop invalid 2 3 4 5 6 7 8 9 10 "); + + assertEquals(Collections.emptyList(), actualOptions); + printSuccessMessage("tab complete - \"shop invalid 2 3 4 5 6 7 8 9 10\""); + } } @Order(2) @@ -776,7 +878,7 @@ class OnCommandTests { @Order(1) void testShopCommand_ConsoleSender() { performCommand(console, "shop"); - assertEquals("§cOnly players can use this command!", console.nextMessage()); + assertEquals(Notifier.compose(Notifier.CipherKey.ONLY_PLAYERS_CMD, null), console.nextMessage()); printSuccessMessage("shop command - console sender"); } @@ -785,7 +887,7 @@ void testShopCommand_ConsoleSender() { @Order(2) void testShopCommand_InvalidArgumentCount() { performCommand(mrSparkzz, "shop"); - assertEquals("§cInvalid number of arguments!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(Notifier.CipherKey.INVALID_ARG_CNT, null), mrSparkzz.nextMessage()); assertEquals("/shop [buy|sell|browse]", mrSparkzz.nextMessage()); printSuccessMessage("shop command - invalid argument count"); } @@ -795,7 +897,7 @@ void testShopCommand_InvalidArgumentCount() { @Order(3) void testShopCommand_InvalidArgumentCountOneArg() { performCommand(mrSparkzz, "shop test"); - assertEquals("§cInvalid number of arguments!", mrSparkzz.nextMessage()); + assertEquals(Notifier.compose(Notifier.CipherKey.INVALID_ARG_CNT, null), mrSparkzz.nextMessage()); assertEquals("/shop [buy|sell|browse]", mrSparkzz.nextMessage()); printSuccessMessage("shop command - invalid argument count (1 arg)"); }