From 24148f30bad3d7a7cca9bb6619a629314ffaa835 Mon Sep 17 00:00:00 2001 From: tastybento Date: Fri, 10 Nov 2023 10:53:28 -0800 Subject: [PATCH] Rank Management (#2220) * Put ranks in the database. Prework for #1798 * Prevent coop and trust commands from being registered if those ranks don't exist. * Add /bbox rank command for ranks management * Rename RanksObject to Ranks * Strip / on commands if it exists. Fixes #2221 * Fix test failure --- .../commands/admin/AdminGetrankCommand.java | 1 + .../island/team/IslandTeamCommand.java | 408 +++++++++--------- .../bentobox/commands/BentoBoxCommand.java | 1 + .../commands/BentoBoxRankCommand.java | 141 ++++++ .../bentobox/database/objects/Ranks.java | 45 ++ .../bentobox/managers/RanksManager.java | 303 ++++++------- src/main/resources/locales/en-US.yml | 11 +- .../commands/admin/AdminInfoCommandTest.java | 394 +++++++++-------- .../admin/AdminSetrankCommandTest.java | 18 +- .../admin/AdminSettingsCommandTest.java | 21 +- .../island/DefaultPlayerCommandTest.java | 235 +++++----- .../commands/island/IslandBanCommandTest.java | 15 +- .../island/IslandBanlistCommandTest.java | 15 +- .../island/IslandDeletehomeCommandTest.java | 18 +- .../island/IslandExpelCommandTest.java | 17 +- .../island/IslandInfoCommandTest.java | 20 +- .../island/IslandUnbanCommandTest.java | 14 +- .../island/team/IslandTeamCommandTest.java | 19 +- .../team/IslandTeamCoopCommandTest.java | 14 +- .../team/IslandTeamInviteCommandTest.java | 10 +- .../team/IslandTeamKickCommandTest.java | 13 +- .../team/IslandTeamPromoteCommandTest.java | 17 +- .../team/IslandTeamTrustCommandTest.java | 14 +- .../team/IslandTeamUncoopCommandTest.java | 8 +- .../team/IslandTeamUntrustCommandTest.java | 10 +- .../CommandRankClickListenerTest.java | 19 +- .../lists/GameModePlaceholderTest.java | 10 +- .../bentobox/managers/PlayersManagerTest.java | 2 - .../managers/RanksManagerBeforeClassTest.java | 84 ++++ .../bentobox/managers/RanksManagerTest.java | 21 +- 30 files changed, 1033 insertions(+), 885 deletions(-) create mode 100644 src/main/java/world/bentobox/bentobox/commands/BentoBoxRankCommand.java create mode 100644 src/main/java/world/bentobox/bentobox/database/objects/Ranks.java create mode 100644 src/test/java/world/bentobox/bentobox/managers/RanksManagerBeforeClassTest.java diff --git a/src/main/java/world/bentobox/bentobox/api/commands/admin/AdminGetrankCommand.java b/src/main/java/world/bentobox/bentobox/api/commands/admin/AdminGetrankCommand.java index 676127186..1c9b10b2e 100644 --- a/src/main/java/world/bentobox/bentobox/api/commands/admin/AdminGetrankCommand.java +++ b/src/main/java/world/bentobox/bentobox/api/commands/admin/AdminGetrankCommand.java @@ -16,6 +16,7 @@ import world.bentobox.bentobox.util.Util; /** + * Tells the rank of the player * @author tastybento * */ diff --git a/src/main/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamCommand.java b/src/main/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamCommand.java index f78a7d318..3de75c4b6 100644 --- a/src/main/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamCommand.java +++ b/src/main/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamCommand.java @@ -24,206 +24,210 @@ public class IslandTeamCommand extends CompositeCommand { - /** - * Invited list. Key is the invited party, value is the invite. - * @since 1.8.0 - */ - private final Map inviteMap; - - public IslandTeamCommand(CompositeCommand parent) { - super(parent, "team"); - inviteMap = new HashMap<>(); - } - - @Override - public void setup() { - setPermission("island.team"); - setOnlyPlayer(true); - setDescription("commands.island.team.description"); - // Register commands - new IslandTeamInviteCommand(this); - new IslandTeamLeaveCommand(this); - new IslandTeamSetownerCommand(this); - new IslandTeamKickCommand(this); - new IslandTeamInviteAcceptCommand(this); - new IslandTeamInviteRejectCommand(this); - new IslandTeamCoopCommand(this); - new IslandTeamUncoopCommand(this); - new IslandTeamTrustCommand(this); - new IslandTeamUntrustCommand(this); - new IslandTeamPromoteCommand(this, "promote"); - new IslandTeamPromoteCommand(this, "demote"); - } - - @Override - public boolean execute(User user, String label, List args) { - // Player issuing the command must have an island - Island island = getIslands().getPrimaryIsland(getWorld(), user.getUniqueId()); - if (island == null) { - user.sendMessage("general.errors.no-island"); - return false; - } - - UUID playerUUID = user.getUniqueId(); - // Fire event so add-ons can run commands, etc. - if (fireEvent(user, island)) { - // Cancelled - return false; - } - Set teamMembers = getMembers(getWorld(), user); - if (playerUUID.equals(island.getOwner())) { - int maxSize = getIslands().getMaxMembers(island, RanksManager.MEMBER_RANK); - if (teamMembers.size() < maxSize) { - user.sendMessage("commands.island.team.invite.you-can-invite", TextVariables.NUMBER, String.valueOf(maxSize - teamMembers.size())); - } else { - user.sendMessage("commands.island.team.invite.errors.island-is-full"); - } - } - // Show members of island - showMembers(island, user); - return true; - } - - private void showMembers(Island island, User user) { - // Gather online members - long count = island - .getMemberSet(RanksManager.MEMBER_RANK) - .stream() - .filter(uuid -> Util.getOnlinePlayerList(user).contains(Bukkit.getOfflinePlayer(uuid).getName())) - .count(); - - // List of ranks that we will loop through - Integer[] ranks = new Integer[]{RanksManager.OWNER_RANK, RanksManager.SUB_OWNER_RANK, RanksManager.MEMBER_RANK, RanksManager.TRUSTED_RANK, RanksManager.COOP_RANK}; - - // Show header: - user.sendMessage("commands.island.team.info.header", - "[max]", String.valueOf(getIslands().getMaxMembers(island, RanksManager.MEMBER_RANK)), - "[total]", String.valueOf(island.getMemberSet().size()), - "[online]", String.valueOf(count)); - - // We now need to get all online "members" of the island - incl. Trusted and coop - List onlineMembers = island.getMemberSet(RanksManager.COOP_RANK).stream() - .filter(uuid -> Util.getOnlinePlayerList(user).contains(Bukkit.getOfflinePlayer(uuid).getName())).toList(); - - for (int rank : ranks) { - Set players = island.getMemberSet(rank, false); - if (!players.isEmpty()) { - if (rank == RanksManager.OWNER_RANK) { - // Slightly special handling for the owner rank - user.sendMessage("commands.island.team.info.rank-layout.owner", - TextVariables.RANK, user.getTranslation(RanksManager.OWNER_RANK_REF)); - } else { - user.sendMessage("commands.island.team.info.rank-layout.generic", - TextVariables.RANK, user.getTranslation(getPlugin().getRanksManager().getRank(rank)), - TextVariables.NUMBER, String.valueOf(island.getMemberSet(rank, false).size())); - } - displayOnOffline(user, rank, island, onlineMembers); - } - } - } - - private void displayOnOffline(User user, int rank, Island island, List onlineMembers) { - for (UUID member : island.getMemberSet(rank, false)) { - OfflinePlayer offlineMember = Bukkit.getOfflinePlayer(member); - if (onlineMembers.contains(member)) { - // the player is online - user.sendMessage("commands.island.team.info.member-layout.online", - TextVariables.NAME, offlineMember.getName()); - } else { - // A bit of handling for the last joined date - Instant lastJoined = Instant.ofEpochMilli(offlineMember.getLastPlayed()); - Instant now = Instant.now(); - - Duration duration = Duration.between(lastJoined, now); - String lastSeen; - final String reference = "commands.island.team.info.last-seen.layout"; - if (duration.toMinutes() < 60L) { - lastSeen = user.getTranslation(reference, - TextVariables.NUMBER, String.valueOf(duration.toMinutes()), - TextVariables.UNIT, user.getTranslation("commands.island.team.info.last-seen.minutes")); - } else if (duration.toHours() < 24L) { - lastSeen = user.getTranslation(reference, - TextVariables.NUMBER, String.valueOf(duration.toHours()), - TextVariables.UNIT, user.getTranslation("commands.island.team.info.last-seen.hours")); - } else { - lastSeen = user.getTranslation(reference, - TextVariables.NUMBER, String.valueOf(duration.toDays()), - TextVariables.UNIT, user.getTranslation("commands.island.team.info.last-seen.days")); - } - - if(island.getMemberSet(RanksManager.MEMBER_RANK, true).contains(member)) { - user.sendMessage("commands.island.team.info.member-layout.offline", - TextVariables.NAME, offlineMember.getName(), - "[last_seen]", lastSeen); - } else { - // This will prevent anyone that is trusted or below to not have a last-seen status - user.sendMessage("commands.island.team.info.member-layout.offline-not-last-seen", - TextVariables.NAME, offlineMember.getName()); - } - } - } - - } - - private boolean fireEvent(User user, Island island) { - IslandBaseEvent e = TeamEvent.builder() - .island(island) - .reason(TeamEvent.Reason.INFO) - .involvedPlayer(user.getUniqueId()) - .build(); - return e.getNewEvent().map(IslandBaseEvent::isCancelled) - .orElse(e.isCancelled()); - } - - /** - * Add an invite - * @param type - type of invite - * @param inviter - uuid of inviter - * @param invitee - uuid of invitee - * @since 1.8.0 - */ - public void addInvite(Invite.Type type, @NonNull UUID inviter, @NonNull UUID invitee, @NonNull Island island) { - inviteMap.put(invitee, new Invite(type, inviter, invitee, island)); - } - - /** - * Check if a player has been invited - * @param invitee - UUID of invitee to check - * @return true if invited, false if not - * @since 1.8.0 - */ - public boolean isInvited(@NonNull UUID invitee) { - return inviteMap.containsKey(invitee); - } - - /** - * Get whoever invited invitee - * @param invitee - uuid - * @return UUID of inviter, or null if invitee has not been invited - * @since 1.8.0 - */ - @Nullable - public UUID getInviter(UUID invitee) { - return isInvited(invitee) ? inviteMap.get(invitee).getInviter() : null; - } - - /** - * Gets the invite for an invitee. - * @param invitee - UUID of invitee - * @return invite or null if none - * @since 1.8.0 - */ - @Nullable - public Invite getInvite(UUID invitee) { - return inviteMap.get(invitee); - } - - /** - * Removes a pending invite. - * @param invitee - UUID of invited user - * @since 1.8.0 - */ - public void removeInvite(@NonNull UUID invitee) { - inviteMap.remove(invitee); - } + /** + * Invited list. Key is the invited party, value is the invite. + * @since 1.8.0 + */ + private final Map inviteMap; + + public IslandTeamCommand(CompositeCommand parent) { + super(parent, "team"); + inviteMap = new HashMap<>(); + } + + @Override + public void setup() { + setPermission("island.team"); + setOnlyPlayer(true); + setDescription("commands.island.team.description"); + // Register commands + new IslandTeamInviteCommand(this); + new IslandTeamLeaveCommand(this); + new IslandTeamSetownerCommand(this); + new IslandTeamKickCommand(this); + new IslandTeamInviteAcceptCommand(this); + new IslandTeamInviteRejectCommand(this); + if (getPlugin().getRanksManager().rankExists(RanksManager.COOP_RANK_REF)) { + new IslandTeamCoopCommand(this); + new IslandTeamUncoopCommand(this); + } + if (getPlugin().getRanksManager().rankExists(RanksManager.TRUSTED_RANK_REF)) { + new IslandTeamTrustCommand(this); + new IslandTeamUntrustCommand(this); + } + new IslandTeamPromoteCommand(this, "promote"); + new IslandTeamPromoteCommand(this, "demote"); + } + + @Override + public boolean execute(User user, String label, List args) { + // Player issuing the command must have an island + Island island = getIslands().getPrimaryIsland(getWorld(), user.getUniqueId()); + if (island == null) { + user.sendMessage("general.errors.no-island"); + return false; + } + + UUID playerUUID = user.getUniqueId(); + // Fire event so add-ons can run commands, etc. + if (fireEvent(user, island)) { + // Cancelled + return false; + } + Set teamMembers = getMembers(getWorld(), user); + if (playerUUID.equals(island.getOwner())) { + int maxSize = getIslands().getMaxMembers(island, RanksManager.MEMBER_RANK); + if (teamMembers.size() < maxSize) { + user.sendMessage("commands.island.team.invite.you-can-invite", TextVariables.NUMBER, String.valueOf(maxSize - teamMembers.size())); + } else { + user.sendMessage("commands.island.team.invite.errors.island-is-full"); + } + } + // Show members of island + showMembers(island, user); + return true; + } + + private void showMembers(Island island, User user) { + // Gather online members + long count = island + .getMemberSet(RanksManager.MEMBER_RANK) + .stream() + .filter(uuid -> Util.getOnlinePlayerList(user).contains(Bukkit.getOfflinePlayer(uuid).getName())) + .count(); + + // List of ranks that we will loop through + Integer[] ranks = new Integer[]{RanksManager.OWNER_RANK, RanksManager.SUB_OWNER_RANK, RanksManager.MEMBER_RANK, RanksManager.TRUSTED_RANK, RanksManager.COOP_RANK}; + + // Show header: + user.sendMessage("commands.island.team.info.header", + "[max]", String.valueOf(getIslands().getMaxMembers(island, RanksManager.MEMBER_RANK)), + "[total]", String.valueOf(island.getMemberSet().size()), + "[online]", String.valueOf(count)); + + // We now need to get all online "members" of the island - incl. Trusted and coop + List onlineMembers = island.getMemberSet(RanksManager.COOP_RANK).stream() + .filter(uuid -> Util.getOnlinePlayerList(user).contains(Bukkit.getOfflinePlayer(uuid).getName())).toList(); + + for (int rank : ranks) { + Set players = island.getMemberSet(rank, false); + if (!players.isEmpty()) { + if (rank == RanksManager.OWNER_RANK) { + // Slightly special handling for the owner rank + user.sendMessage("commands.island.team.info.rank-layout.owner", + TextVariables.RANK, user.getTranslation(RanksManager.OWNER_RANK_REF)); + } else { + user.sendMessage("commands.island.team.info.rank-layout.generic", + TextVariables.RANK, user.getTranslation(getPlugin().getRanksManager().getRank(rank)), + TextVariables.NUMBER, String.valueOf(island.getMemberSet(rank, false).size())); + } + displayOnOffline(user, rank, island, onlineMembers); + } + } + } + + private void displayOnOffline(User user, int rank, Island island, List onlineMembers) { + for (UUID member : island.getMemberSet(rank, false)) { + OfflinePlayer offlineMember = Bukkit.getOfflinePlayer(member); + if (onlineMembers.contains(member)) { + // the player is online + user.sendMessage("commands.island.team.info.member-layout.online", + TextVariables.NAME, offlineMember.getName()); + } else { + // A bit of handling for the last joined date + Instant lastJoined = Instant.ofEpochMilli(offlineMember.getLastPlayed()); + Instant now = Instant.now(); + + Duration duration = Duration.between(lastJoined, now); + String lastSeen; + final String reference = "commands.island.team.info.last-seen.layout"; + if (duration.toMinutes() < 60L) { + lastSeen = user.getTranslation(reference, + TextVariables.NUMBER, String.valueOf(duration.toMinutes()), + TextVariables.UNIT, user.getTranslation("commands.island.team.info.last-seen.minutes")); + } else if (duration.toHours() < 24L) { + lastSeen = user.getTranslation(reference, + TextVariables.NUMBER, String.valueOf(duration.toHours()), + TextVariables.UNIT, user.getTranslation("commands.island.team.info.last-seen.hours")); + } else { + lastSeen = user.getTranslation(reference, + TextVariables.NUMBER, String.valueOf(duration.toDays()), + TextVariables.UNIT, user.getTranslation("commands.island.team.info.last-seen.days")); + } + + if(island.getMemberSet(RanksManager.MEMBER_RANK, true).contains(member)) { + user.sendMessage("commands.island.team.info.member-layout.offline", + TextVariables.NAME, offlineMember.getName(), + "[last_seen]", lastSeen); + } else { + // This will prevent anyone that is trusted or below to not have a last-seen status + user.sendMessage("commands.island.team.info.member-layout.offline-not-last-seen", + TextVariables.NAME, offlineMember.getName()); + } + } + } + + } + + private boolean fireEvent(User user, Island island) { + IslandBaseEvent e = TeamEvent.builder() + .island(island) + .reason(TeamEvent.Reason.INFO) + .involvedPlayer(user.getUniqueId()) + .build(); + return e.getNewEvent().map(IslandBaseEvent::isCancelled) + .orElse(e.isCancelled()); + } + + /** + * Add an invite + * @param type - type of invite + * @param inviter - uuid of inviter + * @param invitee - uuid of invitee + * @since 1.8.0 + */ + public void addInvite(Invite.Type type, @NonNull UUID inviter, @NonNull UUID invitee, @NonNull Island island) { + inviteMap.put(invitee, new Invite(type, inviter, invitee, island)); + } + + /** + * Check if a player has been invited + * @param invitee - UUID of invitee to check + * @return true if invited, false if not + * @since 1.8.0 + */ + public boolean isInvited(@NonNull UUID invitee) { + return inviteMap.containsKey(invitee); + } + + /** + * Get whoever invited invitee + * @param invitee - uuid + * @return UUID of inviter, or null if invitee has not been invited + * @since 1.8.0 + */ + @Nullable + public UUID getInviter(UUID invitee) { + return isInvited(invitee) ? inviteMap.get(invitee).getInviter() : null; + } + + /** + * Gets the invite for an invitee. + * @param invitee - UUID of invitee + * @return invite or null if none + * @since 1.8.0 + */ + @Nullable + public Invite getInvite(UUID invitee) { + return inviteMap.get(invitee); + } + + /** + * Removes a pending invite. + * @param invitee - UUID of invited user + * @since 1.8.0 + */ + public void removeInvite(@NonNull UUID invitee) { + inviteMap.remove(invitee); + } } diff --git a/src/main/java/world/bentobox/bentobox/commands/BentoBoxCommand.java b/src/main/java/world/bentobox/bentobox/commands/BentoBoxCommand.java index 9662a88ee..e4c8e637d 100644 --- a/src/main/java/world/bentobox/bentobox/commands/BentoBoxCommand.java +++ b/src/main/java/world/bentobox/bentobox/commands/BentoBoxCommand.java @@ -25,6 +25,7 @@ public void setup() { new BentoBoxLocaleCommand(this); new BentoBoxHelpCommand(this); new BentoBoxPermsCommand(this); + new BentoBoxRankCommand(this); // Database names with a 2 in them are migration databases if (getPlugin().getSettings().getDatabaseType().name().contains("2")) { new BentoBoxMigrateCommand(this); diff --git a/src/main/java/world/bentobox/bentobox/commands/BentoBoxRankCommand.java b/src/main/java/world/bentobox/bentobox/commands/BentoBoxRankCommand.java new file mode 100644 index 000000000..a6113dcae --- /dev/null +++ b/src/main/java/world/bentobox/bentobox/commands/BentoBoxRankCommand.java @@ -0,0 +1,141 @@ +package world.bentobox.bentobox.commands; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import world.bentobox.bentobox.api.commands.CompositeCommand; +import world.bentobox.bentobox.api.localization.TextVariables; +import world.bentobox.bentobox.api.user.User; +import world.bentobox.bentobox.managers.RanksManager; + +/** + * Manages ranks + * + * @author tastybento + * @since 2.0.0 + */ +public class BentoBoxRankCommand extends CompositeCommand { + + private int rankValue; + private String firstElement; + private final RanksManager rm; + + /** + * Rank management. Add and remove + * @param parent command parent + */ + public BentoBoxRankCommand(CompositeCommand parent) { + super(parent, "rank"); + rm = getPlugin().getRanksManager(); + } + + @Override + public void setup() { + setPermission("bentobox.admin.rank"); + setDescription("commands.bentobox.rank.description"); + this.setParametersHelp("commands.bentobox.rank.parameters"); + } + + @Override + public boolean canExecute(User user, String label, List args) { + + if (args.isEmpty()) { + // Show help + showHelp(this, user); + return false; + } + // Check if the first element is "add" or "remove" or "list" + firstElement = args.get(0); + if (!("list".equals(firstElement) || "add".equals(firstElement) || "remove".equals(firstElement))) { + // Show help + showHelp(this, user); + return false; + } + + if ("remove".equals(firstElement) && args.size() != 2) { + // Show help + showHelp(this, user); + return false; + } + + // If the first element is "add", then check if the third element is an integer + if ("add".equals(firstElement)) { + // Check if there is a third element + if (args.size() < 3) { + // Show help + showHelp(this, user); + return false; + } + + // Check if the third element is an integer + String thirdElement = args.get(2); + try { + rankValue = Integer.parseInt(thirdElement); + } catch (NumberFormatException e) { + // Show help + showHelp(this, user); + return false; + } + } + + // If all checks passed, return true + return true; + } + + @Override + public boolean execute(User user, String label, List args) { + + if ("list".equals(firstElement)) { + showRanks(user); + return true; + } + if ("add".equals(firstElement)) { + if (rm.addRank(args.get(1), rankValue)) { + user.sendMessage("commands.bentobox.rank.add.success", "[rank]", args.get(1), TextVariables.NUMBER, String.valueOf(rankValue)); + showRanks(user); + } else { + user.sendMessage("commands.bentobox.rank.add.failure", "[rank]", args.get(1), TextVariables.NUMBER, String.valueOf(rankValue)); + return false; + } + } else { + if (rm.removeRank(args.get(1))) { + user.sendMessage("commands.bentobox.rank.remove.success", "[rank]", args.get(1)); + showRanks(user); + } else { + user.sendMessage("commands.bentobox.rank.remove.failure", "[rank]", args.get(1)); + return false; + } + } + return true; + } + + private void showRanks(User user) { + user.sendMessage("commands.bentobox.rank.list"); + rm.getRanks().forEach((ref, rank) -> { + user.sendRawMessage(user.getTranslation(ref) + ": " + ref + " " + String.valueOf(rank)); + }); + + } + + @Override + public Optional> tabComplete(User user, String alias, List args) { + if (args.size() <=1) { + return Optional.empty(); + } + firstElement = args.get(1); + if (args.size() <= 2) { + return Optional.of(List.of("add","remove","list")); + } + if (args.size() > 1 && "add".equals(firstElement)) { + List options = new ArrayList<>(RanksManager.DEFAULT_RANKS.keySet()); + options.removeIf(rm.getRanks().keySet()::contains); + return Optional.of(options); + } + if (args.size() > 1 && "remove".equals(firstElement)) { + return Optional.of(new ArrayList<>(rm.getRanks().keySet())); + } + return Optional.empty(); + + } +} diff --git a/src/main/java/world/bentobox/bentobox/database/objects/Ranks.java b/src/main/java/world/bentobox/bentobox/database/objects/Ranks.java new file mode 100644 index 000000000..f6172b579 --- /dev/null +++ b/src/main/java/world/bentobox/bentobox/database/objects/Ranks.java @@ -0,0 +1,45 @@ +package world.bentobox.bentobox.database.objects; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +import com.google.gson.annotations.Expose; + +/** + * Stores data on ranks + */ +@Table(name = "Ranks") +public class Ranks implements DataObject { + + public static final String ID = "BentoBox-Ranks"; + + public Ranks(Map rankReference) { + super(); + this.rankReference = rankReference; + } + + @Expose + private Map rankReference; + + @Override + public String getUniqueId() { + return ID; + } + + @Override + public void setUniqueId(String uniqueId) { + // Nothing to do + } + + public Map getRankReference() { + return Objects.requireNonNullElse(rankReference, new LinkedHashMap<>()); + } + + public void setRankReference(Map rankReference) { + this.rankReference = rankReference; + } + + + +} diff --git a/src/main/java/world/bentobox/bentobox/managers/RanksManager.java b/src/main/java/world/bentobox/bentobox/managers/RanksManager.java index a679b0bed..99cb5d1b1 100644 --- a/src/main/java/world/bentobox/bentobox/managers/RanksManager.java +++ b/src/main/java/world/bentobox/bentobox/managers/RanksManager.java @@ -3,8 +3,15 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; import java.util.stream.Collectors; +import org.eclipse.jdt.annotation.NonNull; + +import world.bentobox.bentobox.BentoBox; +import world.bentobox.bentobox.database.Database; +import world.bentobox.bentobox.database.objects.Ranks; + /** * Ranks Manager * Handles ranks and holds constants for various island ranks @@ -13,149 +20,155 @@ */ public class RanksManager { - // Constants that define the hard coded rank values - public static final String ADMIN_RANK_REF = "ranks.admin"; - public static final String MOD_RANK_REF = "ranks.mod"; - public static final String OWNER_RANK_REF = "ranks.owner"; - public static final String SUB_OWNER_RANK_REF = "ranks.sub-owner"; - public static final String MEMBER_RANK_REF = "ranks.member"; - public static final String TRUSTED_RANK_REF = "ranks.trusted"; - public static final String COOP_RANK_REF = "ranks.coop"; - public static final String VISITOR_RANK_REF = "ranks.visitor"; - public static final String BANNED_RANK_REF = "ranks.banned"; - public static final int ADMIN_RANK = 10000; - public static final int MOD_RANK = 5000; - public static final int OWNER_RANK = 1000; - public static final int SUB_OWNER_RANK = 900; - public static final int MEMBER_RANK = 500; - public static final int TRUSTED_RANK = 400; - public static final int COOP_RANK = 200; - public static final int VISITOR_RANK = 0; - public static final int BANNED_RANK = -1; - - // The store of ranks - private LinkedHashMap ranks = new LinkedHashMap<>(); - - public RanksManager() { - // Hard coded ranks - ranksPut(ADMIN_RANK_REF, ADMIN_RANK); - ranksPut(MOD_RANK_REF, MOD_RANK); - ranksPut(OWNER_RANK_REF, OWNER_RANK); - ranksPut(SUB_OWNER_RANK_REF, SUB_OWNER_RANK); - ranksPut(MEMBER_RANK_REF, MEMBER_RANK); - ranksPut(TRUSTED_RANK_REF, TRUSTED_RANK); - ranksPut(COOP_RANK_REF, COOP_RANK); - ranksPut(VISITOR_RANK_REF, VISITOR_RANK); - ranksPut(BANNED_RANK_REF, BANNED_RANK); - } - - /** - * Try to add a new rank. Owner, member, visitor and banned ranks cannot be changed. - * @param reference - a reference that can be found in a locale file - * @param value - the rank value - * @return true if the rank was successfully added - */ - public boolean addRank(String reference, int value) { - if (reference.equalsIgnoreCase(OWNER_RANK_REF) - || reference.equalsIgnoreCase(SUB_OWNER_RANK_REF) - || reference.equalsIgnoreCase(TRUSTED_RANK_REF) - || reference.equalsIgnoreCase(COOP_RANK_REF) - || reference.equalsIgnoreCase(MEMBER_RANK_REF) - || reference.equalsIgnoreCase(VISITOR_RANK_REF) - || reference.equalsIgnoreCase(BANNED_RANK_REF) - || reference.equalsIgnoreCase(ADMIN_RANK_REF) - || reference.equalsIgnoreCase(MOD_RANK_REF)) { - return false; - } - ranksPut(reference, value); - - return true; - } - - private void ranksPut(String reference, int value) { - ranks.put(reference, value); - // Sort - ranks = ranks.entrySet().stream() - .sorted(Map.Entry.comparingByValue()) - .collect(Collectors.toMap( - Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); - } - - /** - * Try to remove a rank. Owner, member, visitor and banned ranks cannot be removed. - * @param reference - a reference that can be found in a locale file - * @return true if removed - */ - public boolean removeRank(String reference) { - return !reference.equalsIgnoreCase(OWNER_RANK_REF) - && !reference.equalsIgnoreCase(SUB_OWNER_RANK_REF) - && !reference.equalsIgnoreCase(TRUSTED_RANK_REF) - && !reference.equalsIgnoreCase(COOP_RANK_REF) - && !reference.equalsIgnoreCase(MEMBER_RANK_REF) - && !reference.equalsIgnoreCase(VISITOR_RANK_REF) - && !reference.equalsIgnoreCase(BANNED_RANK_REF) - && !reference.equalsIgnoreCase(ADMIN_RANK_REF) - && !reference.equalsIgnoreCase(MOD_RANK_REF) && (ranks.remove(reference) != null); - - } - - /** - * Get the rank value for this reference - * @param reference - locale reference to the name of this rank - * @return rank value or zero if this is an unknown rank - */ - public int getRankValue(String reference) { - return ranks.getOrDefault(reference, VISITOR_RANK); - } - - /** - * Get the ranks. Ranks are listed in ascending order - * @return immutable map of ranks - */ - public Map getRanks() { - return new LinkedHashMap<>(ranks); - } - - - /** - * Gets the next rank value above the current rank. Highest is {@link RanksManager#OWNER_RANK} - * @param currentRank - current rank value - * @return Optional rank value - */ - public int getRankUpValue(int currentRank) { - return getRanks().values().stream().mapToInt(x -> { - if (x > currentRank) { - return x; - } - return OWNER_RANK; - }).min().orElse(currentRank); - } - - /** - * Gets the previous rank value below the current rank. Lowest is {@link RanksManager#VISITOR_RANK} - * @param currentRank - current rank value - * @return Optional rank value - */ - public int getRankDownValue(int currentRank) { - return getRanks().values().stream().mapToInt(x -> { - if (x < currentRank) { - return x; - } - return VISITOR_RANK; - }).max().orElse(currentRank); - } - - /** - * Gets the reference to the rank name for value - * @param rank - value - * @return Reference - */ - public String getRank(int rank) { - for (Entry en : ranks.entrySet()) { - if (rank == en.getValue()) { - return en.getKey(); - } - } - return ""; - } + // Constants that define the hard coded rank values + public static final String ADMIN_RANK_REF = "ranks.admin"; + public static final String MOD_RANK_REF = "ranks.mod"; + public static final String OWNER_RANK_REF = "ranks.owner"; + public static final String SUB_OWNER_RANK_REF = "ranks.sub-owner"; + public static final String MEMBER_RANK_REF = "ranks.member"; + public static final String TRUSTED_RANK_REF = "ranks.trusted"; + public static final String COOP_RANK_REF = "ranks.coop"; + public static final String VISITOR_RANK_REF = "ranks.visitor"; + public static final String BANNED_RANK_REF = "ranks.banned"; + public static final int ADMIN_RANK = 10000; + public static final int MOD_RANK = 5000; + public static final int OWNER_RANK = 1000; + public static final int SUB_OWNER_RANK = 900; + public static final int MEMBER_RANK = 500; + public static final int TRUSTED_RANK = 400; + public static final int COOP_RANK = 200; + public static final int VISITOR_RANK = 0; + public static final int BANNED_RANK = -1; + + // The store of ranks + private LinkedHashMap ranks = new LinkedHashMap<>(); + public static final Map DEFAULT_RANKS = Map.of(ADMIN_RANK_REF, ADMIN_RANK, + MOD_RANK_REF, MOD_RANK, + OWNER_RANK_REF, OWNER_RANK, + SUB_OWNER_RANK_REF, SUB_OWNER_RANK, + MEMBER_RANK_REF, MEMBER_RANK, + TRUSTED_RANK_REF, TRUSTED_RANK, + COOP_RANK_REF, COOP_RANK, + VISITOR_RANK_REF, VISITOR_RANK, + BANNED_RANK_REF, BANNED_RANK); + + @NonNull + private Database handler; + + public RanksManager() { + // Set up the database handler to store and retrieve Island classes + handler = new Database<>(BentoBox.getInstance(), Ranks.class); + if (!handler.objectExists(Ranks.ID)) { + // Make the initial object + DEFAULT_RANKS.forEach((ref, rank) -> ranksPut(ref, rank)); + handler.saveObject(new Ranks(ranks)); + } else { + // Load the ranks from the database + Objects.requireNonNull(handler.loadObject(Ranks.ID)).getRankReference().forEach(this::ranksPut); + } + + } + + /** + * Check if a rank exists + * @param reference YAML reference to rank, e.g., ranks.trusted + * @return true if the rank exists + */ + public boolean rankExists(String reference) { + return ranks.containsKey(reference); + } + + /** + * Try to add a new rank. Owner, member, visitor and banned ranks cannot be changed. + * @param reference - a reference that can be found in a locale file + * @param value - the rank value + * @return true if the rank was successfully added + */ + public boolean addRank(String reference, int value) { + if (rankExists(reference)) { + return false; + } + ranksPut(reference, value); + + return true; + } + + private void ranksPut(String reference, int value) { + ranks.put(reference, value); + // Sort + ranks = ranks.entrySet().stream() + .sorted(Map.Entry.comparingByValue()) + .collect(Collectors.toMap( + Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); + } + + /** + * Try to remove a rank. Owner, member, visitor and banned ranks cannot be removed. + * @param reference - a reference that can be found in a locale file + * @return true if removed + */ + public boolean removeRank(String reference) { + return ranks.remove(reference) != null; + + } + + /** + * Get the rank value for this reference + * @param reference - locale reference to the name of this rank + * @return rank value or zero if this is an unknown rank + */ + public int getRankValue(String reference) { + return ranks.getOrDefault(reference, VISITOR_RANK); + } + + /** + * Get the ranks. Ranks are listed in ascending order + * @return immutable map of ranks + */ + public Map getRanks() { + return new LinkedHashMap<>(ranks); + } + + + /** + * Gets the next rank value above the current rank. Highest is {@link RanksManager#OWNER_RANK} + * @param currentRank - current rank value + * @return Optional rank value + */ + public int getRankUpValue(int currentRank) { + return getRanks().values().stream().mapToInt(x -> { + if (x > currentRank) { + return x; + } + return OWNER_RANK; + }).min().orElse(currentRank); + } + + /** + * Gets the previous rank value below the current rank. Lowest is {@link RanksManager#VISITOR_RANK} + * @param currentRank - current rank value + * @return Optional rank value + */ + public int getRankDownValue(int currentRank) { + return getRanks().values().stream().mapToInt(x -> { + if (x < currentRank) { + return x; + } + return VISITOR_RANK; + }).max().orElse(currentRank); + } + + /** + * Gets the reference to the rank name for value + * @param rank - value + * @return Reference + */ + public String getRank(int rank) { + for (Entry en : ranks.entrySet()) { + if (rank == en.getValue()) { + return en.getKey(); + } + } + return ""; + } } diff --git a/src/main/resources/locales/en-US.yml b/src/main/resources/locales/en-US.yml index ee4314bc7..b129e5162 100644 --- a/src/main/resources/locales/en-US.yml +++ b/src/main/resources/locales/en-US.yml @@ -498,7 +498,16 @@ commands: addons: '[prefix_bentobox]&6 Migrating addons' class: '[prefix_bentobox]&6 Migrating [description]' migrated: '[prefix_bentobox]&a Migrated' - + rank: + description: 'list, add, or remove ranks' + parameters: '&a [list | add | remove] [rank reference] [rank value]' + add: + success: '&a Added [rank] with value [number]' + failure: '&c Failed to add [rank] with value [number]. Maybe a duplicate?' + remove: + success: '&a Removed [rank]' + failure: '&c Failed to remove [rank]. Unknown rank.' + list: '&a Registered ranks are as follows:' confirmation: confirm: '&c Type command again within &b [seconds]s&c to confirm.' previous-request-cancelled: '&6 Previous confirmation request cancelled.' diff --git a/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminInfoCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminInfoCommandTest.java index c9abe12c9..21e2eea69 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminInfoCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminInfoCommandTest.java @@ -23,7 +23,6 @@ import org.bukkit.entity.Player; import org.bukkit.util.Vector; import org.eclipse.jdt.annotation.NonNull; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -33,7 +32,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.api.commands.CompositeCommand; @@ -46,6 +44,7 @@ import world.bentobox.bentobox.managers.PlaceholdersManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; import world.bentobox.bentobox.util.Util; /** @@ -54,205 +53,196 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, Util.class}) -public class AdminInfoCommandTest { - - @Mock - private CompositeCommand ic; - @Mock - private User user; - @Mock - private IslandsManager im; - @Mock - private PlayersManager pm; - - private Island island; - - private AdminInfoCommand iic; - - @Mock - private Player player; - @Mock - private World world; - @Mock - private PlaceholdersManager phm; - @Mock - private @NonNull Location location; - @Mock - private IslandWorldManager iwm; - - /** - */ - @Before - public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); - - // IWM - when(plugin.getIWM()).thenReturn(iwm); - when(plugin.getRanksManager()).thenReturn(new RanksManager()); - - // Bukkit - PowerMockito.mockStatic(Bukkit.class, Mockito.RETURNS_MOCKS); - // Command manager - CommandsManager cm = mock(CommandsManager.class); - when(plugin.getCommandsManager()).thenReturn(cm); - - // Player - when(player.isOp()).thenReturn(false); - UUID uuid = UUID.randomUUID(); - when(user.getUniqueId()).thenReturn(uuid); - when(user.getName()).thenReturn("tastybento"); - when(user.getWorld()).thenReturn(world); - when(user.getPlayer()).thenReturn(player); - when(user.isPlayer()).thenReturn(true); - //user = User.getInstance(player); - // Set the User class plugin as this one - User.setPlugin(plugin); - - // Locales - LocalesManager lm = mock(LocalesManager.class); - when(lm.get(any(), any())).thenAnswer((Answer) invocation -> invocation.getArgument(1, String.class)); - when(plugin.getLocalesManager()).thenReturn(lm); - // Return the same string - when(phm.replacePlaceholders(any(), anyString())).thenAnswer((Answer) invocation -> invocation.getArgument(1, String.class)); - when(plugin.getPlaceholdersManager()).thenReturn(phm); - // Translate - when(user.getTranslation(anyString())).thenAnswer((Answer) invocation -> invocation.getArgument(0, String.class)); - when(user.getTranslation(anyString(), anyString(), anyString())).thenAnswer((Answer) invocation -> invocation.getArgument(0, String.class)); - - // Island manager - island = new Island(location, uuid, 100); - island.setRange(400); - when(location.toVector()).thenReturn(new Vector(1,2,3)); - when(plugin.getIslands()).thenReturn(im); - Optional optionalIsland = Optional.of(island); - when(im.getIslandAt(any())).thenReturn(optionalIsland); - when(im.getIsland(any(), any(UUID.class))).thenReturn(island); - - // Players manager - when(plugin.getPlayers()).thenReturn(pm); - when(pm.getUUID(any())).thenReturn(uuid); - - - // Command - iic = new AdminInfoCommand(ic); - } - - /** - */ - @After - public void tearDown() { - User.clearUsers(); - Mockito.framework().clearInlineMocks(); - } - - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#setup()}. - */ - @Test - public void testSetup() { - assertEquals("mod.info", iic.getPermission()); - assertFalse(iic.isOnlyPlayer()); - assertEquals("commands.admin.info.parameters", iic.getParameters()); - assertEquals("commands.admin.info.description", iic.getDescription()); - } - - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. - */ - @Test - public void testExecuteUserStringListOfStringTooManyArgs() { - assertFalse(iic.execute(user, "", Arrays.asList("hdhh", "hdhdhd"))); - verify(user).sendMessage("commands.help.header", "[label]", "commands.help.console"); - } - - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. - */ - @Test - public void testExecuteUserStringListOfStringNoArgsConsole() { - CommandSender console = mock(CommandSender.class); - User sender = User.getInstance(console); - assertFalse(iic.execute(sender, "", Collections.emptyList())); - verify(user, never()).sendMessage("commands.help.header", "[label]", "commands.help.console"); - } - - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. - */ - @Test - public void testExecuteUserStringListOfStringNoArgsNoIsland() { - when(im.getIslandAt(any())).thenReturn(Optional.empty()); - assertTrue(iic.execute(user, "", Collections.emptyList())); - verify(user).sendMessage("commands.admin.info.no-island"); - } - - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. - */ - @Test - public void testExecuteUserStringListOfStringNoArgsSuccess() { - assertTrue(iic.execute(user, "", Collections.emptyList())); - verify(user).sendMessage("commands.admin.info.title"); - verify(user).sendMessage(eq("commands.admin.info.island-uuid"), eq("[uuid]"), any()); - verify(user).sendMessage(eq("commands.admin.info.owner"), eq("[owner]"), eq(null), eq("[uuid]"), any()); - verify(user).sendMessage(eq("commands.admin.info.last-login"), eq("[date]"), any()); - verify(user).sendMessage("commands.admin.info.deaths", "[number]", "0"); - verify(user).sendMessage("commands.admin.info.resets-left", "[number]", "0", "[total]", "0"); - verify(user).sendMessage("commands.admin.info.team-members-title"); - verify(user).sendMessage("commands.admin.info.team-owner-format", "[name]", null, "[rank]", "ranks.owner"); - verify(user).sendMessage("commands.admin.info.island-protection-center", "[xyz]", "0,0,0"); - verify(user).sendMessage("commands.admin.info.island-center", "[xyz]", "0,0,0"); - verify(user).sendMessage("commands.admin.info.island-coords", "[xz1]", "-400,0,-400", "[xz2]", "400,0,400"); - verify(user).sendMessage("commands.admin.info.protection-range", "[range]", "100"); - verify(user).sendMessage("commands.admin.info.max-protection-range", "[range]", "100"); - verify(user).sendMessage("commands.admin.info.protection-coords", "[xz1]", "-100,0,-100", "[xz2]", "99,0,99"); - } - - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. - */ - @Test - public void testExecuteUserStringListOfStringArgsSuccess() { - assertTrue(iic.execute(user, "", Collections.singletonList("tastybento"))); - verify(user).sendMessage("commands.admin.info.title"); - verify(user).sendMessage(eq("commands.admin.info.island-uuid"), eq("[uuid]"), any()); - verify(user).sendMessage(eq("commands.admin.info.owner"), eq("[owner]"), eq(null), eq("[uuid]"), any()); - verify(user).sendMessage(eq("commands.admin.info.last-login"), eq("[date]"), any()); - verify(user).sendMessage("commands.admin.info.deaths", "[number]", "0"); - verify(user).sendMessage("commands.admin.info.resets-left", "[number]", "0", "[total]", "0"); - verify(user).sendMessage("commands.admin.info.team-members-title"); - verify(user).sendMessage("commands.admin.info.team-owner-format", "[name]", null, "[rank]", "ranks.owner"); - verify(user).sendMessage("commands.admin.info.island-protection-center", "[xyz]", "0,0,0"); - verify(user).sendMessage("commands.admin.info.island-center", "[xyz]", "0,0,0"); - verify(user).sendMessage("commands.admin.info.island-coords", "[xz1]", "-400,0,-400", "[xz2]", "400,0,400"); - verify(user).sendMessage("commands.admin.info.protection-range", "[range]", "100"); - verify(user).sendMessage("commands.admin.info.max-protection-range", "[range]", "100"); - verify(user).sendMessage("commands.admin.info.protection-coords", "[xz1]", "-100,0,-100", "[xz2]", "99,0,99"); - - } - - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. - */ - @Test - public void testExecuteUserStringListOfStringArgsNoIsland() { - when(im.getIsland(any(), any(UUID.class))).thenReturn(null); - assertFalse(iic.execute(user, "", Collections.singletonList("tastybento"))); - verify(user).sendMessage("general.errors.player-has-no-island"); - } - - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. - */ - @Test - public void testExecuteUserStringListOfStringArgsUnknownPlayer() { - PowerMockito.mockStatic(Util.class); - when(Util.getUUID(any())).thenReturn(null); - assertFalse(iic.execute(user, "", Collections.singletonList("tastybento"))); - verify(user).sendMessage("general.errors.unknown-player", "[name]", "tastybento"); - - } +public class AdminInfoCommandTest extends RanksManagerBeforeClassTest { + + @Mock + private CompositeCommand ic; + @Mock + private User user; + @Mock + private IslandsManager im; + @Mock + private PlayersManager pm; + + private Island island; + + private AdminInfoCommand iic; + + @Mock + private Player player; + @Mock + private World world; + @Mock + private PlaceholdersManager phm; + @Mock + private @NonNull Location location; + @Mock + private IslandWorldManager iwm; + + /** + */ + @Before + public void setUp() throws Exception { + super.setUp(); + + // IWM + when(plugin.getIWM()).thenReturn(iwm); + RanksManager rm = new RanksManager(); + when(plugin.getRanksManager()).thenReturn(rm); + + // Bukkit + PowerMockito.mockStatic(Bukkit.class, Mockito.RETURNS_MOCKS); + // Command manager + CommandsManager cm = mock(CommandsManager.class); + when(plugin.getCommandsManager()).thenReturn(cm); + + // Player + when(player.isOp()).thenReturn(false); + UUID uuid = UUID.randomUUID(); + when(user.getUniqueId()).thenReturn(uuid); + when(user.getName()).thenReturn("tastybento"); + when(user.getWorld()).thenReturn(world); + when(user.getPlayer()).thenReturn(player); + when(user.isPlayer()).thenReturn(true); + //user = User.getInstance(player); + // Set the User class plugin as this one + User.setPlugin(plugin); + + // Locales + LocalesManager lm = mock(LocalesManager.class); + when(lm.get(any(), any())).thenAnswer((Answer) invocation -> invocation.getArgument(1, String.class)); + when(plugin.getLocalesManager()).thenReturn(lm); + // Return the same string + when(phm.replacePlaceholders(any(), anyString())).thenAnswer((Answer) invocation -> invocation.getArgument(1, String.class)); + when(plugin.getPlaceholdersManager()).thenReturn(phm); + // Translate + when(user.getTranslation(anyString())).thenAnswer((Answer) invocation -> invocation.getArgument(0, String.class)); + when(user.getTranslation(anyString(), anyString(), anyString())).thenAnswer((Answer) invocation -> invocation.getArgument(0, String.class)); + + // Island manager + island = new Island(location, uuid, 100); + island.setRange(400); + when(location.toVector()).thenReturn(new Vector(1,2,3)); + when(plugin.getIslands()).thenReturn(im); + Optional optionalIsland = Optional.of(island); + when(im.getIslandAt(any())).thenReturn(optionalIsland); + when(im.getIsland(any(), any(UUID.class))).thenReturn(island); + + // Players manager + when(plugin.getPlayers()).thenReturn(pm); + when(pm.getUUID(any())).thenReturn(uuid); + + + // Command + iic = new AdminInfoCommand(ic); + } + + /** + * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#setup()}. + */ + @Test + public void testSetup() { + assertEquals("mod.info", iic.getPermission()); + assertFalse(iic.isOnlyPlayer()); + assertEquals("commands.admin.info.parameters", iic.getParameters()); + assertEquals("commands.admin.info.description", iic.getDescription()); + } + + /** + * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. + */ + @Test + public void testExecuteUserStringListOfStringTooManyArgs() { + assertFalse(iic.execute(user, "", Arrays.asList("hdhh", "hdhdhd"))); + verify(user).sendMessage("commands.help.header", "[label]", "commands.help.console"); + } + + /** + * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. + */ + @Test + public void testExecuteUserStringListOfStringNoArgsConsole() { + CommandSender console = mock(CommandSender.class); + User sender = User.getInstance(console); + assertFalse(iic.execute(sender, "", Collections.emptyList())); + verify(user, never()).sendMessage("commands.help.header", "[label]", "commands.help.console"); + } + + /** + * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. + */ + @Test + public void testExecuteUserStringListOfStringNoArgsNoIsland() { + when(im.getIslandAt(any())).thenReturn(Optional.empty()); + assertTrue(iic.execute(user, "", Collections.emptyList())); + verify(user).sendMessage("commands.admin.info.no-island"); + } + + /** + * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. + */ + @Test + public void testExecuteUserStringListOfStringNoArgsSuccess() { + assertTrue(iic.execute(user, "", Collections.emptyList())); + verify(user).sendMessage("commands.admin.info.title"); + verify(user).sendMessage(eq("commands.admin.info.island-uuid"), eq("[uuid]"), any()); + verify(user).sendMessage(eq("commands.admin.info.owner"), eq("[owner]"), eq(null), eq("[uuid]"), any()); + verify(user).sendMessage(eq("commands.admin.info.last-login"), eq("[date]"), any()); + verify(user).sendMessage("commands.admin.info.deaths", "[number]", "0"); + verify(user).sendMessage("commands.admin.info.resets-left", "[number]", "0", "[total]", "0"); + verify(user).sendMessage("commands.admin.info.team-members-title"); + verify(user).sendMessage("commands.admin.info.team-owner-format", "[name]", null, "[rank]", "ranks.owner"); + verify(user).sendMessage("commands.admin.info.island-protection-center", "[xyz]", "0,0,0"); + verify(user).sendMessage("commands.admin.info.island-center", "[xyz]", "0,0,0"); + verify(user).sendMessage("commands.admin.info.island-coords", "[xz1]", "-400,0,-400", "[xz2]", "400,0,400"); + verify(user).sendMessage("commands.admin.info.protection-range", "[range]", "100"); + verify(user).sendMessage("commands.admin.info.max-protection-range", "[range]", "100"); + verify(user).sendMessage("commands.admin.info.protection-coords", "[xz1]", "-100,0,-100", "[xz2]", "99,0,99"); + } + + /** + * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. + */ + @Test + public void testExecuteUserStringListOfStringArgsSuccess() { + assertTrue(iic.execute(user, "", Collections.singletonList("tastybento"))); + verify(user).sendMessage("commands.admin.info.title"); + verify(user).sendMessage(eq("commands.admin.info.island-uuid"), eq("[uuid]"), any()); + verify(user).sendMessage(eq("commands.admin.info.owner"), eq("[owner]"), eq(null), eq("[uuid]"), any()); + verify(user).sendMessage(eq("commands.admin.info.last-login"), eq("[date]"), any()); + verify(user).sendMessage("commands.admin.info.deaths", "[number]", "0"); + verify(user).sendMessage("commands.admin.info.resets-left", "[number]", "0", "[total]", "0"); + verify(user).sendMessage("commands.admin.info.team-members-title"); + verify(user).sendMessage("commands.admin.info.team-owner-format", "[name]", null, "[rank]", "ranks.owner"); + verify(user).sendMessage("commands.admin.info.island-protection-center", "[xyz]", "0,0,0"); + verify(user).sendMessage("commands.admin.info.island-center", "[xyz]", "0,0,0"); + verify(user).sendMessage("commands.admin.info.island-coords", "[xz1]", "-400,0,-400", "[xz2]", "400,0,400"); + verify(user).sendMessage("commands.admin.info.protection-range", "[range]", "100"); + verify(user).sendMessage("commands.admin.info.max-protection-range", "[range]", "100"); + verify(user).sendMessage("commands.admin.info.protection-coords", "[xz1]", "-100,0,-100", "[xz2]", "99,0,99"); + + } + + /** + * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. + */ + @Test + public void testExecuteUserStringListOfStringArgsNoIsland() { + when(im.getIsland(any(), any(UUID.class))).thenReturn(null); + assertFalse(iic.execute(user, "", Collections.singletonList("tastybento"))); + verify(user).sendMessage("general.errors.player-has-no-island"); + } + + /** + * Test method for {@link world.bentobox.bentobox.api.commands.island.AdminInfoCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. + */ + @Test + public void testExecuteUserStringListOfStringArgsUnknownPlayer() { + PowerMockito.mockStatic(Util.class); + when(Util.getUUID(any())).thenReturn(null); + assertFalse(iic.execute(user, "", Collections.singletonList("tastybento"))); + verify(user).sendMessage("general.errors.unknown-player", "[name]", "tastybento"); + + } } diff --git a/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminSetrankCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminSetrankCommandTest.java index 10a72c98b..29a797b60 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminSetrankCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminSetrankCommandTest.java @@ -19,17 +19,14 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.api.commands.CompositeCommand; @@ -38,6 +35,7 @@ import world.bentobox.bentobox.managers.IslandsManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; import world.bentobox.bentobox.util.Util; /** @@ -46,7 +44,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, Util.class}) -public class AdminSetrankCommandTest { +public class AdminSetrankCommandTest extends RanksManagerBeforeClassTest { @Mock private CompositeCommand ac; @@ -66,9 +64,7 @@ public class AdminSetrankCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); Util.setPlugin(plugin); // Ranks Manager @@ -104,14 +100,6 @@ public void setUp() throws Exception { when(Bukkit.getPluginManager()).thenReturn(pim); } - /** - */ - @After - public void tearDown() { - User.clearUsers(); - Mockito.framework().clearInlineMocks(); - } - /** * Test method for {@link world.bentobox.bentobox.api.commands.admin.AdminSetrankCommand#AdminSetrankCommand(world.bentobox.bentobox.api.commands.CompositeCommand)}. */ diff --git a/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminSettingsCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminSettingsCommandTest.java index 91a48aa26..e2eae1449 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminSettingsCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/admin/AdminSettingsCommandTest.java @@ -29,7 +29,6 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.PluginManager; import org.bukkit.scheduler.BukkitScheduler; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -39,7 +38,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.Settings; @@ -55,6 +53,7 @@ import world.bentobox.bentobox.managers.LocalesManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; import world.bentobox.bentobox.util.Util; /** @@ -63,7 +62,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class, Util.class}) -public class AdminSettingsCommandTest { +public class AdminSettingsCommandTest extends RanksManagerBeforeClassTest { private AdminSettingsCommand asc; @Mock @@ -96,9 +95,7 @@ public class AdminSettingsCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); Util.setPlugin(plugin); // Command manager @@ -177,7 +174,8 @@ public void setUp() throws Exception { when(plugin.getFlagsManager()).thenReturn(fm); // RnksManager - when(plugin.getRanksManager()).thenReturn(new RanksManager()); + RanksManager rm = new RanksManager(); + when(plugin.getRanksManager()).thenReturn(rm); @@ -185,15 +183,6 @@ public void setUp() throws Exception { } - /** - */ - @After - public void tearDown() throws Exception { - User.clearUsers(); - Mockito.framework().clearInlineMocks(); - - } - /** * Test method for {@link world.bentobox.bentobox.api.commands.admin.AdminSettingsCommand#setup()}. */ diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/DefaultPlayerCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/DefaultPlayerCommandTest.java index e1ee89ca1..9287406cb 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/DefaultPlayerCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/DefaultPlayerCommandTest.java @@ -15,7 +15,6 @@ import org.bukkit.Bukkit; import org.bukkit.World; import org.eclipse.jdt.annotation.Nullable; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -24,7 +23,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.api.addons.GameModeAddon; @@ -34,124 +32,125 @@ import world.bentobox.bentobox.database.objects.Island; import world.bentobox.bentobox.managers.CommandsManager; import world.bentobox.bentobox.managers.IslandsManager; +import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento * */ @RunWith(PowerMockRunner.class) -@PrepareForTest({Bukkit.class, BentoBox.class}) -public class DefaultPlayerCommandTest { - - @Mock - GameModeAddon addon; - private PlayerCommand dpc; - @Mock - private WorldSettings ws; - @Mock - private User user; - @Mock - private IslandsManager im; - @Mock - private @Nullable Island island; - - - class PlayerCommand extends DefaultPlayerCommand { - - protected PlayerCommand(GameModeAddon addon) { - super(addon); - } - - } - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); - - // Addon - - // User - when(user.getUniqueId()).thenReturn(UUID.randomUUID()); - // IM - when(plugin.getIslandsManager()).thenReturn(im); - when(plugin.getIslands()).thenReturn(im); - when(im.getIsland(any(World.class), any(UUID.class))).thenReturn(island); - - // Command manager - CommandsManager cm = mock(CommandsManager.class); - when(plugin.getCommandsManager()).thenReturn(cm); - - // World Settings - when(ws.getDefaultPlayerAction()).thenReturn("go"); - when(ws.getDefaultNewPlayerAction()).thenReturn("create"); - - PowerMockito.mockStatic(Bukkit.class, Mockito.RETURNS_MOCKS); - - when(ws.getPlayerCommandAliases()).thenReturn("island is"); - when(addon.getWorldSettings()).thenReturn(ws); - dpc = new PlayerCommand(addon); - dpc.setWorld(mock(World.class)); - - } - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - } - - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#DefaultPlayerCommand(world.bentobox.bentobox.api.addons.GameModeAddon)}. - */ - @Test - public void testDefaultPlayerCommand() { - assertNotNull(dpc); - } - - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#setup()}. - */ - @Test - public void testSetup() { - assertEquals("commands.island.help.description", dpc.getDescription()); - assertTrue(dpc.isOnlyPlayer()); - assertEquals("island", dpc.getPermission()); - // 20 = 19 subcommands + help command - assertEquals(20, dpc.getSubCommands().size()); // Update when commands are added or removed - } - - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. - */ - @Test - public void testExecuteUserStringListOfStringUnknownCommand() { - assertFalse(dpc.execute(user, "label", List.of("unknown"))); - verify(user).sendMessage("general.errors.unknown-command", TextVariables.LABEL, "island"); - } - - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. - */ - @Test - public void testExecuteUserStringListOfStringNullUser() { - assertFalse(dpc.execute(null, "label", List.of())); - } - /** - * Test method for {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. - */ - @Test - public void testExecuteUserStringListOfStringEmptyArgsHasIsland() { - assertFalse(dpc.execute(user, "label", List.of())); - verify(user).sendMessage("general.errors.use-in-game"); - } - - /** +@PrepareForTest({ Bukkit.class, BentoBox.class }) +public class DefaultPlayerCommandTest extends RanksManagerBeforeClassTest { + + @Mock + GameModeAddon addon; + private PlayerCommand dpc; + @Mock + private WorldSettings ws; + @Mock + private User user; + @Mock + private IslandsManager im; + @Mock + private @Nullable Island island; + + class PlayerCommand extends DefaultPlayerCommand { + + protected PlayerCommand(GameModeAddon addon) { + super(addon); + } + + } + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + super.setUp(); + // RanksManager + RanksManager rm = new RanksManager(); + when(plugin.getRanksManager()).thenReturn(rm); + + // Addon + + // User + when(user.getUniqueId()).thenReturn(UUID.randomUUID()); + // IM + when(plugin.getIslandsManager()).thenReturn(im); + when(plugin.getIslands()).thenReturn(im); + when(im.getIsland(any(World.class), any(UUID.class))).thenReturn(island); + + // Command manager + CommandsManager cm = mock(CommandsManager.class); + when(plugin.getCommandsManager()).thenReturn(cm); + + // World Settings + when(ws.getDefaultPlayerAction()).thenReturn("go"); + when(ws.getDefaultNewPlayerAction()).thenReturn("create"); + + PowerMockito.mockStatic(Bukkit.class, Mockito.RETURNS_MOCKS); + + when(ws.getPlayerCommandAliases()).thenReturn("island is"); + when(addon.getWorldSettings()).thenReturn(ws); + dpc = new PlayerCommand(addon); + dpc.setWorld(mock(World.class)); + + } + + /** + * Test method for + * {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#DefaultPlayerCommand(world.bentobox.bentobox.api.addons.GameModeAddon)}. + */ + @Test + public void testDefaultPlayerCommand() { + assertNotNull(dpc); + } + + /** + * Test method for + * {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#setup()}. + */ + @Test + public void testSetup() { + assertEquals("commands.island.help.description", dpc.getDescription()); + assertTrue(dpc.isOnlyPlayer()); + assertEquals("island", dpc.getPermission()); + // 20 = 19 subcommands + help command + assertEquals(20, dpc.getSubCommands().size()); // Update when commands are added or removed + } + + /** + * Test method for + * {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. + */ + @Test + public void testExecuteUserStringListOfStringUnknownCommand() { + assertFalse(dpc.execute(user, "label", List.of("unknown"))); + verify(user).sendMessage("general.errors.unknown-command", TextVariables.LABEL, "island"); + } + + /** + * Test method for + * {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. + */ + @Test + public void testExecuteUserStringListOfStringNullUser() { + assertFalse(dpc.execute(null, "label", List.of())); + } + + /** + * Test method for + * {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. + */ + @Test + public void testExecuteUserStringListOfStringEmptyArgsHasIsland() { + assertFalse(dpc.execute(user, "label", List.of())); + verify(user).sendMessage("general.errors.use-in-game"); + } + + /** * Test method for {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. */ @Test @@ -161,7 +160,7 @@ public void testExecuteUserStringListOfStringEmptyArgsHasNoIsland() { verify(user).sendMessage("general.errors.use-in-game"); } - /** + /** * Test method for {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. */ @Test @@ -172,7 +171,7 @@ public void testExecuteUserStringListOfStringEmptyArgsHasIslandUnknownCommand() verify(user).performCommand("label goxxx"); } - /** + /** * Test method for {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. */ @Test @@ -185,7 +184,7 @@ public void testExecuteUserStringListOfStringEmptyArgsHasNoIslandUnknownCommand( verify(user).performCommand("label createxxx"); } - /** + /** * Test method for {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. */ @Test @@ -196,7 +195,7 @@ public void testExecuteUserStringListOfStringEmptyArgsHasIslandUnknownCommandSla verify(user).performCommand("goxxx"); } - /** + /** * Test method for {@link world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand#execute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. */ @Test diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandBanCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandBanCommandTest.java index 00635da93..e336aab01 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandBanCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandBanCommandTest.java @@ -27,7 +27,6 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import org.bukkit.scheduler.BukkitScheduler; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -37,7 +36,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.Settings; @@ -53,6 +51,7 @@ import world.bentobox.bentobox.managers.PlaceholdersManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento @@ -60,7 +59,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class}) -public class IslandBanCommandTest { +public class IslandBanCommandTest extends RanksManagerBeforeClassTest { @Mock private CompositeCommand ic; @@ -83,9 +82,7 @@ public class IslandBanCommandTest { @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); User.setPlugin(plugin); // Command manager @@ -174,12 +171,6 @@ public void setUp() throws Exception { } - @After - public void tearDown() { - User.clearUsers(); - Mockito.framework().clearInlineMocks(); - } - /** * Test method for {@link world.bentobox.bentobox.api.commands.island.IslandBanCommand#execute(User, String, List)}. */ diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandBanlistCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandBanlistCommandTest.java index b30833585..a416f7772 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandBanlistCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandBanlistCommandTest.java @@ -21,17 +21,14 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitScheduler; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.Settings; @@ -44,6 +41,7 @@ import world.bentobox.bentobox.managers.IslandsManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento @@ -51,7 +49,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class }) -public class IslandBanlistCommandTest { +public class IslandBanlistCommandTest extends RanksManagerBeforeClassTest { @Mock private CompositeCommand ic; @@ -69,9 +67,7 @@ public class IslandBanlistCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); // Command manager CommandsManager cm = mock(CommandsManager.class); @@ -126,11 +122,6 @@ public void setUp() throws Exception { } - @After - public void tearDown() { - Mockito.framework().clearInlineMocks(); - } - /** * Test method for {@link IslandBanlistCommand#canExecute(User, String, java.util.List)}. */ diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandDeletehomeCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandDeletehomeCommandTest.java index 6e6382a8e..f6bda8d97 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandDeletehomeCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandDeletehomeCommandTest.java @@ -23,7 +23,6 @@ import org.bukkit.entity.Player; import org.eclipse.jdt.annotation.NonNull; import org.jetbrains.annotations.NotNull; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -32,7 +31,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.Settings; @@ -46,6 +44,7 @@ import world.bentobox.bentobox.managers.IslandsManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento @@ -53,7 +52,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class }) -public class IslandDeletehomeCommandTest { +public class IslandDeletehomeCommandTest extends RanksManagerBeforeClassTest { @Mock private CompositeCommand ic; @@ -79,9 +78,7 @@ public class IslandDeletehomeCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); // Command manager CommandsManager cm = mock(CommandsManager.class); @@ -147,15 +144,6 @@ public void setUp() throws Exception { idh = new IslandDeletehomeCommand(ic); } - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - User.clearUsers(); - Mockito.framework().clearInlineMocks(); - } - /** * Test method for {@link world.bentobox.bentobox.api.commands.island.IslandDeletehomeCommand#IslandDeletehomeCommand(world.bentobox.bentobox.api.commands.CompositeCommand)}. */ diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandExpelCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandExpelCommandTest.java index d1de24250..1c97d49c7 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandExpelCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandExpelCommandTest.java @@ -26,7 +26,6 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import org.bukkit.scheduler.BukkitScheduler; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -36,7 +35,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.Settings; @@ -53,6 +51,7 @@ import world.bentobox.bentobox.managers.PlaceholdersManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento @@ -60,7 +59,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class }) -public class IslandExpelCommandTest { +public class IslandExpelCommandTest extends RanksManagerBeforeClassTest { @Mock private CompositeCommand ic; @@ -88,9 +87,7 @@ public class IslandExpelCommandTest { @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); User.setPlugin(plugin); // Command manager @@ -166,14 +163,6 @@ public void setUp() throws Exception { iec = new IslandExpelCommand(ic); } - /** - */ - @After - public void tearDown() { - User.clearUsers(); - Mockito.framework().clearInlineMocks(); - } - /** * Test method for {@link world.bentobox.bentobox.api.commands.island.IslandExpelCommand#IslandExpelCommand(world.bentobox.bentobox.api.commands.CompositeCommand)}. */ diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandInfoCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandInfoCommandTest.java index e07422f17..a7a1b5ec9 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandInfoCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandInfoCommandTest.java @@ -23,7 +23,6 @@ import org.bukkit.entity.Player; import org.bukkit.util.Vector; import org.eclipse.jdt.annotation.NonNull; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -33,7 +32,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.api.commands.CompositeCommand; @@ -46,6 +44,7 @@ import world.bentobox.bentobox.managers.PlaceholdersManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; import world.bentobox.bentobox.util.Util; /** @@ -54,7 +53,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, Util.class}) -public class IslandInfoCommandTest { +public class IslandInfoCommandTest extends RanksManagerBeforeClassTest { @Mock private CompositeCommand ic; @@ -84,13 +83,12 @@ public class IslandInfoCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); // IWM when(plugin.getIWM()).thenReturn(iwm); - when(plugin.getRanksManager()).thenReturn(new RanksManager()); + RanksManager rm = new RanksManager(); + when(plugin.getRanksManager()).thenReturn(rm); // Bukkit PowerMockito.mockStatic(Bukkit.class, Mockito.RETURNS_MOCKS); @@ -139,14 +137,6 @@ public void setUp() throws Exception { iic = new IslandInfoCommand(ic); } - /** - */ - @After - public void tearDown() { - User.clearUsers(); - Mockito.framework().clearInlineMocks(); - } - /** * Test method for {@link world.bentobox.bentobox.api.commands.island.IslandInfoCommand#setup()}. */ diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandUnbanCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandUnbanCommandTest.java index 195992862..20c015d63 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/IslandUnbanCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/IslandUnbanCommandTest.java @@ -24,7 +24,6 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import org.bukkit.scheduler.BukkitScheduler; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -33,7 +32,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.Settings; @@ -46,6 +44,7 @@ import world.bentobox.bentobox.managers.IslandsManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento @@ -53,7 +52,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class }) -public class IslandUnbanCommandTest { +public class IslandUnbanCommandTest extends RanksManagerBeforeClassTest { @Mock private CompositeCommand ic; @@ -71,9 +70,7 @@ public class IslandUnbanCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); User.setPlugin(plugin); // Command manager @@ -135,11 +132,6 @@ public void setUp() throws Exception { } - @After - public void tearDown() { - Mockito.framework().clearInlineMocks(); - } - /** * Test method for {@link IslandUnbanCommand#canExecute(User, String, List)} */ diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamCommandTest.java index 3bc491105..5b49aae4d 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamCommandTest.java @@ -18,7 +18,6 @@ import org.bukkit.World; import org.bukkit.plugin.PluginManager; import org.eclipse.jdt.annotation.Nullable; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,7 +25,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import com.google.common.collect.ImmutableSet; @@ -40,6 +38,7 @@ import world.bentobox.bentobox.managers.IslandWorldManager; import world.bentobox.bentobox.managers.IslandsManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento @@ -47,7 +46,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class }) -public class IslandTeamCommandTest { +public class IslandTeamCommandTest extends RanksManagerBeforeClassTest { @Mock private CompositeCommand ic; @@ -81,9 +80,7 @@ public class IslandTeamCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); // Command manager CommandsManager cm = mock(CommandsManager.class); @@ -125,18 +122,16 @@ public void setUp() throws Exception { // IWM when(plugin.getIWM()).thenReturn(iwm); when(iwm.getPermissionPrefix(any())).thenReturn("bskyblock."); + + // RanksManager + RanksManager rm = new RanksManager(); + when(plugin.getRanksManager()).thenReturn(rm); // Command under test tc = new IslandTeamCommand(ic); } - /** - */ - @After - public void tearDown() throws Exception { - } - /** * Test method for {@link world.bentobox.bentobox.api.commands.island.team.IslandTeamCommand#IslandTeamCommand(world.bentobox.bentobox.api.commands.CompositeCommand)}. */ diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamCoopCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamCoopCommandTest.java index 224e71ead..824121f6a 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamCoopCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamCoopCommandTest.java @@ -18,7 +18,6 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitScheduler; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,7 +26,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import com.google.common.collect.ImmutableSet; @@ -43,6 +41,7 @@ import world.bentobox.bentobox.managers.PlaceholdersManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento @@ -50,7 +49,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class }) -public class IslandTeamCoopCommandTest { +public class IslandTeamCoopCommandTest extends RanksManagerBeforeClassTest { @Mock private IslandTeamCommand ic; @@ -69,9 +68,7 @@ public class IslandTeamCoopCommandTest { @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); // Command manager CommandsManager cm = mock(CommandsManager.class); @@ -145,11 +142,6 @@ public void setUp() throws Exception { } - @After - public void tearDown() { - User.clearUsers(); - } - /** * Test method for {@link world.bentobox.bentobox.api.commands.island.team.IslandTeamCoopCommand#canExecute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. */ diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamInviteCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamInviteCommandTest.java index d3308cb71..cc32b3b40 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamInviteCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamInviteCommandTest.java @@ -29,7 +29,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import com.google.common.collect.ImmutableSet; @@ -46,6 +45,7 @@ import world.bentobox.bentobox.managers.LocalesManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento @@ -53,7 +53,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class }) -public class IslandTeamInviteCommandTest { +public class IslandTeamInviteCommandTest extends RanksManagerBeforeClassTest { @Mock private IslandTeamCommand ic; @@ -86,10 +86,8 @@ public class IslandTeamInviteCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); - + super.setUp(); + // Command manager CommandsManager cm = mock(CommandsManager.class); when(plugin.getCommandsManager()).thenReturn(cm); diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamKickCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamKickCommandTest.java index b11245fc0..4db3c7813 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamKickCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamKickCommandTest.java @@ -25,7 +25,6 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import org.bukkit.scheduler.BukkitScheduler; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -34,7 +33,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet.Builder; @@ -55,13 +53,14 @@ import world.bentobox.bentobox.managers.PlaceholdersManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class }) -public class IslandTeamKickCommandTest { +public class IslandTeamKickCommandTest extends RanksManagerBeforeClassTest { @Mock private CompositeCommand ic; @@ -94,9 +93,7 @@ public class IslandTeamKickCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); // Command manager CommandsManager cm = mock(CommandsManager.class); @@ -194,10 +191,6 @@ public void setUp() throws Exception { when(island.getRank(notUUID)).thenReturn(RanksManager.MEMBER_RANK); } - @After - public void tearDown() { - User.clearUsers(); - } /** * Test method for {@link IslandTeamKickCommand#execute(User, String, java.util.List)} diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamPromoteCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamPromoteCommandTest.java index e9072ebc3..5482a1bfc 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamPromoteCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamPromoteCommandTest.java @@ -20,7 +20,6 @@ import org.bukkit.World; import org.bukkit.entity.Player; import org.eclipse.jdt.annotation.Nullable; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -29,7 +28,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import com.google.common.collect.ImmutableSet; @@ -44,6 +42,7 @@ import world.bentobox.bentobox.managers.PlaceholdersManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento @@ -51,7 +50,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class }) -public class IslandTeamPromoteCommandTest { +public class IslandTeamPromoteCommandTest extends RanksManagerBeforeClassTest { @Mock Player player; @@ -82,9 +81,7 @@ public class IslandTeamPromoteCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); // Command manager CommandsManager cm = mock(CommandsManager.class); @@ -145,14 +142,6 @@ public void setUp() throws Exception { } - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - User.clearUsers(); - } - /** * Test method for {@link world.bentobox.bentobox.api.commands.island.team.IslandTeamPromoteCommand#IslandTeamPromoteCommand(world.bentobox.bentobox.api.commands.CompositeCommand, java.lang.String)}. */ diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamTrustCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamTrustCommandTest.java index afb0507a4..2e3bc40d0 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamTrustCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamTrustCommandTest.java @@ -19,7 +19,6 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitScheduler; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -28,7 +27,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import com.google.common.collect.ImmutableSet; @@ -44,6 +42,7 @@ import world.bentobox.bentobox.managers.PlaceholdersManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento @@ -51,7 +50,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class }) -public class IslandTeamTrustCommandTest { +public class IslandTeamTrustCommandTest extends RanksManagerBeforeClassTest { @Mock private IslandTeamCommand ic; @@ -74,9 +73,7 @@ public class IslandTeamTrustCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); // Command manager CommandsManager cm = mock(CommandsManager.class); @@ -156,11 +153,6 @@ public void setUp() throws Exception { } - @After - public void tearDown() { - User.clearUsers(); - } - /** * Test method for {@link world.bentobox.bentobox.api.commands.island.team.IslandTeamTrustCommand#canExecute(world.bentobox.bentobox.api.user.User, java.lang.String, java.util.List)}. */ diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamUncoopCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamUncoopCommandTest.java index 804ca1da7..e173b18f4 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamUncoopCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamUncoopCommandTest.java @@ -30,7 +30,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.Settings; @@ -44,6 +43,7 @@ import world.bentobox.bentobox.managers.LocalesManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento @@ -51,7 +51,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class }) -public class IslandTeamUncoopCommandTest { +public class IslandTeamUncoopCommandTest extends RanksManagerBeforeClassTest { private CompositeCommand ic; private UUID uuid; @@ -67,9 +67,7 @@ public class IslandTeamUncoopCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + super.setUp(); // Command manager CommandsManager cm = mock(CommandsManager.class); diff --git a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamUntrustCommandTest.java b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamUntrustCommandTest.java index 948fc82ae..1c3c9d898 100644 --- a/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamUntrustCommandTest.java +++ b/src/test/java/world/bentobox/bentobox/api/commands/island/team/IslandTeamUntrustCommandTest.java @@ -29,7 +29,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.Settings; @@ -43,6 +42,7 @@ import world.bentobox.bentobox.managers.LocalesManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento @@ -50,7 +50,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, User.class }) -public class IslandTeamUntrustCommandTest { +public class IslandTeamUntrustCommandTest extends RanksManagerBeforeClassTest { private CompositeCommand ic; private UUID uuid; @@ -66,10 +66,8 @@ public class IslandTeamUntrustCommandTest { */ @Before public void setUp() throws Exception { - // Set up plugin - BentoBox plugin = mock(BentoBox.class); - Whitebox.setInternalState(BentoBox.class, "instance", plugin); - + super.setUp(); + // Command manager CommandsManager cm = mock(CommandsManager.class); when(plugin.getCommandsManager()).thenReturn(cm); diff --git a/src/test/java/world/bentobox/bentobox/listeners/flags/clicklisteners/CommandRankClickListenerTest.java b/src/test/java/world/bentobox/bentobox/listeners/flags/clicklisteners/CommandRankClickListenerTest.java index 732846657..ade3a1be4 100644 --- a/src/test/java/world/bentobox/bentobox/listeners/flags/clicklisteners/CommandRankClickListenerTest.java +++ b/src/test/java/world/bentobox/bentobox/listeners/flags/clicklisteners/CommandRankClickListenerTest.java @@ -25,7 +25,6 @@ import org.bukkit.inventory.Inventory; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,7 +34,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.api.addons.GameModeAddon; @@ -50,6 +48,7 @@ import world.bentobox.bentobox.managers.IslandWorldManager; import world.bentobox.bentobox.managers.IslandsManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; import world.bentobox.bentobox.panels.settings.SettingsTab; import world.bentobox.bentobox.util.Util; @@ -59,7 +58,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({Bukkit.class, BentoBox.class, Util.class}) -public class CommandRankClickListenerTest { +public class CommandRankClickListenerTest extends RanksManagerBeforeClassTest { @Mock private User user; @Mock @@ -67,8 +66,6 @@ public class CommandRankClickListenerTest { @Mock private TabbedPanel panel; @Mock - private BentoBox plugin; - @Mock private IslandWorldManager iwm; @Mock private @NonNull Inventory inv; @@ -94,11 +91,11 @@ public class CommandRankClickListenerTest { */ @Before public void setUp() throws Exception { + super.setUp(); // Bukkit PowerMockito.mockStatic(Bukkit.class, Mockito.RETURNS_MOCKS); - // Set up plugin - Whitebox.setInternalState(BentoBox.class, "instance", plugin); + // Island when(island.getOwner()).thenReturn(uuid); when(island.isAllowed(user, Flags.CHANGE_SETTINGS)).thenReturn(true); @@ -146,14 +143,6 @@ public void setUp() throws Exception { crcl = new CommandRankClickListener(); } - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - Mockito.framework().clearInlineMocks(); - } - /** * Test method for {@link world.bentobox.bentobox.listeners.flags.clicklisteners.CommandRankClickListener#onClick(world.bentobox.bentobox.api.panels.Panel, world.bentobox.bentobox.api.user.User, org.bukkit.event.inventory.ClickType, int)}. */ diff --git a/src/test/java/world/bentobox/bentobox/lists/GameModePlaceholderTest.java b/src/test/java/world/bentobox/bentobox/lists/GameModePlaceholderTest.java index f1d13e4da..886c73a3d 100644 --- a/src/test/java/world/bentobox/bentobox/lists/GameModePlaceholderTest.java +++ b/src/test/java/world/bentobox/bentobox/lists/GameModePlaceholderTest.java @@ -23,7 +23,6 @@ import com.google.common.collect.ImmutableSet; -import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.TestWorldSettings; import world.bentobox.bentobox.api.addons.GameModeAddon; import world.bentobox.bentobox.api.configuration.WorldSettings; @@ -33,13 +32,14 @@ import world.bentobox.bentobox.managers.IslandsManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.bentobox.managers.RanksManagerBeforeClassTest; /** * @author tastybento * */ @RunWith(PowerMockRunner.class) -public class GameModePlaceholderTest { +public class GameModePlaceholderTest extends RanksManagerBeforeClassTest { @Mock private GameModeAddon addon; @@ -53,12 +53,10 @@ public class GameModePlaceholderTest { @Mock private World world; @Mock - private BentoBox plugin; - @Mock private IslandWorldManager iwm; @Mock private IslandsManager im; - private final RanksManager rm = new RanksManager(); + private RanksManager rm; @Mock private @Nullable Location location; @@ -67,6 +65,8 @@ public class GameModePlaceholderTest { */ @Before public void setUp() throws Exception { + super.setUp(); + rm = new RanksManager(); uuid = UUID.randomUUID(); when(addon.getPlayers()).thenReturn(pm); when(addon.getIslands()).thenReturn(im); diff --git a/src/test/java/world/bentobox/bentobox/managers/PlayersManagerTest.java b/src/test/java/world/bentobox/bentobox/managers/PlayersManagerTest.java index acc3cf611..8e70129aa 100644 --- a/src/test/java/world/bentobox/bentobox/managers/PlayersManagerTest.java +++ b/src/test/java/world/bentobox/bentobox/managers/PlayersManagerTest.java @@ -250,8 +250,6 @@ public void setUp() throws Exception { pm = new PlayersManager(plugin); } - /** - */ @After public void tearDown() throws Exception { User.clearUsers(); diff --git a/src/test/java/world/bentobox/bentobox/managers/RanksManagerBeforeClassTest.java b/src/test/java/world/bentobox/bentobox/managers/RanksManagerBeforeClassTest.java new file mode 100644 index 000000000..86d28f14d --- /dev/null +++ b/src/test/java/world/bentobox/bentobox/managers/RanksManagerBeforeClassTest.java @@ -0,0 +1,84 @@ +package world.bentobox.bentobox.managers; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.beans.IntrospectionException; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.concurrent.CompletableFuture; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import world.bentobox.bentobox.BentoBox; +import world.bentobox.bentobox.api.user.User; +import world.bentobox.bentobox.database.AbstractDatabaseHandler; +import world.bentobox.bentobox.database.DatabaseSetup; + +/** + * @author tastybento + * + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest({BentoBox.class, DatabaseSetup.class,}) +public abstract class RanksManagerBeforeClassTest { + + private static AbstractDatabaseHandler h; + + @Mock + public BentoBox plugin; + + @SuppressWarnings("unchecked") + @BeforeClass + public static void beforeClass() throws IllegalAccessException, InvocationTargetException, IntrospectionException { + // This has to be done beforeClass otherwise the tests will interfere with each other + h = mock(AbstractDatabaseHandler.class); + // Database + PowerMockito.mockStatic(DatabaseSetup.class); + DatabaseSetup dbSetup = mock(DatabaseSetup.class); + when(DatabaseSetup.getDatabase()).thenReturn(dbSetup); + when(dbSetup.getHandler(any())).thenReturn(h); + when(h.saveObject(any())).thenReturn(CompletableFuture.completedFuture(true)); + } + + /** + */ + @Before + public void setUp() throws Exception { + // Set up plugin + Whitebox.setInternalState(BentoBox.class, "instance", plugin); + } + + @After + public void tearDown() throws IOException { + User.clearUsers(); + Mockito.framework().clearInlineMocks(); + deleteAll(new File("database")); + deleteAll(new File("database_backup")); + } + + private void deleteAll(File file) throws IOException { + if (file.exists()) { + Files.walk(file.toPath()) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } + + } + +} diff --git a/src/test/java/world/bentobox/bentobox/managers/RanksManagerTest.java b/src/test/java/world/bentobox/bentobox/managers/RanksManagerTest.java index fe925cc14..328bf99ea 100644 --- a/src/test/java/world/bentobox/bentobox/managers/RanksManagerTest.java +++ b/src/test/java/world/bentobox/bentobox/managers/RanksManagerTest.java @@ -6,31 +6,32 @@ import java.util.Map; -import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.mockito.Mockito; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import world.bentobox.bentobox.database.DatabaseSetup; /** * @author tastybento * */ -public class RanksManagerTest { +@RunWith(PowerMockRunner.class) +@PrepareForTest({DatabaseSetup.class,}) +public class RanksManagerTest extends RanksManagerBeforeClassTest { public static RanksManager ranksManager; - + /** */ @Before public void setUp() throws Exception { + super.setUp(); ranksManager = new RanksManager(); } - - @After - public void tearDown() { - Mockito.framework().clearInlineMocks(); - } - + /** * Test method for {@link world.bentobox.bentobox.managers.RanksManager#addRank(java.lang.String, int)}. */