1
0
mirror of https://github.com/mcMMO-Dev/mcMMO.git synced 2026-02-18 17:53:00 +01:00

Compare commits

...

19 Commits

Author SHA1 Message Date
nossr50
7afdb0ec9c more work on command on level up and misc refactoring on unit tests 2025-07-09 17:40:38 -07:00
nossr50
0af8b2c41d Merge branch 'master' of https://github.com/mcMMO-Dev/mcMMO into commandsonlevelup 2025-07-09 14:36:50 -07:00
nossr50
9b5be855fd (WIP) reworking level up commands to have multiple requirements 2024-02-18 15:45:51 -08:00
nossr50
0650731723 fix annotation 2024-02-17 16:23:17 -08:00
nossr50
37949d07f6 logging changes 2024-02-17 16:19:46 -08:00
nossr50
3bc7b8eee7 Merge branch 'master' of https://github.com/mcMMO-Dev/mcMMO into commandsonlevelup 2024-02-17 16:11:52 -08:00
nossr50
847095aff4 Add power level commands to commands on level up 2024-01-28 16:57:26 -08:00
nossr50
c5ec99ab51 Merge branch 'master' of https://github.com/mcMMO-Dev/mcMMO into commandsonlevelup 2024-01-28 15:04:36 -08:00
nossr50
302b07f221 Merge branch 'master' of https://github.com/mcMMO-Dev/mcMMO into commandsonlevelup 2023-08-27 16:20:41 -07:00
nossr50
edab455581 Fix bug with levels up commands reporting incorrect level 2023-08-27 16:19:46 -07:00
nossr50
2d8bdbded8 More unit tests 2023-08-27 14:39:59 -07:00
nossr50
c1a4cc2c97 Add power_level_milestones entry to default config 2023-08-20 14:56:13 -07:00
nossr50
02cacb9e94 Add some string injection for commands 2023-08-20 14:28:53 -07:00
nossr50
899a37edbc Merge branch 'master' of https://github.com/mcMMO-Dev/mcMMO into commandsonlevelup 2023-08-20 13:43:11 -07:00
nossr50
753834e1fc Read and register commands from config 2023-08-20 13:42:55 -07:00
nossr50
656beb34ef Builder style 2023-07-30 16:25:58 -07:00
nossr50
8ee282beec Add builder, switch to BiPredicate for impl 2023-07-30 16:23:41 -07:00
nossr50
eb8c5bf0e9 more unit tests 2023-07-22 10:34:27 -07:00
nossr50
027b79639b command on level up wip 2023-07-22 10:14:35 -07:00
33 changed files with 1606 additions and 256 deletions

View File

@@ -1109,7 +1109,7 @@ public final class ExperienceAPI {
* @throws InvalidFormulaTypeException if the given formulaType is not valid
*/
public static int getXpNeededToLevel(int level) {
return mcMMO.getFormulaManager()
return mcMMO.p.getFormulaManager()
.getXPtoNextLevel(level, ExperienceConfig.getInstance().getFormulaType());
}
@@ -1123,7 +1123,7 @@ public final class ExperienceAPI {
* @throws InvalidFormulaTypeException if the given formulaType is not valid
*/
public static int getXpNeededToLevel(int level, String formulaType) {
return mcMMO.getFormulaManager().getXPtoNextLevel(level, getFormulaType(formulaType));
return mcMMO.p.getFormulaManager().getXPtoNextLevel(level, getFormulaType(formulaType));
}
/**

View File

@@ -18,7 +18,7 @@ public class ConvertExperienceCommand implements CommandExecutor {
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command,
@NotNull String label, String[] args) {
if (args.length == 2) {
FormulaType previousType = mcMMO.getFormulaManager().getPreviousFormulaType();
FormulaType previousType = mcMMO.p.getFormulaManager().getPreviousFormulaType();
FormulaType newType = FormulaType.getFormulaType(args[1].toUpperCase(Locale.ENGLISH));
if (newType == FormulaType.UNKNOWN) {

View File

@@ -0,0 +1,4 @@
package com.gmail.nossr50.commands.levelup;
public interface CommandsOnLevel {
}

View File

@@ -0,0 +1,126 @@
package com.gmail.nossr50.commands.levelup;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.VisibleForTesting;
public class LevelUpCommand implements CommandsOnLevel {
private final @Nullable List<BiPredicate<PrimarySkillType, Integer>> conditions;
private final @Nullable Predicate<Integer> powerLevelCondition;
private final boolean logInfo;
private final @NotNull LinkedList<String> commands;
public LevelUpCommand(@Nullable List<BiPredicate<PrimarySkillType, Integer>> conditions,
@Nullable Predicate<Integer> powerLevelCondition,
@NotNull LinkedList<String> commands, boolean logInfo) {
this.conditions = conditions;
this.powerLevelCondition = powerLevelCondition;
if (conditions == null && powerLevelCondition == null) {
throw new IllegalArgumentException("At least one condition must be set");
}
this.commands = commands;
this.logInfo = logInfo;
}
public void process(@NotNull McMMOPlayer player, @NotNull PrimarySkillType primarySkillType,
@NotNull Set<Integer> levelsGained,
@NotNull Set<Integer> powerLevelsGained) {
// each predicate has to pass at least once
// we check the predicates against all levels gained to see if they pass at least once
// if all predicates pass at least once, we execute the command
boolean allConditionsPass = (conditions == null) || conditions.stream().allMatch(
predicate -> levelsGained.stream()
.anyMatch(level -> predicate.test(primarySkillType, level)));
// we also check the power level predicate to see if it passes at least once, if this predicate is null, we mark it as passed
boolean powerLevelConditionPass =
(powerLevelCondition == null) || powerLevelsGained.stream()
.anyMatch(powerLevelCondition);
if (allConditionsPass && powerLevelConditionPass) {
executeCommand(player);
}
}
@VisibleForTesting
void executeCommand(@NotNull McMMOPlayer player) {
LogUtils.debug(mcMMO.p.getLogger(), "Executing level up commands: " + commands);
for (String command : commands) {
LogUtils.debug(mcMMO.p.getLogger(), "Executing command: " + command);
String injectedCommand = injectedCommand(command, player);
if (!injectedCommand.equalsIgnoreCase(command)) {
LogUtils.debug(mcMMO.p.getLogger(),
("Command has been injected with new values: " + injectedCommand));
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), injectedCommand);
}
}
@VisibleForTesting
String injectedCommand(String command, McMMOPlayer player) {
// TODO: unit tests
StringBuilder commandBuilder = new StringBuilder(command);
// Replace %player% with player name
replaceAll(commandBuilder, "{@player}", player.getPlayer().getName());
// Replace each skill level
for (PrimarySkillType primarySkillType : PrimarySkillType.values()) {
if (primarySkillType == PrimarySkillType.SMELTING
|| primarySkillType == PrimarySkillType.SALVAGE) {
continue;
}
replaceAll(commandBuilder, "{@" + primarySkillType.name().toLowerCase() + "_level}",
String.valueOf(player.getSkillLevel(primarySkillType)));
}
// Replace power level
replaceAll(commandBuilder, "{@power_level}", String.valueOf(player.getPowerLevel()));
return commandBuilder.toString();
}
private void replaceAll(StringBuilder builder, String from, String to) {
int index = builder.indexOf(from);
while (index != -1) {
builder.replace(index, index + from.length(), to);
index = builder.indexOf(from, index + to.length());
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LevelUpCommand that = (LevelUpCommand) o;
return logInfo == that.logInfo && Objects.equals(conditions, that.conditions)
&& Objects.equals(commands, that.commands);
}
@Override
public int hashCode() {
return Objects.hash(conditions, logInfo, commands);
}
@Override
public String toString() {
return "SkillLevelUpCommand{" +
"conditions=" + conditions +
", logInfo=" + logInfo +
", commands=" + commands +
'}';
}
}

View File

@@ -0,0 +1,77 @@
package com.gmail.nossr50.commands.levelup;
import static java.util.Objects.requireNonNull;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
import org.jetbrains.annotations.NotNull;
public class LevelUpCommandBuilder {
private LinkedList<String> commands = null;
private List<BiPredicate<PrimarySkillType, Integer>> conditions = null;
private Predicate<Integer> powerLevelCondition = null;
private boolean logInfo;
public LevelUpCommandBuilder() {
this.logInfo = false;
}
public LevelUpCommandBuilder withPredicate(BiPredicate<PrimarySkillType, Integer> condition) {
if (this.conditions == null) {
this.conditions = new LinkedList<>();
}
conditions.add(condition);
return this;
}
public LevelUpCommandBuilder withPowerLevelCondition(Predicate<Integer> powerLevelCondition) {
if (this.powerLevelCondition != null) {
throw new IllegalStateException("power level condition already set");
}
this.powerLevelCondition = powerLevelCondition;
return this;
}
public LevelUpCommandBuilder withConditions(
@NotNull Collection<BiPredicate<PrimarySkillType, Integer>> conditions) {
if (this.conditions == null) {
this.conditions = new LinkedList<>();
} else {
throw new IllegalStateException("conditions already set");
}
this.conditions.addAll(conditions);
return this;
}
public LevelUpCommandBuilder withLogInfo(boolean logInfo) {
this.logInfo = logInfo;
return this;
}
public LevelUpCommandBuilder command(@NotNull String command) {
this.commands = new LinkedList<>();
this.commands.add(command);
return this;
}
public LevelUpCommandBuilder commands(@NotNull Collection<String> command) {
this.commands = new LinkedList<>(command);
return this;
}
public LevelUpCommand build() {
if (conditions == null && powerLevelCondition == null) {
throw new IllegalStateException("no conditions found for level up command");
}
requireNonNull(commands, "no commands found for level up command");
return new LevelUpCommand(conditions, powerLevelCondition, commands, logInfo);
}
}

View File

@@ -0,0 +1,89 @@
package com.gmail.nossr50.commands.levelup;
import static java.util.Objects.requireNonNull;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import org.jetbrains.annotations.NotNull;
/**
* Manages commands to be executed on level up
*/
public class LevelUpCommandManager {
private final @NotNull Set<LevelUpCommand> levelUpCommands;
private final @NotNull mcMMO plugin;
public LevelUpCommandManager(@NotNull mcMMO plugin) {
this.plugin = requireNonNull(plugin, "plugin cannot be null");
this.levelUpCommands = new HashSet<>();
}
public void registerCommand(@NotNull LevelUpCommand levelUpCommand) {
requireNonNull(levelUpCommand, "skillLevelUpCommand cannot be null");
levelUpCommands.add(levelUpCommand);
LogUtils.debug(mcMMO.p.getLogger(),
"Registered level up command - SkillLevelUpCommand: " + levelUpCommand);
}
/**
* Apply the level up commands to the player
*
* @param mmoPlayer the player
* @param primarySkillType the skill type
* @param levelsGained the levels gained
*/
public void applySkillLevelUp(@NotNull McMMOPlayer mmoPlayer,
@NotNull PrimarySkillType primarySkillType,
Set<Integer> levelsGained, Set<Integer> powerLevelsGained) {
if (!mmoPlayer.getPlayer().isOnline()) {
return;
}
for (LevelUpCommand command : levelUpCommands) {
command.process(mmoPlayer, primarySkillType, levelsGained, powerLevelsGained);
}
}
public @NotNull Set<LevelUpCommand> getLevelUpCommands() {
return levelUpCommands;
}
/**
* Clear all registered commands
*/
public void clear() {
mcMMO.p.getLogger().info("Clearing registered commands on level up");
levelUpCommands.clear();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LevelUpCommandManager that = (LevelUpCommandManager) o;
return Objects.equals(levelUpCommands, that.levelUpCommands) && Objects.equals(plugin,
that.plugin);
}
@Override
public int hashCode() {
return Objects.hash(levelUpCommands, plugin);
}
@Override
public String toString() {
return "LevelUpCommandManager{" +
"levelUpCommands=" + levelUpCommands +
", plugin=" + plugin +
'}';
}
}

View File

@@ -0,0 +1,127 @@
package com.gmail.nossr50.config;
import com.gmail.nossr50.commands.levelup.LevelUpCommand;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import java.io.File;
import org.bukkit.configuration.ConfigurationSection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class CommandOnLevelUpConfig extends BukkitConfig {
public static final String LEVEL_UP_COMMANDS = "level_up_commands";
public static final String LEVELS_SECTION = "levels";
public static final String SKILLS_SECTION = "skills";
public static final String CONDITION_SECTION = "condition";
public static final String ENABLED = "enabled";
public static final String COMMANDS = "commands";
public static final String POWER_LEVEL_SECTION = "power_level";
public CommandOnLevelUpConfig(@NotNull File dataFolder) {
super("levelupcommands.yml", dataFolder);
// TODO: loadKeys() should really get called in super
loadKeys();
}
@Override
protected void loadKeys() {
final ConfigurationSection configurationSection = config.getConfigurationSection(LEVEL_UP_COMMANDS);
if (configurationSection == null) {
LogUtils.debug(mcMMO.p.getLogger(), "No commands found in the level up commands config file.");
return;
}
for (String key : configurationSection.getKeys(false)) {
final ConfigurationSection commandSection = configurationSection.getConfigurationSection(key);
if (commandSection == null) {
mcMMO.p.getLogger().severe("Unable to load command section for key: " + key);
continue;
}
LevelUpCommand levelUpCommand = buildSkillLevelUpCommand(commandSection);
if (levelUpCommand == null) {
mcMMO.p.getLogger().severe("Invalid command format for key: " + key);
} else {
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommand);
mcMMO.p.getLogger().info("Level up command successfully loaded from config for key: " + key);
}
}
}
private @Nullable LevelUpCommand buildSkillLevelUpCommand(final ConfigurationSection commandSection) {
// TODO: Rework
return null;
// LevelUpCommandBuilder builder = new LevelUpCommandBuilder();
// // check if command is enabled
// if (!commandSection.getBoolean(ENABLED, true)) {
// return null;
// }
// /* Condition Section */
// ConfigurationSection condition = commandSection.getConfigurationSection(CONDITION_SECTION);
// if (condition == null) {
// mcMMO.p.getLogger().severe("No condition section found for command named " + commandSection.getName());
// return null;
// }
//
// // Skill Filter
// // check if skills is string or configuration section
// if (condition.contains(SKILLS_SECTION)) {
// if (condition.isString(SKILLS_SECTION)) {
// String skillName = condition.getString(SKILLS_SECTION);
// if (skillName != null) {
// PrimarySkillType primarySkillType = mcMMO.p.getSkillTools().matchSkill(skillName);
// if (primarySkillType != null) {
// builder.withSkillFilter(getSkillsFromFilter(new HashSet<>(Set.of(skillName))));
// }
// }
// } else {
// ConfigurationSection skillsSection = condition.getConfigurationSection(SKILLS_SECTION);
// if (skillsSection != null) {
// Set<String> skillNames = skillsSection.getKeys(false);
// Set<PrimarySkillType> skillsFromFilter = getSkillsFromFilter(skillNames);
// if (skillsFromFilter.isEmpty()) {
// LogUtils.debug(mcMMO.p.getLogger(), "No valid skills found for command named "
// + commandSection.getName() + "for condition section named " + skillsSection.getName());
// } else {
// builder.withSkillFilter(skillsFromFilter);
// }
// }
// }
// }
//
// // for now only simple condition is supported
// if (!condition.contains(LEVELS_SECTION)) {
// mcMMO.p.getLogger().severe("No condition.levels section found for command named " + commandSection.getName());
// return null;
// }
//
// Collection<Integer> levels = condition.getIntegerList(LEVELS_SECTION);
// if (levels.isEmpty()) {
// mcMMO.p.getLogger().severe("No valid levels found in condition.levels for command named "
// + commandSection.getName());
// return null;
// }
// builder.withLevels(levels);
//
// // commands
// if (commandSection.isString(COMMANDS)) {
// String command = commandSection.getString(COMMANDS);
// if (command != null) {
// builder.command(command);
// }
// } else {
// List<String> commands = commandSection.getStringList(COMMANDS);
// if (commands.isEmpty()) {
// mcMMO.p.getLogger().severe("No commands defined for command named "
// + commandSection.getName());
// return null;
// } else {
// builder.commands(commands);
// }
// }
//
// return builder.build();
}
}

View File

@@ -223,7 +223,7 @@ public class ExperienceConfig extends BukkitConfig {
/* Curve settings */
public FormulaType getFormulaType() {
return FormulaType.getFormulaType(config.getString("Experience_Formula.Curve"));
return FormulaType.getFormulaType(config.getString("Experience_Formula.Curve", "LINEAR"));
}
public boolean getCumulativeCurveEnabled() {
@@ -232,14 +232,16 @@ public class ExperienceConfig extends BukkitConfig {
/* Curve values */
public double getMultiplier(FormulaType type) {
double def = type == FormulaType.LINEAR ? 20D : 0.1D;
return config.getDouble(
"Experience_Formula." + StringUtils.getCapitalized(type.toString())
+ "_Values.multiplier");
+ "_Values.multiplier", def);
}
public int getBase(FormulaType type) {
int def = type == FormulaType.LINEAR ? 1020 : 2000;
return config.getInt("Experience_Formula." + StringUtils.getCapitalized(type.toString())
+ "_Values.base");
+ "_Values.base", def);
}
public double getExponent(FormulaType type) {
@@ -288,7 +290,7 @@ public class ExperienceConfig extends BukkitConfig {
return config.getDouble(
"Experience_Formula.Skill_Multiplier." + StringUtils.getCapitalized(
skill.toString()),
1);
1D);
}
/* Custom XP perk */

View File

@@ -206,7 +206,7 @@ public class Party {
public int getXpToLevel() {
FormulaType formulaType = ExperienceConfig.getInstance().getFormulaType();
return (mcMMO.getFormulaManager().getXPtoNextLevel(level, formulaType)) * (
return (mcMMO.p.getFormulaManager().getXPtoNextLevel(level, formulaType)) * (
getOnlineMembers().size() + mcMMO.p.getGeneralConfig().getPartyXpCurveMultiplier());
}

View File

@@ -65,7 +65,6 @@ import java.util.Map;
import java.util.UUID;
import net.kyori.adventure.identity.Identified;
import net.kyori.adventure.identity.Identity;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.block.Block;
@@ -711,13 +710,13 @@ public class McMMOPlayer implements Identified {
*/
public void applyXpGain(PrimarySkillType primarySkillType, float xp, XPGainReason xpGainReason,
XPGainSource xpGainSource) {
if (!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, primarySkillType)) {
if (!Permissions.skillEnabled(player, primarySkillType)) {
return;
}
final McMMOPlayerPreXpGainEvent mmoPlayerPreXpGainEvent = new McMMOPlayerPreXpGainEvent(
player, primarySkillType, xp, xpGainReason);
Bukkit.getPluginManager().callEvent(mmoPlayerPreXpGainEvent);
mcMMO.p.getServer().getPluginManager().callEvent(mmoPlayerPreXpGainEvent);
xp = mmoPlayerPreXpGainEvent.getXpGained();
if (SkillTools.isChildSkill(primarySkillType)) {

View File

@@ -450,7 +450,7 @@ public class PlayerProfile {
? UserManager.getPlayer(playerName).getPowerLevel() : skills.get(primarySkillType);
FormulaType formulaType = ExperienceConfig.getInstance().getFormulaType();
return mcMMO.getFormulaManager().getXPtoNextLevel(level, formulaType);
return mcMMO.p.getFormulaManager().getXPtoNextLevel(level, formulaType);
}
private int getChildSkillLevel(@NotNull PrimarySkillType primarySkillType)

View File

@@ -5,7 +5,9 @@ import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.skills.SkillTools;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
@@ -185,6 +187,16 @@ public enum PrimarySkillType {
return mcMMO.p.getSkillTools().matchSkill(skillName);
}
/**
* WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
* @see SkillTools#matchSkill(java.lang.String)
* @deprecated this is being removed in an upcoming update, you should be using mcMMO.getSkillTools() instead
*/
@Deprecated
public static Set<PrimarySkillType> getSkills(Collection<String> skillNames) {
return mcMMO.p.getSkillTools().matchSkills(skillNames);
}
/**
* WARNING: Being removed in an upcoming update, you should be using mcMMO.getSkillTools()
* instead

View File

@@ -15,6 +15,8 @@ import com.gmail.nossr50.util.skills.RankUtils;
import com.gmail.nossr50.util.skills.SkillTools;
import com.gmail.nossr50.worldguard.WorldGuardManager;
import com.gmail.nossr50.worldguard.WorldGuardUtils;
import java.util.LinkedHashSet;
import java.util.Set;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@@ -30,8 +32,8 @@ public class SelfListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerLevelUp(McMMOPlayerLevelUpEvent event) {
Player player = event.getPlayer();
PrimarySkillType skill = event.getSkill();
final Player player = event.getPlayer();
final PrimarySkillType skill = event.getSkill();
final McMMOPlayer mmoPlayer = UserManager.getPlayer(player);
@@ -56,6 +58,20 @@ public class SelfListener implements Listener {
ScoreboardManager.handleLevelUp(player, skill);
}
}
final Set<Integer> levelsAchieved = new LinkedHashSet<>();
final Set<Integer> powerLevelsAchieved = new LinkedHashSet<>();
int startingLevel = event.getSkillLevel() - event.getLevelsGained();
int startingPowerLevel = mmoPlayer.getPowerLevel() - event.getLevelsGained();
for (int i = 0; i < event.getLevelsGained(); i++) {
levelsAchieved.add(startingLevel + (i + 1));
}
for (int i = 0; i < event.getLevelsGained(); i++) {
powerLevelsAchieved.add(startingPowerLevel + (i + 1));
}
plugin.getLevelUpCommandManager()
.applySkillLevelUp(mmoPlayer, skill, levelsAchieved, powerLevelsAchieved);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)

View File

@@ -2,7 +2,9 @@ package com.gmail.nossr50;
import com.gmail.nossr50.chat.ChatManager;
import com.gmail.nossr50.commands.CommandManager;
import com.gmail.nossr50.commands.levelup.LevelUpCommandManager;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.CommandOnLevelUpConfig;
import com.gmail.nossr50.config.CoreSkillsConfig;
import com.gmail.nossr50.config.CustomItemSupportConfig;
import com.gmail.nossr50.config.GeneralConfig;
@@ -86,10 +88,8 @@ import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -100,8 +100,9 @@ public class mcMMO extends JavaPlugin {
private static RepairableManager repairableManager;
private static SalvageableManager salvageableManager;
private static DatabaseManager databaseManager;
private static FormulaManager formulaManager;
private FormulaManager formulaManager;
private static UpgradeManager upgradeManager;
private static LevelUpCommandManager levelUpCommandManager;
private static MaterialMapStore materialMapStore;
private static PlayerLevelUtils playerLevelUtils;
private static TransientMetadataTools transientMetadataTools;
@@ -158,6 +159,8 @@ public class mcMMO extends JavaPlugin {
private FoliaLib foliaLib;
private PartyManager partyManager;
private CommandOnLevelUpConfig commandOnLevelUpConfig;
public mcMMO() {
p = this;
}
@@ -186,7 +189,9 @@ public class mcMMO extends JavaPlugin {
skillTools = new SkillTools(this); //Load after general config
//Init configs
levelUpCommandManager = new LevelUpCommandManager(this);
advancedConfig = new AdvancedConfig(getDataFolder());
commandOnLevelUpConfig = new CommandOnLevelUpConfig(getDataFolder());
partyConfig = new PartyConfig(getDataFolder());
customItemSupportConfig = new CustomItemSupportConfig(getDataFolder());
@@ -456,7 +461,7 @@ public class mcMMO extends JavaPlugin {
xpEventEnabled = !xpEventEnabled;
}
public static FormulaManager getFormulaManager() {
public FormulaManager getFormulaManager() {
return formulaManager;
}
@@ -840,4 +845,12 @@ public class mcMMO extends JavaPlugin {
public @NotNull FoliaLib getFoliaLib() {
return foliaLib;
}
public @NotNull CommandOnLevelUpConfig getCommandOnLevelUpConfig() {
return commandOnLevelUpConfig;
}
public @NotNull LevelUpCommandManager getLevelUpCommandManager() {
return levelUpCommandManager;
}
}

View File

@@ -51,7 +51,7 @@ public class FormulaConversionTask extends CancellableRunnable {
convertedUsers++;
Misc.printProgress(convertedUsers, DatabaseManager.progressInterval, startMillis);
}
mcMMO.getFormulaManager().setPreviousFormulaType(formulaType);
mcMMO.p.getFormulaManager().setPreviousFormulaType(formulaType);
sender.sendMessage(LocaleLoader.getString("Commands.mcconvert.Experience.Finish",
formulaType.toString()));
@@ -65,14 +65,14 @@ public class FormulaConversionTask extends CancellableRunnable {
for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
int oldLevel = profile.getSkillLevel(primarySkillType);
int oldXPLevel = profile.getSkillXpLevel(primarySkillType);
int totalOldXP = mcMMO.getFormulaManager()
int totalOldXP = mcMMO.p.getFormulaManager()
.calculateTotalExperience(oldLevel, oldXPLevel);
if (totalOldXP == 0) {
continue;
}
int[] newExperienceValues = mcMMO.getFormulaManager()
int[] newExperienceValues = mcMMO.p.getFormulaManager()
.calculateNewLevel(primarySkillType, (int) Math.floor(
totalOldXP / ExperienceConfig.getInstance().getExpModifier()),
formulaType);

View File

@@ -27,6 +27,7 @@ import com.gmail.nossr50.util.skills.CombatUtils;
import com.gmail.nossr50.util.skills.RankUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -209,18 +210,18 @@ public class WoodcuttingManager extends SkillManager {
*/
@VisibleForTesting
void processTree(Block block, Set<Block> treeFellerBlocks) {
List<Block> futureCenterBlocks = new ArrayList<>();
Collection<Block> futureCenterBlocks = new ArrayList<>();
// Check the block up and take different behavior (smaller search) if it's a log
if (processTreeFellerTargetBlock(block.getRelative(BlockFace.UP), futureCenterBlocks,
treeFellerBlocks)) {
for (int[] dir : directions) {
processTreeFellerTargetBlock(block.getRelative(dir[0], 0, dir[1]),
futureCenterBlocks, treeFellerBlocks);
if (treeFellerReachedThreshold) {
return;
}
processTreeFellerTargetBlock(block.getRelative(dir[0], 0, dir[1]),
futureCenterBlocks, treeFellerBlocks);
}
} else {
// Cover DOWN
@@ -229,12 +230,12 @@ public class WoodcuttingManager extends SkillManager {
// Search in a cube
for (int y = -1; y <= 1; y++) {
for (int[] dir : directions) {
processTreeFellerTargetBlock(block.getRelative(dir[0], y, dir[1]),
futureCenterBlocks, treeFellerBlocks);
if (treeFellerReachedThreshold) {
return;
}
processTreeFellerTargetBlock(block.getRelative(dir[0], y, dir[1]),
futureCenterBlocks, treeFellerBlocks);
}
}
}
@@ -302,23 +303,24 @@ public class WoodcuttingManager extends SkillManager {
* @return true if and only if the given block was a Log not already in treeFellerBlocks.
*/
private boolean processTreeFellerTargetBlock(@NotNull Block block,
@NotNull List<Block> futureCenterBlocks,
@NotNull Set<Block> treeFellerBlocks) {
@NotNull Collection<Block> futureCenterBlocks,
@NotNull Collection<Block> treeFellerBlocks) {
if (treeFellerBlocks.contains(block) || mcMMO.getUserBlockTracker().isIneligible(block)) {
return false;
}
// Without this check Tree Feller propagates through leaves until the threshold is hit
if (treeFellerBlocks.size() > treeFellerThreshold) {
treeFellerReachedThreshold = true;
}
if (BlockUtils.hasWoodcuttingXP(block)) {
treeFellerBlocks.add(block);
futureCenterBlocks.add(block);
if (treeFellerBlocks.size() >= treeFellerThreshold) {
treeFellerReachedThreshold = true;
}
return true;
} else if (BlockUtils.isNonWoodPartOfTree(block)) {
treeFellerBlocks.add(block);
if (treeFellerBlocks.size() >= treeFellerThreshold) {
treeFellerReachedThreshold = true;
}
return false;
}
return false;

View File

@@ -283,7 +283,6 @@ public final class EventUtils {
mmoPlayer.getSkillLevel(skill));
NotificationManager.processPowerLevelUpBroadcasting(mmoPlayer,
mmoPlayer.getPowerLevel());
}
}

View File

@@ -5,6 +5,9 @@ import com.gmail.nossr50.datatypes.experience.FormulaType;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.VisibleForTesting;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
@@ -24,7 +27,19 @@ public class FormulaManager {
public FormulaManager() {
/* Setting for Classic Mode (Scales a lot of stuff up by * 10) */
initExperienceNeededMaps();
loadFormula();
if (!formulaFile.exists()) {
previousFormula = FormulaType.UNKNOWN;
return;
}
previousFormula = FormulaType.getFormulaType(YamlConfiguration.loadConfiguration(formulaFile).getString("Previous_Formula", "UNKNOWN"));
}
@VisibleForTesting
public FormulaManager(FormulaType previousFormulaType) {
/* Setting for Classic Mode (Scales a lot of stuff up by * 10) */
initExperienceNeededMaps();
this.previousFormula = previousFormulaType;
}
/**
@@ -119,7 +134,7 @@ public class FormulaManager {
*/
//TODO: When the heck is Unknown used?
if (formulaType == FormulaType.UNKNOWN) {
if (formulaType == null || formulaType == FormulaType.UNKNOWN) {
formulaType = FormulaType.LINEAR;
}
@@ -216,20 +231,6 @@ public class FormulaManager {
}
}
/**
* Load formula file.
*/
public void loadFormula() {
if (!formulaFile.exists()) {
previousFormula = FormulaType.UNKNOWN;
return;
}
previousFormula = FormulaType.getFormulaType(
YamlConfiguration.loadConfiguration(formulaFile)
.getString("Previous_Formula", "UNKNOWN"));
}
/**
* Save formula file.
*/

View File

@@ -159,7 +159,7 @@ public class NotificationManager {
mcMMO.p.getAdvancedConfig().doesNotificationSendCopyToChat(notificationType));
//Call event
Bukkit.getServer().getPluginManager().callEvent(customEvent);
mcMMO.p.getServer().getPluginManager().callEvent(customEvent);
return customEvent;
}

View File

@@ -14,6 +14,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashSet;
@@ -23,6 +24,7 @@ import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.VisibleForTesting;
public class SkillTools {
@@ -272,14 +274,15 @@ public class SkillTools {
}
/**
* Matches a string of a skill to a skill This is NOT case sensitive First it checks the locale
* Matches a string of a skill to a skill This is NOT case-sensitive First it checks the locale
* file and tries to match by the localized name of the skill Then if nothing is found it checks
* against the hard coded "name" of the skill, which is just its name in English
*
* @param skillName target skill name
* @return the matching PrimarySkillType if one is found, otherwise null
*/
public PrimarySkillType matchSkill(String skillName) {
@Nullable
public PrimarySkillType matchSkill(@NotNull String skillName) {
if (!pluginRef.getGeneralConfig().getLocale().equalsIgnoreCase("en_US")) {
for (PrimarySkillType type : PrimarySkillType.values()) {
if (skillName.equalsIgnoreCase(LocaleLoader.getString(
@@ -303,6 +306,28 @@ public class SkillTools {
return null;
}
/**
* Matches an array of strings of skills to skills
* This is NOT case-sensitive
* First it checks the locale file and tries to match by the localized name of the skill
* Then if nothing is found it checks against the hard coded "name" of the skill, which is just its name in English
*
* @param skills target skill names
* @return the matching PrimarySkillType if one is found, otherwise null
*/
@NotNull
public Set<PrimarySkillType> matchSkills(@NotNull Collection<String> skills) {
Set<PrimarySkillType> matchingSkills = new HashSet<>();
for (String skillName : skills) {
PrimarySkillType primarySkillType = matchSkill(skillName);
if(primarySkillType != null) {
matchingSkills.add(primarySkillType);
}
}
return matchingSkills;
}
/**
* Gets the PrimarySkillStype to which a SubSkillType belongs Return null if it does not belong
* to one.. which should be impossible in most circumstances

View File

@@ -0,0 +1,23 @@
level_up_commands:
woodcutting_and_swords_command:
enabled: true
condition:
swords:
levels: [10, 100]
woodcutting:
levels: [10, 100]
commands:
- "say {@player} reached level {@swords_level} in swords, and {@woodcutting_level} in woodcutting!"
- "say Isn't that nice?"
run_command_as: 'CONSOLE'
log_level: 'INFO'
power_level_milestones:
enabled: true
condition:
power_level:
levels: [ 1000, 2000, 3000, 4000, 5000 ]
commands:
- "say {@player} has reached a power level milestone!"
- "say {@player} is now at power level {@power_level}!"
run_command_as: 'CONSOLE'
log_level: 'DEBUG'

View File

@@ -1,19 +1,23 @@
package com.gmail.nossr50;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import com.gmail.nossr50.api.exceptions.InvalidSkillException;
import com.gmail.nossr50.commands.levelup.LevelUpCommandManager;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.ChatConfig;
import com.gmail.nossr50.config.CommandOnLevelUpConfig;
import com.gmail.nossr50.config.GeneralConfig;
import com.gmail.nossr50.config.RankConfig;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.config.party.PartyConfig;
import com.gmail.nossr50.datatypes.experience.FormulaType;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
@@ -22,9 +26,11 @@ import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.MaterialMapStore;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.TestPlayerMock;
import com.gmail.nossr50.util.TransientEntityTracker;
import com.gmail.nossr50.util.blockmeta.ChunkManager;
import com.gmail.nossr50.util.compat.CompatibilityManager;
import com.gmail.nossr50.util.experience.FormulaManager;
import com.gmail.nossr50.util.platform.MinecraftGameVersion;
import com.gmail.nossr50.util.player.NotificationManager;
import com.gmail.nossr50.util.player.UserManager;
@@ -41,19 +47,17 @@ import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.inventory.ItemFactory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.plugin.PluginManager;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
public abstract class MMOTestEnvironment {
protected MockedStatic<Bukkit> mockedBukkit;
protected MockedStatic<mcMMO> mockedMcMMO;
protected MockedStatic<ChatConfig> mockedChatConfig;
protected MockedStatic<ExperienceConfig> experienceConfig;
protected ExperienceConfig experienceConfigInstance;
protected MockedStatic<Permissions> mockedPermissions;
protected MockedStatic<RankUtils> mockedRankUtils;
protected MockedStatic<UserManager> mockedUserManager;
@@ -63,6 +67,8 @@ public abstract class MMOTestEnvironment {
protected MockedStatic<SoundManager> mockedSoundManager;
protected TransientEntityTracker transientEntityTracker;
protected AdvancedConfig advancedConfig;
protected CommandOnLevelUpConfig commandOnLevelUpConfig;
protected LevelUpCommandManager levelUpCommandManager;
protected PartyConfig partyConfig;
protected GeneralConfig generalConfig;
protected RankConfig rankConfig;
@@ -70,21 +76,10 @@ public abstract class MMOTestEnvironment {
protected Server server;
protected PluginManager pluginManager;
protected World world;
/* Mocks */
protected Player player;
protected UUID playerUUID = UUID.randomUUID();
protected ItemStack itemInMainHand;
protected PlayerInventory playerInventory;
protected PlayerProfile playerProfile;
protected McMMOPlayer mmoPlayer;
private FormulaManager formulaManager;
protected ItemFactory itemFactory;
protected ChunkManager chunkManager;
protected MaterialMapStore materialMapStore;
protected CompatibilityManager compatibilityManager;
protected void mockBaseEnvironment(Logger logger) throws InvalidSkillException {
@@ -98,6 +93,10 @@ public abstract class MMOTestEnvironment {
mcMMO.p = mock(mcMMO.class);
when(mcMMO.p.getLogger()).thenReturn(logger);
// formula manager
formulaManager = new FormulaManager(FormulaType.UNKNOWN);
when(mcMMO.p.getFormulaManager()).thenReturn(formulaManager);
// place store
chunkManager = mock(ChunkManager.class);
when(mcMMO.getUserBlockTracker()).thenReturn(chunkManager);
@@ -118,6 +117,9 @@ public abstract class MMOTestEnvironment {
// wire advanced config
mockAdvancedConfig();
// wire command level up config
mockLevelUpCommand();
// wire experience config
mockExperienceConfig();
@@ -128,8 +130,6 @@ public abstract class MMOTestEnvironment {
this.transientEntityTracker = new TransientEntityTracker();
when(mcMMO.getTransientEntityTracker()).thenReturn(transientEntityTracker);
mockPermissions();
mockedRankUtils = mockStatic(RankUtils.class);
// wire server
@@ -150,11 +150,6 @@ public abstract class MMOTestEnvironment {
when(server.getPluginManager()).thenReturn(pluginManager);
// wire Bukkit -> plugin manager
when(Bukkit.getPluginManager()).thenReturn(pluginManager);
// return the argument provided when call event is invoked on plugin manager mock
doAnswer(invocation -> {
Object[] args = invocation.getArguments();
return args[0];
}).when(pluginManager).callEvent(any(Event.class));
// wire world
this.world = mock(World.class);
@@ -164,30 +159,8 @@ public abstract class MMOTestEnvironment {
when(Misc.getBlockCenter(any(Block.class))).thenReturn(new Location(world, 0, 0, 0));
when(Misc.getBlockCenter(any(BlockState.class))).thenReturn(new Location(world, 0, 0, 0));
// setup player and player related mocks after everything else
this.player = mock(Player.class);
when(player.getUniqueId()).thenReturn(playerUUID);
when(player.isValid()).thenReturn(true);
when(player.isOnline()).thenReturn(true);
// health
when(player.getHealth()).thenReturn(20D);
// wire inventory
this.playerInventory = mock(PlayerInventory.class);
when(player.getInventory()).thenReturn(playerInventory);
// player location
Location playerLocation = mock(Location.class);
Block playerLocationBlock = mock(Block.class);
when(player.getLocation()).thenReturn(playerLocation);
when(playerLocation.getBlock()).thenReturn(playerLocationBlock);
// when(playerLocationBlock.getType()).thenReturn(Material.AIR);
// PlayerProfile and McMMOPlayer are partially mocked
playerProfile = new PlayerProfile("testPlayer", player.getUniqueId(), 0);
mmoPlayer = Mockito.spy(new McMMOPlayer(player, playerProfile));
// wire user manager
this.mockedUserManager = mockStatic(UserManager.class);
when(UserManager.getPlayer(player)).thenReturn(mmoPlayer);
this.materialMapStore = new MaterialMapStore();
when(mcMMO.getMaterialMapStore()).thenReturn(materialMapStore);
@@ -199,18 +172,15 @@ public abstract class MMOTestEnvironment {
mockedSoundManager = mockStatic(SoundManager.class);
}
private void mockPermissions() {
mockedPermissions = mockStatic(Permissions.class);
when(Permissions.isSubSkillEnabled(any(Player.class), any(SubSkillType.class))).thenReturn(
true);
when(Permissions.canUseSubSkill(any(Player.class), any(SubSkillType.class))).thenReturn(
true);
when(Permissions.isSubSkillEnabled(any(Player.class), any(SubSkillType.class))).thenReturn(
true);
when(Permissions.canUseSubSkill(any(Player.class), any(SubSkillType.class))).thenReturn(
true);
when(Permissions.lucky(player, PrimarySkillType.WOODCUTTING)).thenReturn(
false); // player is not lucky
private void mockPermissions(Player player) {
if (mockedPermissions == null) {
mockedPermissions = mockStatic(Permissions.class);
}
when(Permissions.isSubSkillEnabled(eq(player), any(SubSkillType.class))).thenReturn(true);
when(Permissions.canUseSubSkill(eq(player), any(SubSkillType.class))).thenReturn(true);
when(Permissions.isSubSkillEnabled(eq(player), any(SubSkillType.class))).thenReturn(true);
when(Permissions.canUseSubSkill(eq(player), any(SubSkillType.class))).thenReturn(true);
when(Permissions.skillEnabled(eq(player), any(PrimarySkillType.class))).thenReturn(true);
}
private void mockRankConfig() {
@@ -222,13 +192,26 @@ public abstract class MMOTestEnvironment {
when(mcMMO.p.getAdvancedConfig()).thenReturn(advancedConfig);
}
private void mockLevelUpCommand() {
this.commandOnLevelUpConfig = mock(CommandOnLevelUpConfig.class);
when(mcMMO.p.getCommandOnLevelUpConfig()).thenReturn(commandOnLevelUpConfig);
this.levelUpCommandManager = spy(new LevelUpCommandManager(mcMMO.p));
when(mcMMO.p.getLevelUpCommandManager()).thenReturn(levelUpCommandManager);
}
private void mockGeneralConfig() {
generalConfig = mock(GeneralConfig.class);
when(mcMMO.p.getGeneralConfig()).thenReturn(generalConfig);
when(generalConfig.getTreeFellerThreshold()).thenReturn(100);
when(generalConfig.getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING,
Material.OAK_LOG)).thenReturn(true);
when(generalConfig.getLocale()).thenReturn("en_US");
when(mcMMO.p.getGeneralConfig()).thenReturn(generalConfig);
// Allows pseudo functional testing of experience gains
when(generalConfig.getPowerLevelCap())
.thenReturn(Integer.MAX_VALUE);
when(generalConfig.getLevelCap(any(PrimarySkillType.class)))
.thenReturn(Integer.MAX_VALUE);
}
private void mockPartyConfig() {
@@ -239,11 +222,63 @@ public abstract class MMOTestEnvironment {
private void mockExperienceConfig() {
experienceConfig = mockStatic(ExperienceConfig.class);
experienceConfigInstance = mock(ExperienceConfig.class);
when(ExperienceConfig.getInstance()).thenReturn(experienceConfigInstance);
when(experienceConfigInstance.getFormulaType()).thenReturn(FormulaType.LINEAR);
when(experienceConfigInstance.getFormulaSkillModifier(any(PrimarySkillType.class)))
.thenReturn(1D);
when(experienceConfigInstance.getBase(any(FormulaType.class)))
.thenReturn(1000);
when(experienceConfigInstance.getExponent(any())).thenReturn(1D);
when(experienceConfigInstance.getExperienceGainsGlobalMultiplier())
.thenReturn(1D);
when(experienceConfigInstance.getMultiplier(any(FormulaType.class)))
.thenReturn(1D);
// Conversion
when(experienceConfigInstance.getExpModifier())
.thenReturn(1D);
}
when(ExperienceConfig.getInstance()).thenReturn(mock(ExperienceConfig.class));
protected TestPlayerMock mockPlayer() {
final UUID uuid = UUID.randomUUID();
return mockPlayer(uuid, uuid.toString(), 0);
}
// Combat
when(ExperienceConfig.getInstance().getCombatXP("Cow")).thenReturn(1D);
protected TestPlayerMock mockPlayer(UUID uuid, String playerName, int startingLevel) {
final Player player = mock(Player.class);
when(player.getUniqueId()).thenReturn(uuid);
when(player.isValid()).thenReturn(true);
when(player.isOnline()).thenReturn(true);
// Player name
when(player.getName()).thenReturn(playerName);
// health
when(player.getHealth()).thenReturn(20D);
// inventory
final PlayerInventory playerInventory = mock(PlayerInventory.class);
when(player.getInventory()).thenReturn(playerInventory);
// player location
final Location playerLocation = mock(Location.class);
final Block playerLocationBlock = mock(Block.class);
when(player.getLocation()).thenReturn(playerLocation);
when(playerLocation.getBlock()).thenReturn(playerLocationBlock);
// PlayerProfile and McMMOPlayer are partially mocked
final PlayerProfile playerProfile = spy(new PlayerProfile("testPlayer", player.getUniqueId(),
startingLevel));
when(playerProfile.isLoaded()).thenReturn(true);
final McMMOPlayer mmoPlayer = spy(new McMMOPlayer(player, playerProfile));
when(UserManager.getPlayer(player)).thenReturn(mmoPlayer);
// Permissions
mockPermissions(player);
// TODO: Move this to the woodcutting tests
when(Permissions.lucky(player, PrimarySkillType.WOODCUTTING)).thenReturn(
false); // player is not lucky
return new TestPlayerMock(player, playerInventory, playerLocation, playerProfile,
mmoPlayer);
}
protected void cleanUpStaticMocks() {

View File

@@ -0,0 +1,268 @@
//package com.gmail.nossr50;
//
//import static org.mockito.ArgumentMatchers.any;
//import static org.mockito.Mockito.mock;
//import static org.mockito.Mockito.when;
//
//import com.gmail.nossr50.commands.levelup.LevelUpCommandManager;
//import com.gmail.nossr50.config.AdvancedConfig;
//import com.gmail.nossr50.config.ChatConfig;
//import com.gmail.nossr50.config.CommandOnLevelUpConfig;
//import com.gmail.nossr50.config.GeneralConfig;
//import com.gmail.nossr50.config.RankConfig;
//import com.gmail.nossr50.config.experience.ExperienceConfig;
//import com.gmail.nossr50.datatypes.experience.FormulaType;
//import com.gmail.nossr50.datatypes.player.McMMOPlayer;
//import com.gmail.nossr50.datatypes.player.PlayerProfile;
//import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
//import com.gmail.nossr50.datatypes.skills.SubSkillType;
//import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent;
//import com.gmail.nossr50.events.experience.McMMOPlayerPreXpGainEvent;
//import com.gmail.nossr50.listeners.SelfListener;
//import com.gmail.nossr50.util.EventUtils;
//import com.gmail.nossr50.util.Misc;
//import com.gmail.nossr50.util.Permissions;
//import com.gmail.nossr50.util.TransientEntityTracker;
//import com.gmail.nossr50.util.blockmeta.ChunkManager;
//import com.gmail.nossr50.util.experience.FormulaManager;
//import com.gmail.nossr50.util.player.NotificationManager;
//import com.gmail.nossr50.util.player.UserManager;
//import com.gmail.nossr50.util.skills.RankUtils;
//import com.gmail.nossr50.util.skills.SkillTools;
//import java.util.UUID;
//import org.bukkit.Bukkit;
//import org.bukkit.Server;
//import org.bukkit.World;
//import org.bukkit.command.ConsoleCommandSender;
//import org.bukkit.entity.EntityType;
//import org.bukkit.entity.Player;
//import org.bukkit.inventory.PlayerInventory;
//import org.bukkit.plugin.PluginManager;
//import org.junit.jupiter.api.AfterEach;
//import org.junit.jupiter.api.BeforeEach;
//import org.mockito.MockedStatic;
//import org.mockito.Mockito;
//
//public abstract class MMOTestEnvironmentBasic {
// private final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(
// MMOTestEnvironmentBasic.class.getName());
// protected MockedStatic<mcMMO> mockedMcMMO;
// protected MockedStatic<Bukkit> mockedBukkit;
// protected MockedStatic<ChatConfig> mockedChatConfig;
// protected MockedStatic<ExperienceConfig> experienceConfig;
// private MockedStatic<NotificationManager> mockedNotificationManager;
// protected MockedStatic<Permissions> mockedPermissions;
// protected MockedStatic<RankUtils> mockedRankUtils;
// protected MockedStatic<UserManager> mockedUserManager;
// protected MockedStatic<Misc> mockedMisc;
// protected MockedStatic<EventUtils> mockedEventUtils;
// protected SelfListener selfListener;
// protected TransientEntityTracker transientEntityTracker;
// protected AdvancedConfig advancedConfig;
// protected CommandOnLevelUpConfig commandOnLevelUpConfig;
// protected LevelUpCommandManager levelUpCommandManager;
// protected GeneralConfig generalConfig;
// protected RankConfig rankConfig;
// protected SkillTools skillTools;
// protected Server mockedServer;
// protected PluginManager pluginManager;
// protected World world;
//
// private FormulaManager formulaManager;
//
// /* Mocks */
// protected PlayerInventory playerInventory;
//
// protected ChunkManager chunkManager;
//
// protected ConsoleCommandSender consoleCommandSender;
//
// @BeforeEach
// void setUp() {
// mockBaseEnvironment();
// }
//
// @AfterEach
// void tearDown() {
// cleanupBaseEnvironment();
// }
//
// protected void mockBaseEnvironment() {
// mockedMcMMO = Mockito.mockStatic(mcMMO.class);
// mcMMO.p = mock(mcMMO.class);
// when(mcMMO.p.getLogger()).thenReturn(logger);
//
// // formula manager
// formulaManager = new FormulaManager(FormulaType.UNKNOWN);
// when(mcMMO.p.getFormulaManager()).thenReturn(formulaManager);
//
// // place store
// chunkManager = mock(ChunkManager.class);
// when(mcMMO.getPlaceStore()).thenReturn(chunkManager);
//
// // shut off mod manager for woodcutting
// when(mcMMO.getModManager()).thenReturn(mock(ModManager.class));
// when(mcMMO.getModManager().isCustomLog(any())).thenReturn(false);
//
// // chat config
// mockedChatConfig = Mockito.mockStatic(ChatConfig.class);
// when(ChatConfig.getInstance()).thenReturn(mock(ChatConfig.class));
//
// // general config
// mockGeneralConfig();
//
// // rank config
// mockRankConfig();
//
// // wire advanced config
// mockAdvancedConfig();
//
// // wire command level up config
// mockLevelUpCommand();
//
// // wire experience config
// mockExperienceConfig();
//
// // wire skill tools
// this.skillTools = Mockito.spy(new SkillTools(mcMMO.p));
// when(mcMMO.p.getSkillTools()).thenReturn(skillTools);
//
// this.transientEntityTracker = new TransientEntityTracker();
// when(mcMMO.getTransientEntityTracker()).thenReturn(transientEntityTracker);
//
// mockPermissions();
//
// mockNotifications();
//
// mockedRankUtils = Mockito.mockStatic(RankUtils.class);
//
// // wire server
// this.mockedServer = mock(Server.class);
// when(mcMMO.p.getServer()).thenReturn(mockedServer);
//
// // wire plugin manager
// this.pluginManager = mock(PluginManager.class);
// when(mockedServer.getPluginManager()).thenReturn(pluginManager);
// // Process level up events in our self listener
// Mockito.doAnswer(invocation -> {
// selfListener.onPlayerLevelUp(invocation.getArgument(0));
// return null;
// }).when(pluginManager).callEvent(any(McMMOPlayerLevelUpEvent.class));
//
// // Don't process pre-gain events
// Mockito.doAnswer((ignored) -> null).when(pluginManager)
// .callEvent(any(McMMOPlayerPreXpGainEvent.class));
//
// // wire world
// this.world = mock(World.class);
//
// // wire Misc
// this.mockedMisc = Mockito.mockStatic(Misc.class);
// // Mockito.when(Misc.getBlockCenter(any())).thenReturn(new Location(world, 0, 0, 0));
//
// // wire user manager
// this.mockedUserManager = Mockito.mockStatic(UserManager.class);
//
// // Self listener
// selfListener = Mockito.spy(new SelfListener(mcMMO.p));
//
// // Console command sender
// consoleCommandSender = mock(ConsoleCommandSender.class);
// when(consoleCommandSender.getName()).thenReturn("CONSOLE");
// mockedBukkit = Mockito.mockStatic(Bukkit.class);
// when(Bukkit.getConsoleSender()).thenReturn(consoleCommandSender);
// }
//
// private void mockPermissions() {
// mockedPermissions = Mockito.mockStatic(Permissions.class);
// when(Permissions.isSubSkillEnabled(any(Player.class), any(SubSkillType.class))).thenReturn(
// true);
// when(Permissions.isSubSkillEnabled(any(Player.class), any(SubSkillType.class))).thenReturn(
// true);
// when(Permissions.skillEnabled(any(Player.class), any(PrimarySkillType.class))).thenReturn(
// true);
// }
//
// private void mockNotifications() {
// mockedNotificationManager = Mockito.mockStatic(NotificationManager.class);
// }
//
// private void mockRankConfig() {
// rankConfig = mock(RankConfig.class);
// }
//
// private void mockAdvancedConfig() {
// this.advancedConfig = mock(AdvancedConfig.class);
// when(mcMMO.p.getAdvancedConfig()).thenReturn(advancedConfig);
// }
//
// private void mockLevelUpCommand() {
// this.commandOnLevelUpConfig = mock(CommandOnLevelUpConfig.class);
// when(mcMMO.p.getCommandOnLevelUpConfig()).thenReturn(commandOnLevelUpConfig);
//
// this.levelUpCommandManager = Mockito.spy(new LevelUpCommandManager(mcMMO.p));
// when(mcMMO.p.getLevelUpCommandManager()).thenReturn(levelUpCommandManager);
// }
//
// private void mockGeneralConfig() {
// generalConfig = mock(GeneralConfig.class);
// when(generalConfig.getLocale()).thenReturn("en_US");
// when(mcMMO.p.getGeneralConfig()).thenReturn(generalConfig);
//
// // Experience related
// when(generalConfig.getLevelCap(any(PrimarySkillType.class))).thenReturn(Integer.MAX_VALUE);
// when(generalConfig.getPowerLevelCap()).thenReturn(Integer.MAX_VALUE);
// }
//
// private void mockExperienceConfig() {
// experienceConfig = Mockito.mockStatic(ExperienceConfig.class);
//
// when(ExperienceConfig.getInstance()).thenReturn(mock(ExperienceConfig.class));
//
// // Combat
// when(ExperienceConfig.getInstance().getCombatXP(EntityType.COW)).thenReturn(1D);
// when(ExperienceConfig.getInstance().getFormulaType()).thenReturn(FormulaType.LINEAR);
// when(ExperienceConfig.getInstance().getBase(FormulaType.LINEAR)).thenReturn(1020);
// when(ExperienceConfig.getInstance().getMultiplier(FormulaType.LINEAR)).thenReturn(20D);
// when(ExperienceConfig.getInstance()
// .getFormulaSkillModifier(any(PrimarySkillType.class))).thenReturn(1D);
// when(ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()).thenReturn(1D);
// when(ExperienceConfig.getInstance().getExpModifier()).thenReturn(1D);
// }
//
// protected void cleanupBaseEnvironment() {
// // Clean up resources here if needed.
// if (mockedMcMMO != null) {
// mockedMcMMO.close();
// }
// if (mockedBukkit != null) {
// mockedBukkit.close();
// }
// if (experienceConfig != null) {
// experienceConfig.close();
// }
// if (mockedChatConfig != null) {
// mockedChatConfig.close();
// }
// if (mockedPermissions != null) {
// mockedPermissions.close();
// }
// if (mockedRankUtils != null) {
// mockedRankUtils.close();
// }
// if (mockedUserManager != null) {
// mockedUserManager.close();
// }
// if (mockedMisc != null) {
// mockedMisc.close();
// }
// if (mockedEventUtils != null) {
// mockedEventUtils.close();
// }
// if (mockedNotificationManager != null) {
// mockedNotificationManager.close();
// }
// }
//
//
//}

View File

@@ -0,0 +1,454 @@
package com.gmail.nossr50.commands.levelup;
import static com.gmail.nossr50.datatypes.skills.PrimarySkillType.MINING;
import static com.gmail.nossr50.datatypes.skills.PrimarySkillType.WOODCUTTING;
import static java.util.Objects.requireNonNull;
import static java.util.logging.Logger.getLogger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import com.gmail.nossr50.MMOTestEnvironment;
import com.gmail.nossr50.datatypes.experience.XPGainReason;
import com.gmail.nossr50.datatypes.experience.XPGainSource;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent;
import com.gmail.nossr50.events.experience.McMMOPlayerPreXpGainEvent;
import com.gmail.nossr50.events.experience.McMMOPlayerXpGainEvent;
import com.gmail.nossr50.listeners.SelfListener;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.TestPlayerMock;
import java.util.List;
import java.util.UUID;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class LevelUpCommandTest extends MMOTestEnvironment {
private static final Logger logger = getLogger(LevelUpCommandTest.class.getName());
private static final BiPredicate<PrimarySkillType, Integer> ALWAYS_TRUE = (skill, level) -> true;
private static final String DEFAULT_PLAYER_NAME = "Momshroom";
private SelfListener selfListener;
@BeforeEach
void beforeEach() {
mockBaseEnvironment(logger);
mcMMO.p.getLevelUpCommandManager().getLevelUpCommands().clear();
// Self listener
selfListener = Mockito.spy(new SelfListener(mcMMO.p));
// Process level up events in our self listener
Mockito.doAnswer(invocation -> {
selfListener.onPlayerLevelUp(invocation.getArgument(0));
return null;
}).when(pluginManager).callEvent(any(McMMOPlayerLevelUpEvent.class));
Mockito.doAnswer(invocation -> {
selfListener.onPlayerXpGain(invocation.getArgument(0));
return null;
}).when(pluginManager).callEvent(any(McMMOPlayerXpGainEvent.class));
Mockito.doAnswer(invocation -> {
return invocation.getArgument(0);
}).when(pluginManager).callEvent(any(McMMOPlayerPreXpGainEvent.class));
}
@AfterEach
void tearDown() {
cleanUpStaticMocks();
}
@Test
void skillLevelUpShouldRunFiveTimes() {
final TestPlayerMock testPlayerMock = mockPlayer(UUID.randomUUID(), DEFAULT_PLAYER_NAME, 0);
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
// GIVEN level up command for Mining should always execute for Mining level up
final String commandStr = "say hello";
final LevelUpCommand levelUpCommand = buildLevelUpCommand(commandStr,
(skill, skillLevel) -> skill == MINING && skillLevel >= 1 && skillLevel <= 5);
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommand);
// WHEN player gains 5 levels in mining via command
levelPlayerViaXP(mmoPlayer, MINING, 5);
// THEN the command should be checked for execution
verify(levelUpCommandManager, atLeastOnce()).applySkillLevelUp(any(), any(), any(), any());
verify(levelUpCommand, atLeastOnce()).process(any(), any(), any(), any());
// THEN the command should have executed
verify(levelUpCommand, times(5)).executeCommand(any(McMMOPlayer.class));
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), any()), atLeast(5));
}
// @Test
// void dualRequirementsShouldRunOnce() {
// // GIVEN
// final TestPlayerMock testPlayerMock = mockPlayer(UUID.randomUUID(), DEFAULT_PLAYER_NAME, 0);
// final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
// final String commandStr = "say hello";
// BiPredicate<PrimarySkillType, Integer> predicate = (skill, skillLevel) -> skill == MINING
// && skillLevel == 3;
// BiPredicate<PrimarySkillType, Integer> predicate2 = (skill, skillLevel) ->
// skill == WOODCUTTING && skillLevel == 3;
// final LevelUpCommand levelUpCommand = buildLevelUpCommand(commandStr,
// List.of(predicate, predicate2));
//
// mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommand);
//
// // WHEN player gains 5 levels in mining and woodcutting via command
// levelPlayerViaXP(mmoPlayer, MINING, 5);
// levelPlayerViaXP(mmoPlayer, WOODCUTTING, 5);
//
// // THEN the command should be checked for execution
// verify(levelUpCommandManager, times(10)).applySkillLevelUp(any(), any(), any(), any());
// verify(levelUpCommand, times(10)).process(any(), any(), any(), any());
//
// // THEN the command should have executed
// verify(levelUpCommand, times(1)).executeCommand(any(McMMOPlayer.class));
// mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), any()), atLeast(1));
// }
@Test
void skillLevelUpViaXPGainShouldRunFiveTimes() {
// GIVEN level up command for Mining should always execute for Mining level up
final TestPlayerMock testPlayerMock = mockPlayer(UUID.randomUUID(), DEFAULT_PLAYER_NAME, 0);
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
final String commandStr = "say hello";
final LevelUpCommand levelUpCommand = buildLevelUpCommand(commandStr,
(skill, skillLevel) -> skill == MINING && skillLevel >= 1 && skillLevel <= 5);
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommand);
// WHEN player gains 5 levels in mining via command
levelPlayerViaXP(mmoPlayer, MINING, 5);
// THEN the command should be checked for execution
verify(levelUpCommandManager, times(5)).applySkillLevelUp(any(), any(), any(), any());
verify(levelUpCommand, times(5)).process(any(), any(), any(), any());
// THEN the command should have executed
verify(levelUpCommand, times(5)).executeCommand(any(McMMOPlayer.class));
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), any()), atLeast(5));
}
@Test
void skillLevelUpViaXPGainShouldRunCommandFiveTimesWithPlaceholders() {
final TestPlayerMock testPlayerMock = mockPlayer(UUID.randomUUID(), DEFAULT_PLAYER_NAME, 0);
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
// GIVEN level up command for Mining should always execute for Mining level up
final String commandStr = "say hello {@player}, you have reached level {@mining_level}";
final String expectedStr1 =
"say hello " + DEFAULT_PLAYER_NAME + ", you have reached level 1";
final String expectedStr2 =
"say hello " + DEFAULT_PLAYER_NAME + ", you have reached level 2";
final String expectedStr3 =
"say hello " + DEFAULT_PLAYER_NAME + ", you have reached level 3";
final String expectedStr4 =
"say hello " + DEFAULT_PLAYER_NAME + ", you have reached level 4";
final String expectedStr5 =
"say hello " + DEFAULT_PLAYER_NAME + ", you have reached level 5";
final LevelUpCommand levelUpCommand = buildLevelUpCommand(commandStr,
(skill, skillLevel) -> skill == MINING && skillLevel >= 1 && skillLevel <= 5);
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommand);
// WHEN player gains 5 levels in mining via command
assertEquals(0, mmoPlayer.getSkillLevel(MINING));
int levelsGained = 5;
levelPlayerViaXP(mmoPlayer, MINING, levelsGained);
// THEN the command should be checked for execution
verify(levelUpCommandManager, times(levelsGained)).applySkillLevelUp(any(), any(), any(),
any());
verify(levelUpCommand, times(levelsGained)).process(any(), any(), any(), any());
// THEN the command should have executed
verify(levelUpCommand, times(levelsGained)).executeCommand(any(McMMOPlayer.class));
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), any()), atLeast(5));
// AND THEN the message for each level up should have happened at least once
// verify that Bukkit.dispatchCommand got executed at least 5 times with the correct injectedCommand
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), eq(expectedStr1)));
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), eq(expectedStr2)));
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), eq(expectedStr3)));
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), eq(expectedStr4)));
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), eq(expectedStr5)));
}
@Test
void skillLevelUpShouldRunCommandThreeTimesWithPlaceholders() {
/*
This test executes a player leveling up 5 times.
With level 3 separate registered level up commands.
Each registered command runs only once.
*/
// GIVEN level up command for Mining should always execute for Mining level up
final TestPlayerMock testPlayerMock = mockPlayer(UUID.randomUUID(), DEFAULT_PLAYER_NAME, 0);
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
final String commandStr = "say hello {@player}";
final String expectedStr = "say hello " + DEFAULT_PLAYER_NAME;
final LevelUpCommand levelUpCommandOne = buildLevelUpCommand(commandStr,
(skill, level) -> skill == MINING && level == 1);
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommandOne);
final LevelUpCommand levelUpCommandTwo = buildLevelUpCommand(commandStr,
(skill, level) -> skill == MINING && level == 2);
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommandTwo);
final LevelUpCommand levelUpCommandThree = buildLevelUpCommand(commandStr,
(skill, level) -> skill == MINING && level == 3);
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommandThree);
int levelsGained = 5;
// WHEN player gains 5 levels in mining
levelPlayerViaXP(mmoPlayer, MINING, levelsGained);
// THEN the command should be checked for execution
verify(levelUpCommandManager, times(levelsGained)).applySkillLevelUp(any(), any(), any(),
any());
verify(levelUpCommandOne, times(levelsGained)).process(any(), any(), any(), any());
verify(levelUpCommandTwo, times(levelsGained)).process(any(), any(), any(), any());
verify(levelUpCommandThree, times(levelsGained)).process(any(), any(), any(), any());
// THEN the command should have executed
verify(levelUpCommandOne, times(1)).executeCommand(any(McMMOPlayer.class));
verify(levelUpCommandTwo, times(1)).executeCommand(any(McMMOPlayer.class));
verify(levelUpCommandThree, times(1)).executeCommand(any(McMMOPlayer.class));
// verify that Bukkit.dispatchCommand got executed at least 20 times with the correct injectedCommand
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), eq(expectedStr)), atLeast(3));
}
@Test
void skillLevelUpShouldRunCommandFourTimesWithPlaceholders() {
/*
This test executes a player leveling up 5 times.
With level 3 separate registered level up commands.
One command runs twice, the others run once.
*/
// GIVEN level up command for Mining should always execute for Mining level up
final TestPlayerMock testPlayerMock = mockPlayer(UUID.randomUUID(), DEFAULT_PLAYER_NAME, 0);
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
final String commandStr = "say hello {@player}";
final String expectedStr = "say hello " + DEFAULT_PLAYER_NAME;
final LevelUpCommand levelUpCommandOne = buildLevelUpCommand(commandStr,
(skill, level) -> skill == MINING && (level == 1 || level == 4));
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommandOne);
final LevelUpCommand levelUpCommandTwo = buildLevelUpCommand(commandStr,
(skill, level) -> skill == MINING && level == 2);
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommandTwo);
final LevelUpCommand levelUpCommandThree = buildLevelUpCommand(commandStr,
(skill, level) -> skill == MINING && level == 3);
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommandThree);
int levelsGained = 5;
// WHEN player gains 5 levels in mining
levelPlayerViaXP(mmoPlayer, MINING, levelsGained);
// THEN the command should be checked for execution
verify(levelUpCommandManager, times(levelsGained)).applySkillLevelUp(any(), any(), any(),
any());
verify(levelUpCommandOne, times(levelsGained)).process(any(), any(), any(), any());
verify(levelUpCommandTwo, times(levelsGained)).process(any(), any(), any(), any());
verify(levelUpCommandThree, times(levelsGained)).process(any(), any(), any(), any());
// THEN the command should have executed
verify(levelUpCommandOne, times(2)).executeCommand(any(McMMOPlayer.class));
verify(levelUpCommandTwo, times(1)).executeCommand(any(McMMOPlayer.class));
verify(levelUpCommandThree, times(1)).executeCommand(any(McMMOPlayer.class));
// verify that Bukkit.dispatchCommand got executed at least 20 times with the correct injectedCommand
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), eq(expectedStr)), atLeast(3));
}
@Test
void addLevelsShouldRunCommandFiveTimesWithPlaceholdersForLevel() {
// GIVEN level up command for Mining should always execute for Mining level up
final TestPlayerMock testPlayerMock = mockPlayer(UUID.randomUUID(), DEFAULT_PLAYER_NAME, 0);
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
final String commandStr = "say hello {@player}, you have reached level {@mining_level}";
final String expectedStr1 =
"say hello " + DEFAULT_PLAYER_NAME + ", you have reached level 1";
final String expectedStr2 =
"say hello " + DEFAULT_PLAYER_NAME + ", you have reached level 2";
final String expectedStr3 =
"say hello " + DEFAULT_PLAYER_NAME + ", you have reached level 3";
final String expectedStr4 =
"say hello " + DEFAULT_PLAYER_NAME + ", you have reached level 4";
final String expectedStr5 =
"say hello " + DEFAULT_PLAYER_NAME + ", you have reached level 5";
final LevelUpCommand levelUpCommand = buildLevelUpCommand(commandStr,
(skill, ignored) -> skill == MINING);
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommand);
// WHEN player gains 5 levels in mining
int levelsGained = 5;
levelPlayerViaXP(mmoPlayer, MINING, levelsGained);
// THEN the command should be checked for execution
verify(levelUpCommandManager, times(levelsGained))
.applySkillLevelUp(any(), any(), any(), any());
verify(levelUpCommand, times(levelsGained))
.process(any(), any(), any(), any());
// THEN the command should have executed
verify(levelUpCommand, times(levelsGained))
.executeCommand(any(McMMOPlayer.class));
// verify that Bukkit.dispatchCommand got executed at least 5 times with the correct injectedCommand
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), eq(expectedStr1)), atLeastOnce());
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), eq(expectedStr2)), atLeastOnce());
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), eq(expectedStr3)), atLeastOnce());
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), eq(expectedStr4)), atLeastOnce());
mockedBukkit.verify(() -> Bukkit.dispatchCommand(any(), eq(expectedStr5)), atLeastOnce());
}
@Test
void skillLevelUpShouldRunCommandAtLeastOnce() {
// GIVEN level up command for Mining should always execute for Mining level up
final TestPlayerMock testPlayerMock = mockPlayer(UUID.randomUUID(), DEFAULT_PLAYER_NAME, 0);
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
final String commandStr = "say hello";
final LevelUpCommand levelUpCommand = buildLevelUpCommand(commandStr,
(skill, ignored) -> skill == MINING);
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommand);
int levelsGained = 1;
// WHEN player gains 5 levels in mining
McMMOPlayerLevelUpEvent event = new McMMOPlayerLevelUpEvent(mmoPlayer.getPlayer(), MINING,
levelsGained, XPGainReason.PVE);
selfListener.onPlayerLevelUp(event);
// THEN the command should be checked for execution
verify(levelUpCommandManager).applySkillLevelUp(any(), any(), any(), any());
verify(levelUpCommand).process(any(), any(), any(), any());
// THEN the command should have executed
verify(levelUpCommand).executeCommand(any(McMMOPlayer.class));
}
@Test
void skillLevelUpShouldNotRunCommand() {
// GIVEN level up command for Woodcutting should not execute for Mining level up
final TestPlayerMock testPlayerMock = mockPlayer(UUID.randomUUID(), DEFAULT_PLAYER_NAME, 0);
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
final String commandStr = "say hello";
final LevelUpCommand levelUpCommand = buildLevelUpCommand(commandStr,
(skill, ignored) -> skill == WOODCUTTING);
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommand);
int levelsGained = 5;
// WHEN player gains 5 levels in mining
McMMOPlayerLevelUpEvent event = new McMMOPlayerLevelUpEvent(mmoPlayer.getPlayer(), MINING,
levelsGained, XPGainReason.PVE);
selfListener.onPlayerLevelUp(event);
// THEN the command should be checked for execution
verify(levelUpCommandManager).applySkillLevelUp(any(), any(), any(), any());
verify(levelUpCommand).process(any(), any(), any(), any());
// THEN the command should not be run
verify(levelUpCommand, never()).executeCommand(any(McMMOPlayer.class));
}
@Test
public void levelUpShouldAlwaysRunCommand() {
// GIVEN level up command should always execute for any level up
final TestPlayerMock testPlayerMock = mockPlayer(UUID.randomUUID(), DEFAULT_PLAYER_NAME, 0);
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
final String commandStr = "say hello";
final LevelUpCommand levelUpCommand = buildLevelUpCommand(commandStr, ALWAYS_TRUE);
mcMMO.p.getLevelUpCommandManager().registerCommand(levelUpCommand);
// WHEN player gains 10 levels
levelPlayerViaXP(mmoPlayer, MINING, 10);
// THEN the command should be checked for execution
verify(levelUpCommandManager, atLeastOnce()).applySkillLevelUp(any(), eq(MINING), any(),
any());
verify(levelUpCommand, atLeastOnce()).process(any(), any(), any(), any());
// THEN the command should have executed
verify(levelUpCommand, times(10)).executeCommand(any(McMMOPlayer.class));
}
@Test
public void skillLevelUpShouldRunPowerlevelCommandOnce() {
// GIVEN level up command for power level should always execute for any level up
final TestPlayerMock testPlayerMock = mockPlayer(UUID.randomUUID(), DEFAULT_PLAYER_NAME, 0);
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
final String commandStr = "say hello";
final LevelUpCommand powerLevelUpCommand = buildLevelUpCommand(commandStr,
(ignoredA, ignoredB) -> true, (powerlevel) -> powerlevel == 3);
mcMMO.p.getLevelUpCommandManager().registerCommand(powerLevelUpCommand);
// WHEN player gains 5 levels
levelPlayerViaXP(mmoPlayer, MINING, 5);
// THEN the command should be checked for execution
verify(levelUpCommandManager, atLeastOnce()).applySkillLevelUp(any(), any(), any(), any());
verify(powerLevelUpCommand, atLeastOnce()).process(any(), any(), any(), any());
// THEN the command should have executed
verify(powerLevelUpCommand, times(1)).executeCommand(any(McMMOPlayer.class));
}
private LevelUpCommand buildLevelUpCommand(@NotNull String commandStr,
@NotNull List<BiPredicate<PrimarySkillType, Integer>> conditions,
@Nullable Predicate<Integer> powerLevelCondition) {
requireNonNull(commandStr, "commandStr cannot be null");
requireNonNull(conditions, "conditions cannot be null");
final var builder = new LevelUpCommandBuilder();
if (powerLevelCondition != null) {
builder.withPowerLevelCondition(powerLevelCondition);
}
builder.command(commandStr)
.withConditions(conditions)
.withLogInfo(true);
return Mockito.spy(builder.build());
}
private LevelUpCommand buildLevelUpCommand(@NotNull String commandStr,
@NotNull List<BiPredicate<PrimarySkillType, Integer>> conditions) {
return buildLevelUpCommand(commandStr, conditions, null);
}
private LevelUpCommand buildLevelUpCommand(@NotNull String commandStr,
@NotNull BiPredicate<PrimarySkillType, Integer> predicate,
@Nullable Predicate<Integer> powerLevelCondition) {
requireNonNull(commandStr, "commandStr cannot be null");
requireNonNull(predicate, "predicate cannot be null");
final var builder = new LevelUpCommandBuilder();
if (powerLevelCondition != null) {
builder.withPowerLevelCondition(powerLevelCondition);
}
builder.command(commandStr)
.withPredicate(predicate)
.withLogInfo(true);
return Mockito.spy(builder.build());
}
private LevelUpCommand buildLevelUpCommand(@NotNull String commandStr,
@NotNull BiPredicate<PrimarySkillType, Integer> predicate) {
return buildLevelUpCommand(commandStr, predicate, null);
}
private void levelPlayerViaXP(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType skill,
int levelsGained) {
System.out.println("Leveling " + mmoPlayer.getPlayer().getName() + " up " + levelsGained
+ " levels in " + skill.getName());
assertEquals(0, mmoPlayer.getSkillLevel(skill));
for (int i = 0; i < levelsGained; i++) {
mmoPlayer.applyXpGain(skill, mmoPlayer.getProfile().getXpToLevel(skill),
XPGainReason.COMMAND, XPGainSource.COMMAND);
}
assertEquals(levelsGained, mmoPlayer.getSkillLevel(skill));
}
}

View File

@@ -16,6 +16,7 @@ import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.party.PartyLeader;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.TestPlayerMock;
import com.gmail.nossr50.util.player.NotificationManager;
import com.gmail.nossr50.util.player.UserManager;
import java.util.ArrayList;
@@ -144,6 +145,8 @@ class PartyManagerTest extends MMOTestEnvironment {
@Test
public void checkPartyExistenceReturnsTrueIfExists() {
final TestPlayerMock testPlayerMock = mockPlayer();
final Player player = testPlayerMock.player();
PartyManager partyManager = new PartyManager(mcMMO.p);
Party party = Mockito.mock(Party.class);

View File

@@ -11,13 +11,16 @@ import static org.mockito.Mockito.when;
import com.gmail.nossr50.MMOTestEnvironment;
import com.gmail.nossr50.api.exceptions.InvalidSkillException;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill;
import com.gmail.nossr50.datatypes.skills.subskills.acrobatics.Roll;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.TestPlayerMock;
import com.gmail.nossr50.util.skills.RankUtils;
import java.util.logging.Logger;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageEvent;
import org.jetbrains.annotations.NotNull;
@@ -62,9 +65,11 @@ class AcrobaticsTest extends MMOTestEnvironment {
@Test
public void rollShouldLowerDamage() {
// Given
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
final Roll roll = new Roll();
final double damage = 2D;
final EntityDamageEvent mockEvent = mockEntityDamageEvent(damage);
final EntityDamageEvent mockEvent = mockEntityDamageEvent(testPlayerMock.player(), damage);
mmoPlayer.modifySkill(PrimarySkillType.ACROBATICS, 1000);
when(roll.canRoll(mmoPlayer)).thenReturn(true);
assertThat(roll.canRoll(mmoPlayer)).isTrue();
@@ -80,9 +85,11 @@ class AcrobaticsTest extends MMOTestEnvironment {
@Test
public void rollShouldNotLowerDamage() {
// Given
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
final Roll roll = new Roll();
final double damage = 100D;
final EntityDamageEvent mockEvent = mockEntityDamageEvent(damage);
final EntityDamageEvent mockEvent = mockEntityDamageEvent(testPlayerMock.player(), damage);
mmoPlayer.modifySkill(PrimarySkillType.ACROBATICS, 0);
when(roll.canRoll(mmoPlayer)).thenReturn(true);
assertThat(roll.canRoll(mmoPlayer)).isTrue();
@@ -95,7 +102,7 @@ class AcrobaticsTest extends MMOTestEnvironment {
verify(mockEvent, Mockito.never()).setDamage(any(Double.class));
}
private @NotNull EntityDamageEvent mockEntityDamageEvent(double damage) {
private @NotNull EntityDamageEvent mockEntityDamageEvent(Entity player, double damage) {
final EntityDamageEvent mockEvent = mock(EntityDamageEvent.class);
when(mockEvent.isApplicable(any(EntityDamageEvent.DamageModifier.class))).thenReturn(true);
when(mockEvent.getCause()).thenReturn(EntityDamageEvent.DamageCause.FALL);

View File

@@ -10,9 +10,11 @@ import static org.mockito.Mockito.when;
import com.gmail.nossr50.MMOTestEnvironment;
import com.gmail.nossr50.api.exceptions.InvalidSkillException;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.datatypes.treasure.ExcavationTreasure;
import com.gmail.nossr50.util.TestPlayerMock;
import com.gmail.nossr50.util.skills.RankUtils;
import java.util.ArrayList;
import java.util.List;
@@ -48,14 +50,6 @@ class ExcavationTest extends MMOTestEnvironment {
eq(SubSkillType.EXCAVATION_ARCHAEOLOGY))).thenReturn(true);
when(RankUtils.hasReachedRank(eq(1), any(Player.class),
eq(SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER))).thenReturn(true);
// setup player and player related mocks after everything else
this.player = Mockito.mock(Player.class);
when(player.getUniqueId()).thenReturn(playerUUID);
// wire inventory
this.itemInMainHand = new ItemStack(Material.DIAMOND_SHOVEL);
when(playerInventory.getItemInMainHand()).thenReturn(itemInMainHand);
}
@AfterEach
@@ -65,6 +59,10 @@ class ExcavationTest extends MMOTestEnvironment {
@Test
void excavationShouldHaveTreasureDrops() {
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(testPlayerMock.playerInventory().getItemInMainHand())
.thenReturn(new ItemStack(Material.DIAMOND_SHOVEL));
mmoPlayer.modifySkill(PrimarySkillType.EXCAVATION, 1000);
// Wire block
@@ -83,6 +81,10 @@ class ExcavationTest extends MMOTestEnvironment {
@Test
void excavationShouldNotDropTreasure() {
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(testPlayerMock.playerInventory().getItemInMainHand())
.thenReturn(new ItemStack(Material.DIAMOND_SHOVEL));
mmoPlayer.modifySkill(PrimarySkillType.EXCAVATION, 1000);
// Wire block

View File

@@ -1,43 +1,43 @@
package com.gmail.nossr50.skills.tridents;
import static java.util.logging.Logger.getLogger;
import com.gmail.nossr50.MMOTestEnvironment;
import com.gmail.nossr50.api.exceptions.InvalidSkillException;
import java.util.logging.Logger;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.Mockito;
class TridentsTest extends MMOTestEnvironment {
private static final Logger logger = getLogger(TridentsTest.class.getName());
TridentsManager tridentsManager;
ItemStack trident;
@BeforeEach
void setUp() throws InvalidSkillException {
mockBaseEnvironment(logger);
// setup player and player related mocks after everything else
this.player = Mockito.mock(Player.class);
Mockito.when(player.getUniqueId()).thenReturn(playerUUID);
// wire inventory
this.playerInventory = Mockito.mock(PlayerInventory.class);
this.trident = new ItemStack(Material.TRIDENT);
Mockito.when(playerInventory.getItemInMainHand()).thenReturn(trident);
// Set up spy for manager
tridentsManager = Mockito.spy(new TridentsManager(mmoPlayer));
}
@AfterEach
void tearDown() {
cleanUpStaticMocks();
}
}
//package com.gmail.nossr50.skills.tridents;
//
//import static java.util.logging.Logger.getLogger;
//
//import com.gmail.nossr50.MMOTestEnvironment;
//import com.gmail.nossr50.api.exceptions.InvalidSkillException;
//import java.util.logging.Logger;
//import org.bukkit.Material;
//import org.bukkit.entity.Player;
//import org.bukkit.inventory.ItemStack;
//import org.bukkit.inventory.PlayerInventory;
//import org.junit.jupiter.api.AfterEach;
//import org.junit.jupiter.api.BeforeEach;
//import org.mockito.Mockito;
//
//class TridentsTest extends MMOTestEnvironment {
// private static final Logger logger = getLogger(TridentsTest.class.getName());
//
// TridentsManager tridentsManager;
// ItemStack trident;
//
// @BeforeEach
// void setUp() throws InvalidSkillException {
// mockBaseEnvironment(logger);
//
// // setup player and player related mocks after everything else
// this.player = Mockito.mock(Player.class);
// Mockito.when(player.getUniqueId()).thenReturn(playerUUID);
//
// // wire inventory
// this.playerInventory = Mockito.mock(PlayerInventory.class);
// this.trident = new ItemStack(Material.TRIDENT);
// Mockito.when(playerInventory.getItemInMainHand()).thenReturn(trident);
//
// // Set up spy for manager
// tridentsManager = Mockito.spy(new TridentsManager(mmoPlayer));
// }
//
// @AfterEach
// void tearDown() {
// cleanUpStaticMocks();
// }
//}

View File

@@ -9,14 +9,17 @@ import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
import com.gmail.nossr50.MMOTestEnvironment;
import com.gmail.nossr50.api.exceptions.InvalidSkillException;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.BlockUtils;
import com.gmail.nossr50.util.TestPlayerMock;
import com.gmail.nossr50.util.skills.RankUtils;
import java.lang.reflect.Field;
import java.util.ArrayList;
@@ -40,15 +43,13 @@ import org.mockito.Mockito;
class WoodcuttingTest extends MMOTestEnvironment {
private static final Logger logger = getLogger(WoodcuttingTest.class.getName());
private WoodcuttingManager woodcuttingManager;
@BeforeEach
void setUp() throws InvalidSkillException {
mockBaseEnvironment(logger);
// TODO: can move the rest of these to a beforeAll
Mockito.when(rankConfig.getSubSkillUnlockLevel(SubSkillType.WOODCUTTING_HARVEST_LUMBER, 1))
.thenReturn(1);
// wire advanced config
Mockito.when(advancedConfig.getMaximumProbability(SubSkillType.WOODCUTTING_HARVEST_LUMBER))
.thenReturn(100D);
Mockito.when(advancedConfig.getMaximumProbability(SubSkillType.WOODCUTTING_CLEAN_CUTS))
@@ -66,14 +67,6 @@ class WoodcuttingTest extends MMOTestEnvironment {
eq(SubSkillType.WOODCUTTING_HARVEST_LUMBER))).thenReturn(true);
Mockito.when(RankUtils.hasReachedRank(eq(1), any(Player.class),
eq(SubSkillType.WOODCUTTING_CLEAN_CUTS))).thenReturn(true);
// wire inventory
this.itemInMainHand = new ItemStack(Material.DIAMOND_AXE);
Mockito.when(player.getInventory()).thenReturn(playerInventory);
Mockito.when(playerInventory.getItemInMainHand()).thenReturn(itemInMainHand);
// Set up spy for WoodcuttingManager
woodcuttingManager = Mockito.spy(new WoodcuttingManager(mmoPlayer));
}
@AfterEach
@@ -83,6 +76,12 @@ class WoodcuttingTest extends MMOTestEnvironment {
@Test
void harvestLumberShouldDoubleDrop() {
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(testPlayerMock.playerInventory().getItemInMainHand())
.thenReturn(new ItemStack(Material.DIAMOND_AXE));
final WoodcuttingManager woodcuttingManager = Mockito.spy(
new WoodcuttingManager(mmoPlayer));
mmoPlayer.modifySkill(PrimarySkillType.WOODCUTTING, 1000);
Block block = mock(Block.class);
@@ -100,6 +99,12 @@ class WoodcuttingTest extends MMOTestEnvironment {
@Test
void harvestLumberShouldNotDoubleDrop() {
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(testPlayerMock.playerInventory().getItemInMainHand())
.thenReturn(new ItemStack(Material.DIAMOND_AXE));
final WoodcuttingManager woodcuttingManager = Mockito.spy(
new WoodcuttingManager(mmoPlayer));
mmoPlayer.modifySkill(PrimarySkillType.WOODCUTTING, 0);
Block block = mock(Block.class);
@@ -115,6 +120,12 @@ class WoodcuttingTest extends MMOTestEnvironment {
@Test
void testProcessWoodcuttingBlockXP() {
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(testPlayerMock.playerInventory().getItemInMainHand())
.thenReturn(new ItemStack(Material.DIAMOND_AXE));
final WoodcuttingManager woodcuttingManager = Mockito.spy(
new WoodcuttingManager(mmoPlayer));
Block targetBlock = mock(Block.class);
Mockito.when(targetBlock.getType()).thenReturn(Material.OAK_LOG);
// wire XP
@@ -129,11 +140,15 @@ class WoodcuttingTest extends MMOTestEnvironment {
@Test
void treeFellerShouldStopAtThreshold() {
// Set threshold artificially low
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(testPlayerMock.playerInventory().getItemInMainHand())
.thenReturn(new ItemStack(Material.DIAMOND_AXE));
// Set threshold to 3
int fakeThreshold = 3;
Mockito.when(generalConfig.getTreeFellerThreshold()).thenReturn(fakeThreshold);
WoodcuttingManager manager = Mockito.spy(new WoodcuttingManager(mmoPlayer));
final WoodcuttingManager woodcuttingManager = Mockito.spy(
new WoodcuttingManager(mmoPlayer));
// Simulate all blocks are logs with XP
MockedStatic<BlockUtils> mockedBlockUtils = mockStatic(BlockUtils.class);
@@ -163,7 +178,7 @@ class WoodcuttingTest extends MMOTestEnvironment {
ThreadLocalRandom.current().nextInt(relatives.size())));
Set<Block> treeFellerBlocks = new HashSet<>();
manager.processTree(centerBlock, treeFellerBlocks);
woodcuttingManager.processTree(centerBlock, treeFellerBlocks);
// --- Assertions ---
@@ -171,12 +186,8 @@ class WoodcuttingTest extends MMOTestEnvironment {
assertFalse(treeFellerBlocks.isEmpty(), "Tree Feller should process at least one block");
// It reached or slightly exceeded the threshold
assertTrue(treeFellerBlocks.size() >= fakeThreshold,
"Tree Feller should process up to the threshold limit");
// Confirm it stopped due to the threshold
assertTrue(getPrivateTreeFellerReachedThreshold(manager),
"Tree Feller should set treeFellerReachedThreshold to true");
assertEquals(fakeThreshold, treeFellerBlocks.size(),
"expected that Tree Feller will have a block size equal to the threshold");
mockedBlockUtils.close();
}
@@ -192,12 +203,16 @@ class WoodcuttingTest extends MMOTestEnvironment {
}
@Test
void treeFellerShouldNotReachThreshold() throws NoSuchFieldException, IllegalAccessException {
void treeFellerShouldNotReachThreshold() {
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(testPlayerMock.playerInventory().getItemInMainHand())
.thenReturn(new ItemStack(Material.DIAMOND_AXE));
final WoodcuttingManager woodcuttingManager = Mockito.spy(
new WoodcuttingManager(mmoPlayer));
int threshold = 10;
Mockito.when(generalConfig.getTreeFellerThreshold()).thenReturn(threshold);
WoodcuttingManager manager = Mockito.spy(new WoodcuttingManager(mmoPlayer));
MockedStatic<BlockUtils> mockedBlockUtils = mockStatic(BlockUtils.class);
mockedBlockUtils.when(() -> BlockUtils.hasWoodcuttingXP(any(Block.class))).thenReturn(true);
mockedBlockUtils.when(() -> BlockUtils.isNonWoodPartOfTree(any(Block.class)))
@@ -222,10 +237,10 @@ class WoodcuttingTest extends MMOTestEnvironment {
Mockito.when(b3.getRelative(any(BlockFace.class))).thenReturn(null);
Set<Block> processed = new HashSet<>();
manager.processTree(b0, processed);
woodcuttingManager.processTree(b0, processed);
assertEquals(3, processed.size(), "Should process exactly 4 blocks");
assertFalse(getPrivateTreeFellerReachedThreshold(manager),
assertFalse(getPrivateTreeFellerReachedThreshold(woodcuttingManager),
"treeFellerReachedThreshold should remain false");
mockedBlockUtils.close();

View File

@@ -1,60 +1,60 @@
package com.gmail.nossr50.util;
import static com.gmail.nossr50.util.PotionEffectUtil.getNauseaPotionEffectType;
import static java.util.logging.Logger.getLogger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.compat.CompatibilityManager;
import com.gmail.nossr50.util.platform.MinecraftGameVersion;
import org.bukkit.potion.PotionEffectType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
class PotionEffectUtilTest {
private MockedStatic<mcMMO> mockedStaticMcMMO;
private static final java.util.logging.Logger logger = getLogger(
PotionEffectUtilTest.class.getName());
@BeforeEach
void setUp() {
mockedStaticMcMMO = mockStatic(mcMMO.class);
mcMMO.p = mock(mcMMO.class);
when(mcMMO.p.getLogger()).thenReturn(logger);
CompatibilityManager compatibilityManager = mock(CompatibilityManager.class);
MinecraftGameVersion minecraftGameVersion = mock(MinecraftGameVersion.class);
when(compatibilityManager.getMinecraftGameVersion()).thenReturn(minecraftGameVersion);
when(minecraftGameVersion.isAtLeast(1, 20, 5)).thenReturn(false);
when(mcMMO.getCompatibilityManager()).thenReturn(compatibilityManager);
}
@AfterEach
void tearDown() {
mockedStaticMcMMO.close();
}
@Test
@Tag("skip")
void testGetNauseaPotionEffectType() {
// TODO: Test only works on older versions since we aren't properly mocking the spigot registry
final PotionEffectType nausea = getNauseaPotionEffectType();
assertNotNull(nausea);
assertThat(nausea).isEqualTo(PotionEffectType.NAUSEA);
}
@Test
@Tag("skip")
void testGetHastePotionEffectType() {
// TODO: Test only works on older versions since we aren't properly mocking the spigot registry
final PotionEffectType haste = PotionEffectUtil.getHastePotionEffectType();
assertNotNull(haste);
assertThat(haste).isEqualTo(PotionEffectType.HASTE);
}
}
//package com.gmail.nossr50.util;
//
//import static com.gmail.nossr50.util.PotionEffectUtil.getNauseaPotionEffectType;
//import static java.util.logging.Logger.getLogger;
//import static org.assertj.core.api.Assertions.assertThat;
//import static org.junit.jupiter.api.Assertions.assertNotNull;
//import static org.mockito.Mockito.mock;
//import static org.mockito.Mockito.mockStatic;
//import static org.mockito.Mockito.when;
//
//import com.gmail.nossr50.mcMMO;
//import com.gmail.nossr50.util.compat.CompatibilityManager;
//import com.gmail.nossr50.util.platform.MinecraftGameVersion;
//import org.bukkit.potion.PotionEffectType;
//import org.junit.jupiter.api.AfterEach;
//import org.junit.jupiter.api.BeforeEach;
//import org.junit.jupiter.api.Tag;
//import org.junit.jupiter.api.Test;
//import org.mockito.MockedStatic;
//
//class PotionEffectUtilTest {
// private MockedStatic<mcMMO> mockedStaticMcMMO;
// private static final java.util.logging.Logger logger = getLogger(
// PotionEffectUtilTest.class.getName());
//
// @BeforeEach
// void setUp() {
// mockedStaticMcMMO = mockStatic(mcMMO.class);
// mcMMO.p = mock(mcMMO.class);
// when(mcMMO.p.getLogger()).thenReturn(logger);
// CompatibilityManager compatibilityManager = mock(CompatibilityManager.class);
// MinecraftGameVersion minecraftGameVersion = mock(MinecraftGameVersion.class);
// when(compatibilityManager.getMinecraftGameVersion()).thenReturn(minecraftGameVersion);
// when(minecraftGameVersion.isAtLeast(1, 20, 5)).thenReturn(false);
// when(mcMMO.getCompatibilityManager()).thenReturn(compatibilityManager);
// }
//
// @AfterEach
// void tearDown() {
// mockedStaticMcMMO.close();
// }
//
// @Test
// @Tag("skip")
// void testGetNauseaPotionEffectType() {
// // TODO: Test only works on older versions since we aren't properly mocking the spigot registry
// final PotionEffectType nausea = getNauseaPotionEffectType();
// assertNotNull(nausea);
// assertThat(nausea).isEqualTo(PotionEffectType.NAUSEA);
// }
//
// @Test
// @Tag("skip")
// void testGetHastePotionEffectType() {
// // TODO: Test only works on older versions since we aren't properly mocking the spigot registry
// final PotionEffectType haste = PotionEffectUtil.getHastePotionEffectType();
// assertNotNull(haste);
// assertThat(haste).isEqualTo(PotionEffectType.HASTE);
// }
//}

View File

@@ -0,0 +1,12 @@
package com.gmail.nossr50.util;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.PlayerInventory;
public record TestPlayerMock(Player player, PlayerInventory playerInventory,
Location playerLocation, PlayerProfile playerProfile,
McMMOPlayer mmoPlayer) {
}

View File

@@ -15,7 +15,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import com.gmail.nossr50.MMOTestEnvironment;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.util.TestPlayerMock;
import java.util.logging.Logger;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterEach;
@@ -66,6 +68,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment {
@Test
public void isSkillRNGSuccessfulShouldBehaveAsExpected() {
// Given
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(advancedConfig.getMaximumProbability(UNARMED_ARROW_DEFLECT)).thenReturn(20D);
when(advancedConfig.getMaxBonusLevel(UNARMED_ARROW_DEFLECT)).thenReturn(0);
@@ -110,6 +114,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment {
@Test
public void getRNGDisplayValuesShouldReturn10PercentForDodge() {
// Given
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(advancedConfig.getMaximumProbability(ACROBATICS_DODGE)).thenReturn(20D);
when(advancedConfig.getMaxBonusLevel(ACROBATICS_DODGE)).thenReturn(1000);
mmoPlayer.modifySkill(ACROBATICS, 500);
@@ -123,6 +129,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment {
@Test
public void getRNGDisplayValuesShouldReturn20PercentForDodge() {
// Given
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(advancedConfig.getMaximumProbability(ACROBATICS_DODGE)).thenReturn(20D);
when(advancedConfig.getMaxBonusLevel(ACROBATICS_DODGE)).thenReturn(1000);
mmoPlayer.modifySkill(ACROBATICS, 1000);
@@ -136,6 +144,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment {
@Test
public void getRNGDisplayValuesShouldReturn0PercentForDodge() {
// Given
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(advancedConfig.getMaximumProbability(ACROBATICS_DODGE)).thenReturn(20D);
when(advancedConfig.getMaxBonusLevel(ACROBATICS_DODGE)).thenReturn(1000);
mmoPlayer.modifySkill(ACROBATICS, 0);
@@ -149,6 +159,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment {
@Test
public void getRNGDisplayValuesShouldReturn10PercentForDoubleDrops() {
// Given
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(advancedConfig.getMaximumProbability(MINING_DOUBLE_DROPS)).thenReturn(100D);
when(advancedConfig.getMaxBonusLevel(MINING_DOUBLE_DROPS)).thenReturn(1000);
mmoPlayer.modifySkill(MINING, 100);
@@ -162,6 +174,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment {
@Test
public void getRNGDisplayValuesShouldReturn50PercentForDoubleDrops() {
// Given
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(advancedConfig.getMaximumProbability(MINING_DOUBLE_DROPS)).thenReturn(100D);
when(advancedConfig.getMaxBonusLevel(MINING_DOUBLE_DROPS)).thenReturn(1000);
mmoPlayer.modifySkill(MINING, 500);
@@ -175,6 +189,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment {
@Test
public void getRNGDisplayValuesShouldReturn100PercentForDoubleDrops() {
// Given
final TestPlayerMock testPlayerMock = mockPlayer();
final McMMOPlayer mmoPlayer = testPlayerMock.mmoPlayer();
when(advancedConfig.getMaximumProbability(MINING_DOUBLE_DROPS)).thenReturn(100D);
when(advancedConfig.getMaxBonusLevel(MINING_DOUBLE_DROPS)).thenReturn(1000);
mmoPlayer.modifySkill(MINING, 1000);

View File

@@ -0,0 +1,23 @@
level_up_commands:
unique_id_here:
enabled: false
condition:
skills:
- 'Swords'
- 'Axes'
levels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
commands:
- "say %player% reached level %level%!"
- "say Isn't that nice?"
run_command_as: 'CONSOLE'
log_level: 'INFO'
other_unique_id_here:
enabled: false
condition:
complex_condition:
source: 'player.getLevel() % 2 == 0'
commands:
- "say %player% reached an even level!"
- "say Isn't that fun?"
run_command_as: 'CONSOLE'
log_level: 'DEBUG'