Fixes tests

This commit is contained in:
tastybento 2019-11-03 14:12:09 -08:00
parent e3e3191e6c
commit 4cb4c7e3fb
6 changed files with 432 additions and 411 deletions

View File

@ -379,6 +379,8 @@ public class ChallengesManager
* This method stores PlayerData into local cache. * This method stores PlayerData into local cache.
* *
* @param playerData ChallengesPlayerData that must be loaded. * @param playerData ChallengesPlayerData that must be loaded.
*
* TODO: Remove this unused method?
*/ */
private void loadPlayerData(@NonNull ChallengesPlayerData playerData) private void loadPlayerData(@NonNull ChallengesPlayerData playerData)
{ {
@ -683,6 +685,7 @@ public class ChallengesManager
/** /**
* This method collects all data from challenges database and migrates them. * This method collects all data from challenges database and migrates them.
*/ */
@SuppressWarnings("deprecation")
private boolean migrateChallenges(World world) private boolean migrateChallenges(World world)
{ {
String addonName = Utils.getGameMode(world); String addonName = Utils.getGameMode(world);

View File

@ -48,9 +48,9 @@ import world.bentobox.challenges.utils.Utils;
*/ */
public class TryToComplete public class TryToComplete
{ {
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// Section: Variables // Section: Variables
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
/** /**
* Challenges addon variable. * Challenges addon variable.
@ -92,9 +92,9 @@ public class TryToComplete
*/ */
private final ChallengeResult EMPTY_RESULT = new ChallengeResult(); private final ChallengeResult EMPTY_RESULT = new ChallengeResult();
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// Section: Builder // Section: Builder
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
@Deprecated @Deprecated
public TryToComplete label(String label) public TryToComplete label(String label)
@ -151,9 +151,9 @@ public class TryToComplete
} }
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// Section: Constructor // Section: Constructor
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
/** /**
@ -165,11 +165,11 @@ public class TryToComplete
* @param permissionPrefix - Permission prefix for GameMode addon. * @param permissionPrefix - Permission prefix for GameMode addon.
*/ */
public TryToComplete(ChallengesAddon addon, public TryToComplete(ChallengesAddon addon,
User user, User user,
Challenge challenge, Challenge challenge,
World world, World world,
String topLabel, String topLabel,
String permissionPrefix) String permissionPrefix)
{ {
this.addon = addon; this.addon = addon;
this.world = world; this.world = world;
@ -194,11 +194,11 @@ public class TryToComplete
* @return true, if challenge is completed, otherwise false. * @return true, if challenge is completed, otherwise false.
*/ */
public static boolean complete(ChallengesAddon addon, public static boolean complete(ChallengesAddon addon,
User user, User user,
Challenge challenge, Challenge challenge,
World world, World world,
String topLabel, String topLabel,
String permissionPrefix) String permissionPrefix)
{ {
return TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix, 1); return TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix, 1);
} }
@ -216,21 +216,21 @@ public class TryToComplete
* @return true, if challenge is completed, otherwise false. * @return true, if challenge is completed, otherwise false.
*/ */
public static boolean complete(ChallengesAddon addon, public static boolean complete(ChallengesAddon addon,
User user, User user,
Challenge challenge, Challenge challenge,
World world, World world,
String topLabel, String topLabel,
String permissionPrefix, String permissionPrefix,
int maxTimes) int maxTimes)
{ {
return new TryToComplete(addon, user, challenge, world, topLabel, permissionPrefix). return new TryToComplete(addon, user, challenge, world, topLabel, permissionPrefix).
build(maxTimes).meetsRequirements; build(maxTimes).meetsRequirements;
} }
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// Section: Methods // Section: Methods
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
/** /**
@ -261,7 +261,7 @@ public class TryToComplete
returnItem.setAmount(amount); returnItem.setAmount(amount);
this.user.getInventory().addItem(returnItem).forEach((k, v) -> this.user.getInventory().addItem(returnItem).forEach((k, v) ->
this.user.getWorld().dropItem(this.user.getLocation(), v)); this.user.getWorld().dropItem(this.user.getLocation(), v));
}); });
} }
@ -279,7 +279,7 @@ public class TryToComplete
// Clone is necessary because otherwise it will chane reward itemstack // Clone is necessary because otherwise it will chane reward itemstack
// amount. // amount.
this.user.getInventory().addItem(reward.clone()).forEach((k, v) -> this.user.getInventory().addItem(reward.clone()).forEach((k, v) ->
this.user.getWorld().dropItem(this.user.getLocation(), v)); this.user.getWorld().dropItem(this.user.getLocation(), v));
} }
// Money Reward // Money Reward
@ -308,8 +308,8 @@ public class TryToComplete
if (!player.getUniqueId().equals(this.user.getUniqueId())) if (!player.getUniqueId().equals(this.user.getUniqueId()))
{ {
User.getInstance(player).sendMessage("challenges.messages.name-has-completed-challenge", User.getInstance(player).sendMessage("challenges.messages.name-has-completed-challenge",
"[name]", this.user.getName(), "[name]", this.user.getName(),
"[value]", this.challenge.getFriendlyName()); "[value]", this.challenge.getFriendlyName());
} }
} }
} }
@ -318,11 +318,11 @@ public class TryToComplete
if (this.addon.getChallengesSettings().isShowCompletionTitle()) if (this.addon.getChallengesSettings().isShowCompletionTitle())
{ {
this.user.getPlayer().sendTitle( this.user.getPlayer().sendTitle(
this.parseChallenge(this.user.getTranslation("challenges.titles.challenge-title"), this.challenge), this.parseChallenge(this.user.getTranslation("challenges.titles.challenge-title"), this.challenge),
this.parseChallenge(this.user.getTranslation("challenges.titles.challenge-subtitle"), this.challenge), this.parseChallenge(this.user.getTranslation("challenges.titles.challenge-subtitle"), this.challenge),
10, 10,
this.addon.getChallengesSettings().getTitleShowtime(), this.addon.getChallengesSettings().getTitleShowtime(),
20); 20);
} }
} }
@ -339,7 +339,7 @@ public class TryToComplete
for (int i = 0; i < rewardFactor; i++) for (int i = 0; i < rewardFactor; i++)
{ {
this.user.getInventory().addItem(reward.clone()).forEach((k, v) -> this.user.getInventory().addItem(reward.clone()).forEach((k, v) ->
this.user.getWorld().dropItem(this.user.getLocation(), v)); this.user.getWorld().dropItem(this.user.getLocation(), v));
} }
} }
@ -347,12 +347,12 @@ public class TryToComplete
if (this.addon.isEconomyProvided()) if (this.addon.isEconomyProvided())
{ {
this.addon.getEconomyProvider().deposit(this.user, this.addon.getEconomyProvider().deposit(this.user,
(double)this.challenge.getRepeatMoneyReward() * rewardFactor); (double)this.challenge.getRepeatMoneyReward() * rewardFactor);
} }
// Experience Repeat Reward // Experience Repeat Reward
this.user.getPlayer().giveExp( this.user.getPlayer().giveExp(
this.challenge.getRepeatExperienceReward() * rewardFactor); this.challenge.getRepeatExperienceReward() * rewardFactor);
// Run commands // Run commands
for (int i = 0; i < rewardFactor; i++) for (int i = 0; i < rewardFactor; i++)
@ -363,8 +363,8 @@ public class TryToComplete
if (result.getFactor() > 1) if (result.getFactor() > 1)
{ {
this.user.sendMessage("challenges.messages.you-repeated-challenge-multiple", this.user.sendMessage("challenges.messages.you-repeated-challenge-multiple",
"[value]", this.challenge.getFriendlyName(), "[value]", this.challenge.getFriendlyName(),
"[count]", Integer.toString(result.getFactor())); "[count]", Integer.toString(result.getFactor()));
} }
else else
{ {
@ -377,7 +377,7 @@ public class TryToComplete
// Check level completion for non-free challenges // Check level completion for non-free challenges
if (!result.wasCompleted() && if (!result.wasCompleted() &&
!this.challenge.getLevel().equals(ChallengesManager.FREE)) !this.challenge.getLevel().equals(ChallengesManager.FREE))
{ {
ChallengeLevel level = this.manager.getLevel(this.challenge); ChallengeLevel level = this.manager.getLevel(this.challenge);
@ -391,7 +391,7 @@ public class TryToComplete
// Clone is necessary because otherwise it will chane reward itemstack // Clone is necessary because otherwise it will chane reward itemstack
// amount. // amount.
this.user.getInventory().addItem(reward.clone()).forEach((k, v) -> this.user.getInventory().addItem(reward.clone()).forEach((k, v) ->
this.user.getWorld().dropItem(this.user.getLocation(), v)); this.user.getWorld().dropItem(this.user.getLocation(), v));
} }
// Money Reward // Money Reward
@ -416,7 +416,7 @@ public class TryToComplete
if (!player.getUniqueId().equals(this.user.getUniqueId())) if (!player.getUniqueId().equals(this.user.getUniqueId()))
{ {
User.getInstance(player).sendMessage("challenges.messages.name-has-completed-level", User.getInstance(player).sendMessage("challenges.messages.name-has-completed-level",
"[name]", this.user.getName(), "[value]", level.getFriendlyName()); "[name]", this.user.getName(), "[value]", level.getFriendlyName());
} }
} }
} }
@ -427,11 +427,11 @@ public class TryToComplete
if (this.addon.getChallengesSettings().isShowCompletionTitle()) if (this.addon.getChallengesSettings().isShowCompletionTitle())
{ {
this.user.getPlayer().sendTitle( this.user.getPlayer().sendTitle(
this.parseLevel(this.user.getTranslation("challenges.titles.level-title"), level), this.parseLevel(this.user.getTranslation("challenges.titles.level-title"), level),
this.parseLevel(this.user.getTranslation("challenges.titles.level-subtitle"), level), this.parseLevel(this.user.getTranslation("challenges.titles.level-subtitle"), level),
10, 10,
this.addon.getChallengesSettings().getTitleShowtime(), this.addon.getChallengesSettings().getTitleShowtime(),
20); 20);
} }
} }
} }
@ -452,15 +452,15 @@ public class TryToComplete
IslandRequirements requirements = this.challenge.getRequirements(); IslandRequirements requirements = this.challenge.getRequirements();
if (result.meetsRequirements && if (result.meetsRequirements &&
requirements.isRemoveEntities() && requirements.isRemoveEntities() &&
!requirements.getRequiredEntities().isEmpty()) !requirements.getRequiredEntities().isEmpty())
{ {
this.removeEntities(result.entities, result.getFactor()); this.removeEntities(result.entities, result.getFactor());
} }
if (result.meetsRequirements && if (result.meetsRequirements &&
requirements.isRemoveBlocks() && requirements.isRemoveBlocks() &&
!requirements.getRequiredBlocks().isEmpty()) !requirements.getRequiredBlocks().isEmpty())
{ {
this.removeBlocks(result.blocks, result.getFactor()); this.removeBlocks(result.blocks, result.getFactor());
} }
@ -471,11 +471,11 @@ public class TryToComplete
if (this.getInventoryRequirements().isTakeItems()) if (this.getInventoryRequirements().isTakeItems())
{ {
int sumEverything = result.requiredItems.stream(). int sumEverything = result.requiredItems.stream().
mapToInt(itemStack -> itemStack.getAmount() * result.getFactor()). mapToInt(itemStack -> itemStack.getAmount() * result.getFactor()).
sum(); sum();
Map<ItemStack, Integer> removedItems = Map<ItemStack, Integer> removedItems =
this.removeItems(result.requiredItems, result.getFactor()); this.removeItems(result.requiredItems, result.getFactor());
int removedAmount = removedItems.values().stream().mapToInt(num -> num).sum(); int removedAmount = removedItems.values().stream().mapToInt(num -> num).sum();
@ -499,11 +499,11 @@ public class TryToComplete
} }
if (requirements.isTakeExperience() && if (requirements.isTakeExperience() &&
this.user.getPlayer().getGameMode() != GameMode.CREATIVE) this.user.getPlayer().getGameMode() != GameMode.CREATIVE)
{ {
// Cannot take anything from creative game mode. // Cannot take anything from creative game mode.
this.user.getPlayer().setTotalExperience( this.user.getPlayer().setTotalExperience(
this.user.getPlayer().getTotalExperience() - requirements.getRequiredExperience()); this.user.getPlayer().getTotalExperience() - requirements.getRequiredExperience());
} }
} }
} }
@ -531,36 +531,36 @@ public class TryToComplete
result = EMPTY_RESULT; result = EMPTY_RESULT;
} }
else if (Util.getWorld(this.world) != Util.getWorld(this.user.getWorld()) || else if (Util.getWorld(this.world) != Util.getWorld(this.user.getWorld()) ||
!this.challenge.matchGameMode(Utils.getGameMode(this.world))) !this.challenge.matchGameMode(Utils.getGameMode(this.world)))
{ {
this.user.sendMessage("general.errors.wrong-world"); this.user.sendMessage("general.errors.wrong-world");
result = EMPTY_RESULT; result = EMPTY_RESULT;
} }
// Player is not on island // Player is not on island
else if (ChallengesAddon.CHALLENGES_WORLD_PROTECTION.isSetForWorld(this.world) && else if (ChallengesAddon.CHALLENGES_WORLD_PROTECTION.isSetForWorld(this.world) &&
!this.addon.getIslands().locationIsOnIsland(this.user.getPlayer(), this.user.getLocation())) !this.addon.getIslands().locationIsOnIsland(this.user.getPlayer(), this.user.getLocation()))
{ {
this.user.sendMessage("challenges.errors.not-on-island"); this.user.sendMessage("challenges.errors.not-on-island");
result = EMPTY_RESULT; result = EMPTY_RESULT;
} }
// Check player permission // Check player permission
else if (!this.addon.getIslands().getIslandAt(this.user.getLocation()). else if (!this.addon.getIslands().getIslandAt(this.user.getLocation()).
map(i -> i.isAllowed(this.user, ChallengesAddon.CHALLENGES_ISLAND_PROTECTION)). map(i -> i.isAllowed(this.user, ChallengesAddon.CHALLENGES_ISLAND_PROTECTION)).
orElse(false)) orElse(false))
{ {
this.user.sendMessage("challenges.errors.no-rank"); this.user.sendMessage("challenges.errors.no-rank");
result = EMPTY_RESULT; result = EMPTY_RESULT;
} }
// Check if user has unlocked challenges level. // Check if user has unlocked challenges level.
else if (!this.challenge.getLevel().equals(ChallengesManager.FREE) && else if (!this.challenge.getLevel().equals(ChallengesManager.FREE) &&
!this.manager.isLevelUnlocked(this.user, this.world, this.manager.getLevel(this.challenge.getLevel()))) !this.manager.isLevelUnlocked(this.user, this.world, this.manager.getLevel(this.challenge.getLevel())))
{ {
this.user.sendMessage("challenges.errors.challenge-level-not-available"); this.user.sendMessage("challenges.errors.challenge-level-not-available");
result = EMPTY_RESULT; result = EMPTY_RESULT;
} }
// Check max times // Check max times
else if (this.challenge.isRepeatable() && this.challenge.getMaxTimes() > 0 && else if (this.challenge.isRepeatable() && this.challenge.getMaxTimes() > 0 &&
this.manager.getChallengeTimes(this.user, this.world, this.challenge) >= this.challenge.getMaxTimes()) this.manager.getChallengeTimes(this.user, this.world, this.challenge) >= this.challenge.getMaxTimes())
{ {
this.user.sendMessage("challenges.errors.not-repeatable"); this.user.sendMessage("challenges.errors.not-repeatable");
result = EMPTY_RESULT; result = EMPTY_RESULT;
@ -573,7 +573,7 @@ public class TryToComplete
} }
// Check environment // Check environment
else if (!this.challenge.getEnvironment().isEmpty() && else if (!this.challenge.getEnvironment().isEmpty() &&
!this.challenge.getEnvironment().contains(this.user.getWorld().getEnvironment())) !this.challenge.getEnvironment().contains(this.user.getWorld().getEnvironment()))
{ {
this.user.sendMessage("challenges.errors.wrong-environment"); this.user.sendMessage("challenges.errors.wrong-environment");
result = EMPTY_RESULT; result = EMPTY_RESULT;
@ -618,7 +618,7 @@ public class TryToComplete
private boolean checkPermissions() private boolean checkPermissions()
{ {
return this.challenge.getRequirements().getRequiredPermissions().isEmpty() || return this.challenge.getRequirements().getRequiredPermissions().isEmpty() ||
this.challenge.getRequirements().getRequiredPermissions().stream().allMatch(s -> this.user.hasPermission(s)); this.challenge.getRequirements().getRequiredPermissions().stream().allMatch(s -> this.user.hasPermission(s));
} }
@ -686,7 +686,7 @@ public class TryToComplete
try try
{ {
if (!this.addon.getServer().dispatchCommand(this.addon.getServer().getConsoleSender(), if (!this.addon.getServer().dispatchCommand(this.addon.getServer().getConsoleSender(),
cmd.replace("[player]", this.user.getName()))) cmd.replace("[player]", this.user.getName())))
{ {
this.showError(cmd); this.showError(cmd);
} }
@ -710,9 +710,9 @@ public class TryToComplete
} }
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// Section: Inventory Challenge // Section: Inventory Challenge
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
/** /**
@ -738,7 +738,7 @@ public class TryToComplete
if (Utils.canIgnoreMeta(required.getType())) if (Utils.canIgnoreMeta(required.getType()))
{ {
numInInventory = numInInventory =
Arrays.stream(this.user.getInventory().getContents()). Arrays.stream(this.user.getInventory().getContents()).
filter(Objects::nonNull). filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())). filter(i -> i.getType().equals(required.getType())).
mapToInt(ItemStack::getAmount). mapToInt(ItemStack::getAmount).
@ -747,7 +747,7 @@ public class TryToComplete
else else
{ {
numInInventory = numInInventory =
Arrays.stream(this.user.getInventory().getContents()). Arrays.stream(this.user.getInventory().getContents()).
filter(Objects::nonNull). filter(Objects::nonNull).
filter(i -> i.isSimilar(required)). filter(i -> i.isSimilar(required)).
mapToInt(ItemStack::getAmount). mapToInt(ItemStack::getAmount).
@ -757,8 +757,8 @@ public class TryToComplete
if (numInInventory < required.getAmount()) if (numInInventory < required.getAmount())
{ {
this.user.sendMessage("challenges.errors.not-enough-items", this.user.sendMessage("challenges.errors.not-enough-items",
"[items]", "[items]",
Util.prettifyText(required.getType().toString())); Util.prettifyText(required.getType().toString()));
return EMPTY_RESULT; return EMPTY_RESULT;
} }
@ -772,9 +772,9 @@ public class TryToComplete
// Return the result // Return the result
return new ChallengeResult(). return new ChallengeResult().
setMeetsRequirements(). setMeetsRequirements().
setCompleteFactor(maxTimes). setCompleteFactor(maxTimes).
setRequiredItems(requiredItems); setRequiredItems(requiredItems);
} }
@ -790,26 +790,24 @@ public class TryToComplete
for (ItemStack required : requiredItemList) for (ItemStack required : requiredItemList)
{ {
int amountToBeRemoved = required.getAmount() * factor; int amountToBeRemoved = required.getAmount() * factor;
List<ItemStack> itemsInInventory; List<ItemStack> itemsInInventory;
if (Utils.canIgnoreMeta(required.getType())) if (Utils.canIgnoreMeta(required.getType()))
{ {
// Use collecting method that ignores item meta. // Use collecting method that ignores item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()). itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull). filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())). filter(i -> i.getType().equals(required.getType())).
collect(Collectors.toList()); collect(Collectors.toList());
} }
else else
{ {
// Use collecting method that compares item meta. // Use collecting method that compares item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()). itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull). filter(Objects::nonNull).
filter(i -> i.isSimilar(required)). filter(i -> i.isSimilar(required)).
collect(Collectors.toList()); collect(Collectors.toList());
} }
for (ItemStack itemStack : itemsInInventory) for (ItemStack itemStack : itemsInInventory)
{ {
if (amountToBeRemoved > 0) if (amountToBeRemoved > 0)
@ -836,7 +834,7 @@ public class TryToComplete
if (amountToBeRemoved > 0) if (amountToBeRemoved > 0)
{ {
this.addon.logError("Could not remove " + amountToBeRemoved + " of " + required.getType() + this.addon.logError("Could not remove " + amountToBeRemoved + " of " + required.getType() +
" from player's inventory!"); " from player's inventory!");
} }
} }
@ -844,9 +842,9 @@ public class TryToComplete
} }
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// Section: Island Challenge // Section: Island Challenge
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
/** /**
@ -877,7 +875,7 @@ public class TryToComplete
// Players should not be able to complete challenge if they stay near island with required blocks. // Players should not be able to complete challenge if they stay near island with required blocks.
Island island = this.addon.getIslands().getIsland(this.world, this.user); Island island = this.addon.getIslands().getIsland(this.world, this.user);
if (island == null) { if (island == null) {
// Just in case. Should never hit because there is a check if the player is on this island further up // Just in case. Should never hit because there is a check if the player is on this island further up
return EMPTY_RESULT; return EMPTY_RESULT;
@ -907,15 +905,15 @@ public class TryToComplete
// Protection code. Do not allow to select too large region for completing challenge. // Protection code. Do not allow to select too large region for completing challenge.
if (boundingBox.getWidthX() > distance * 2 + 3 || if (boundingBox.getWidthX() > distance * 2 + 3 ||
boundingBox.getWidthZ() > distance * 2 + 3 || boundingBox.getWidthZ() > distance * 2 + 3 ||
boundingBox.getHeight() > distance * 2 + 3) boundingBox.getHeight() > distance * 2 + 3)
{ {
this.addon.logError("BoundingBox is larger than SearchRadius. " + this.addon.logError("BoundingBox is larger than SearchRadius. " +
" | BoundingBox: " + boundingBox.toString() + " | BoundingBox: " + boundingBox.toString() +
" | Search Distance: " + requirements.getSearchRadius() + " | Search Distance: " + requirements.getSearchRadius() +
" | Location: " + this.user.getLocation().toString() + " | Location: " + this.user.getLocation().toString() +
" | Center: " + island.getCenter().toString() + " | Center: " + island.getCenter().toString() +
" | Range: " + range); " | Range: " + range);
return EMPTY_RESULT; return EMPTY_RESULT;
} }
@ -952,15 +950,15 @@ public class TryToComplete
// This queue will contain only blocks whit required type ordered by distance till player. // This queue will contain only blocks whit required type ordered by distance till player.
Queue<Block> blockFromWorld = new PriorityQueue<>((o1, o2) -> { Queue<Block> blockFromWorld = new PriorityQueue<>((o1, o2) -> {
if (o1.getType().equals(o2.getType())) if (o1.getType().equals(o2.getType()))
{ {
return Double.compare(o1.getLocation().distance(this.user.getLocation()), return Double.compare(o1.getLocation().distance(this.user.getLocation()),
o2.getLocation().distance(this.user.getLocation())); o2.getLocation().distance(this.user.getLocation()));
} }
else else
{ {
return o1.getType().compareTo(o2.getType()); return o1.getType().compareTo(o2.getType());
} }
}); });
for (int x = (int) boundingBox.getMinX(); x <= boundingBox.getMaxX(); x++) for (int x = (int) boundingBox.getMinX(); x <= boundingBox.getMaxX(); x++)
@ -1002,7 +1000,7 @@ public class TryToComplete
for (Map.Entry<Material, Integer> entry : blocksFound.entrySet()) for (Map.Entry<Material, Integer> entry : blocksFound.entrySet())
{ {
factor = Math.min(factor, factor = Math.min(factor,
entry.getValue() / requiredMap.get(entry.getKey())); entry.getValue() / requiredMap.get(entry.getKey()));
} }
} }
@ -1013,12 +1011,12 @@ public class TryToComplete
} }
this.user.sendMessage("challenges.errors.not-close-enough", this.user.sendMessage("challenges.errors.not-close-enough",
"[number]", "[number]",
String.valueOf(this.getIslandRequirements().getSearchRadius())); String.valueOf(this.getIslandRequirements().getSearchRadius()));
blocks.forEach((k, v) -> user.sendMessage("challenges.errors.you-still-need", blocks.forEach((k, v) -> user.sendMessage("challenges.errors.you-still-need",
"[amount]", String.valueOf(v), "[amount]", String.valueOf(v),
"[item]", Util.prettifyText(k.toString()))); "[item]", Util.prettifyText(k.toString())));
// kick garbage collector // kick garbage collector
@ -1038,8 +1036,8 @@ public class TryToComplete
* @return ChallengeResult * @return ChallengeResult
*/ */
private ChallengeResult searchForEntities(Map<EntityType, Integer> requiredMap, private ChallengeResult searchForEntities(Map<EntityType, Integer> requiredMap,
int factor, int factor,
BoundingBox boundingBox) BoundingBox boundingBox)
{ {
if (requiredMap.isEmpty()) if (requiredMap.isEmpty())
{ {
@ -1055,7 +1053,7 @@ public class TryToComplete
if (o1.getType().equals(o2.getType())) if (o1.getType().equals(o2.getType()))
{ {
return Double.compare(o1.getLocation().distance(this.user.getLocation()), return Double.compare(o1.getLocation().distance(this.user.getLocation()),
o2.getLocation().distance(this.user.getLocation())); o2.getLocation().distance(this.user.getLocation()));
} }
else else
{ {
@ -1067,7 +1065,7 @@ public class TryToComplete
// Check if entity is inside challenge bounding box // Check if entity is inside challenge bounding box
if (requiredMap.containsKey(entity.getType())) if (requiredMap.containsKey(entity.getType()))
{ {
entityQueue.add(entity); entityQueue.add(entity);
entitiesFound.putIfAbsent(entity.getType(), 1); entitiesFound.putIfAbsent(entity.getType(), 1);
entitiesFound.computeIfPresent(entity.getType(), (reqEntity, amount) -> amount + 1); entitiesFound.computeIfPresent(entity.getType(), (reqEntity, amount) -> amount + 1);
@ -1087,7 +1085,7 @@ public class TryToComplete
for (Map.Entry<EntityType, Integer> entry : entitiesFound.entrySet()) for (Map.Entry<EntityType, Integer> entry : entitiesFound.entrySet())
{ {
factor = Math.min(factor, factor = Math.min(factor,
entry.getValue() / requiredMap.get(entry.getKey())); entry.getValue() / requiredMap.get(entry.getKey()));
} }
} }
@ -1098,8 +1096,8 @@ public class TryToComplete
} }
minimalRequirements.forEach((reqEnt, amount) -> this.user.sendMessage("challenges.errors.you-still-need", minimalRequirements.forEach((reqEnt, amount) -> this.user.sendMessage("challenges.errors.you-still-need",
"[amount]", String.valueOf(amount), "[amount]", String.valueOf(amount),
"[item]", Util.prettifyText(reqEnt.toString()))); "[item]", Util.prettifyText(reqEnt.toString())));
// Kick garbage collector // Kick garbage collector
entitiesFound.clear(); entitiesFound.clear();
@ -1142,26 +1140,26 @@ public class TryToComplete
private void removeEntities(Queue<Entity> entityQueue, int factor) private void removeEntities(Queue<Entity> entityQueue, int factor)
{ {
Map<EntityType, Integer> entities = this.getIslandRequirements().getRequiredEntities().isEmpty() ? Map<EntityType, Integer> entities = this.getIslandRequirements().getRequiredEntities().isEmpty() ?
new EnumMap<>(EntityType.class) : new EnumMap<>(this.getIslandRequirements().getRequiredEntities()); new EnumMap<>(EntityType.class) : new EnumMap<>(this.getIslandRequirements().getRequiredEntities());
// Increase required entities by factor. // Increase required entities by factor.
entities.entrySet().forEach(entry -> entry.setValue(entry.getValue() * factor)); entities.entrySet().forEach(entry -> entry.setValue(entry.getValue() * factor));
// Go through entity queue and remove entities that are requried. // Go through entity queue and remove entities that are requried.
entityQueue.forEach(entity -> { entityQueue.forEach(entity -> {
if (entities.containsKey(entity.getType())) if (entities.containsKey(entity.getType()))
{ {
entities.computeIfPresent(entity.getType(), (reqEntity, amount) -> amount - 1); entities.computeIfPresent(entity.getType(), (reqEntity, amount) -> amount - 1);
entities.entrySet().removeIf(e -> e.getValue() == 0); entities.entrySet().removeIf(e -> e.getValue() == 0);
entity.remove(); entity.remove();
} }
}); });
} }
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// Section: Other challenge // Section: Other challenge
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
/** /**
@ -1173,60 +1171,60 @@ public class TryToComplete
{ {
OtherRequirements requirements = this.getOtherRequirements(); OtherRequirements requirements = this.getOtherRequirements();
if (!this.addon.isLevelProvided() && if (!this.addon.isLevelProvided() &&
requirements.getRequiredIslandLevel() != 0) requirements.getRequiredIslandLevel() != 0)
{ {
this.user.sendMessage("challenges.errors.missing-addon"); this.user.sendMessage("challenges.errors.missing-addon");
} }
else if (!this.addon.isEconomyProvided() && else if (!this.addon.isEconomyProvided() &&
requirements.getRequiredMoney() != 0) requirements.getRequiredMoney() != 0)
{ {
this.user.sendMessage("challenges.errors.missing-addon"); this.user.sendMessage("challenges.errors.missing-addon");
} }
else if (this.addon.isEconomyProvided() && requirements.getRequiredMoney() < 0) else if (this.addon.isEconomyProvided() && requirements.getRequiredMoney() < 0)
{ {
this.user.sendMessage("challenges.errors.incorrect"); this.user.sendMessage("challenges.errors.incorrect");
} }
else if (this.addon.isEconomyProvided() && else if (this.addon.isEconomyProvided() &&
!this.addon.getEconomyProvider().has(this.user, requirements.getRequiredMoney())) !this.addon.getEconomyProvider().has(this.user, requirements.getRequiredMoney()))
{ {
this.user.sendMessage("challenges.errors.not-enough-money", this.user.sendMessage("challenges.errors.not-enough-money",
"[value]", "[value]",
Double.toString(requirements.getRequiredMoney())); Double.toString(requirements.getRequiredMoney()));
}
else if (requirements.getRequiredExperience() < 0)
{
this.user.sendMessage("challenges.errors.incorrect");
} }
else if (requirements.getRequiredExperience() < 0)
{
this.user.sendMessage("challenges.errors.incorrect");
}
else if (this.user.getPlayer().getTotalExperience() < requirements.getRequiredExperience() && else if (this.user.getPlayer().getTotalExperience() < requirements.getRequiredExperience() &&
this.user.getPlayer().getGameMode() != GameMode.CREATIVE) this.user.getPlayer().getGameMode() != GameMode.CREATIVE)
{ {
// Players in creative gamemode has infinite amount of EXP. // Players in creative gamemode has infinite amount of EXP.
this.user.sendMessage("challenges.errors.not-enough-experience", this.user.sendMessage("challenges.errors.not-enough-experience",
"[value]", "[value]",
Integer.toString(requirements.getRequiredExperience())); Integer.toString(requirements.getRequiredExperience()));
} }
else if (this.addon.isLevelProvided() && else if (this.addon.isLevelProvided() &&
this.addon.getLevelAddon().getIslandLevel(this.world, this.user.getUniqueId()) < requirements.getRequiredIslandLevel()) this.addon.getLevelAddon().getIslandLevel(this.world, this.user.getUniqueId()) < requirements.getRequiredIslandLevel())
{ {
this.user.sendMessage("challenges.errors.island-level", this.user.sendMessage("challenges.errors.island-level",
TextVariables.NUMBER, TextVariables.NUMBER,
String.valueOf(requirements.getRequiredIslandLevel())); String.valueOf(requirements.getRequiredIslandLevel()));
} }
else else
{ {
// calculate factor // calculate factor
if (this.addon.isEconomyProvided() && requirements.isTakeMoney()) if (this.addon.isEconomyProvided() && requirements.isTakeMoney())
{ {
factor = Math.min(factor, (int) (this.addon.getEconomyProvider().getBalance(this.user) / requirements.getRequiredMoney())); factor = Math.min(factor, (int) (this.addon.getEconomyProvider().getBalance(this.user) / requirements.getRequiredMoney()));
} }
if (requirements.getRequiredExperience() > 0 && requirements.isTakeExperience()) if (requirements.getRequiredExperience() > 0 && requirements.isTakeExperience())
{ {
factor = Math.min(factor, this.user.getPlayer().getTotalExperience() / requirements.getRequiredExperience()); factor = Math.min(factor, this.user.getPlayer().getTotalExperience() / requirements.getRequiredExperience());
} }
return new ChallengeResult().setMeetsRequirements().setCompleteFactor(factor); return new ChallengeResult().setMeetsRequirements().setCompleteFactor(factor);
} }
@ -1235,9 +1233,9 @@ public class TryToComplete
} }
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// Section: Title parsings // Section: Title parsings
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
/** /**
@ -1281,9 +1279,9 @@ public class TryToComplete
} }
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// Section: Simple getter methods // Section: Simple getter methods
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
/** /**
@ -1316,9 +1314,9 @@ public class TryToComplete
} }
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
// Section: Result classes // Section: Result classes
// --------------------------------------------------------------------- // ---------------------------------------------------------------------
/** /**
@ -1480,5 +1478,15 @@ public class TryToComplete
* challenge requirements. * challenge requirements.
*/ */
private Queue<Entity> entities; private Queue<Entity> entities;
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ChallengeResult [completed=" + completed + ", meetsRequirements=" + meetsRequirements + ", factor="
+ factor + ", requiredItems=" + requiredItems + ", removedItems=" + removedItems + ", blocks="
+ blocks + ", entities=" + entities + "]";
}
} }
} }

View File

@ -72,6 +72,7 @@ import world.bentobox.bentobox.managers.IslandsManager;
* @author tastybento * @author tastybento
* *
*/ */
@SuppressWarnings("deprecation")
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest({Bukkit.class, BentoBox.class, User.class, Config.class }) @PrepareForTest({Bukkit.class, BentoBox.class, User.class, Config.class })
public class ChallengesAddonTest { public class ChallengesAddonTest {
@ -179,7 +180,7 @@ public class ChallengesAddonTest {
when(gameMode.getPlayerCommand()).thenReturn(opCmd); when(gameMode.getPlayerCommand()).thenReturn(opCmd);
// Admin command // Admin command
when(gameMode.getAdminCommand()).thenReturn(opCmd); when(gameMode.getAdminCommand()).thenReturn(opCmd);
// Flags manager // Flags manager
when(plugin.getFlagsManager()).thenReturn(fm); when(plugin.getFlagsManager()).thenReturn(fm);
when(fm.getFlags()).thenReturn(Collections.emptyList()); when(fm.getFlags()).thenReturn(Collections.emptyList());
@ -188,9 +189,9 @@ public class ChallengesAddonTest {
when(plugin.getSettings()).thenReturn(settings); when(plugin.getSettings()).thenReturn(settings);
DatabaseType value = DatabaseType.JSON; DatabaseType value = DatabaseType.JSON;
when(settings.getDatabaseType()).thenReturn(value); when(settings.getDatabaseType()).thenReturn(value);
// Bukkit // Bukkit
PowerMockito.mockStatic(Bukkit.class); PowerMockito.mockStatic(Bukkit.class);
when(Bukkit.getScheduler()).thenReturn(scheduler); when(Bukkit.getScheduler()).thenReturn(scheduler);
ItemMeta meta = mock(ItemMeta.class); ItemMeta meta = mock(ItemMeta.class);
ItemFactory itemFactory = mock(ItemFactory.class); ItemFactory itemFactory = mock(ItemFactory.class);
@ -199,7 +200,7 @@ public class ChallengesAddonTest {
UnsafeValues unsafe = mock(UnsafeValues.class); UnsafeValues unsafe = mock(UnsafeValues.class);
when(unsafe.getDataVersion()).thenReturn(777); when(unsafe.getDataVersion()).thenReturn(777);
when(Bukkit.getUnsafe()).thenReturn(unsafe); when(Bukkit.getUnsafe()).thenReturn(unsafe);
} }
@ -212,7 +213,7 @@ public class ChallengesAddonTest {
new File("config.yml").delete(); new File("config.yml").delete();
deleteAll(new File("addons")); deleteAll(new File("addons"));
deleteAll(new File("database")); deleteAll(new File("database"));
} }
private void deleteAll(File file) throws IOException { private void deleteAll(File file) throws IOException {
@ -222,7 +223,7 @@ public class ChallengesAddonTest {
.map(Path::toFile) .map(Path::toFile)
.forEach(File::delete); .forEach(File::delete);
} }
} }
/** /**
@ -235,7 +236,7 @@ public class ChallengesAddonTest {
File check = new File("addons/Challenges","config.yml"); File check = new File("addons/Challenges","config.yml");
assertTrue(check.exists()); assertTrue(check.exists());
} }
/** /**
* Test method for {@link world.bentobox.challenges.ChallengesAddon#onEnable()}. * Test method for {@link world.bentobox.challenges.ChallengesAddon#onEnable()}.
*/ */
@ -246,18 +247,18 @@ public class ChallengesAddonTest {
verify(plugin).logError("[challenges] BentoBox is not available or disabled!"); verify(plugin).logError("[challenges] BentoBox is not available or disabled!");
assertEquals(Addon.State.DISABLED, addon.getState()); assertEquals(Addon.State.DISABLED, addon.getState());
} }
/** /**
* Test method for {@link world.bentobox.challenges.ChallengesAddon#onEnable()}. * Test method for {@link world.bentobox.challenges.ChallengesAddon#onEnable()}.
*/ */
@Test @Test
public void testOnEnableDisabledAddon() { public void testOnEnableDisabledAddon() {
when(plugin.isEnabled()).thenReturn(true); when(plugin.isEnabled()).thenReturn(true);
addon.setState(State.DISABLED); addon.setState(State.DISABLED);
addon.onEnable(); addon.onEnable();
verify(plugin).logError("[challenges] Challenges Addon is not available or disabled!"); verify(plugin).logError("[challenges] Challenges Addon is not available or disabled!");
} }
/** /**
* Test method for {@link world.bentobox.challenges.ChallengesAddon#onEnable()}. * Test method for {@link world.bentobox.challenges.ChallengesAddon#onEnable()}.
*/ */
@ -273,7 +274,7 @@ public class ChallengesAddonTest {
verify(plugin).logError("[challenges] Please use JSON based database type."); verify(plugin).logError("[challenges] Please use JSON based database type.");
assertEquals(State.INCOMPATIBLE, addon.getState()); assertEquals(State.INCOMPATIBLE, addon.getState());
} }
/** /**
* Test method for {@link world.bentobox.challenges.ChallengesAddon#onEnable()}. * Test method for {@link world.bentobox.challenges.ChallengesAddon#onEnable()}.
*/ */
@ -287,9 +288,9 @@ public class ChallengesAddonTest {
verify(plugin).logWarning("[challenges] Economy plugin not found so money options will not work!"); verify(plugin).logWarning("[challenges] Economy plugin not found so money options will not work!");
verify(plugin).log("[challenges] Loading challenges..."); verify(plugin).log("[challenges] Loading challenges...");
verify(plugin, never()).logError("Challenges could not hook into AcidIsland or BSkyBlock so will not do anything!"); verify(plugin, never()).logError("Challenges could not hook into AcidIsland or BSkyBlock so will not do anything!");
} }
/** /**
* Test method for {@link world.bentobox.challenges.ChallengesAddon#onEnable()}. * Test method for {@link world.bentobox.challenges.ChallengesAddon#onEnable()}.
*/ */
@ -302,7 +303,7 @@ public class ChallengesAddonTest {
addon.onEnable(); addon.onEnable();
verify(plugin).log("[challenges] Loading challenges..."); verify(plugin).log("[challenges] Loading challenges...");
verify(plugin).logError("[challenges] Challenges could not hook into AcidIsland or BSkyBlock so will not do anything!"); verify(plugin).logError("[challenges] Challenges could not hook into AcidIsland or BSkyBlock so will not do anything!");
} }
/** /**
@ -313,7 +314,7 @@ public class ChallengesAddonTest {
addon.onReload(); addon.onReload();
verify(plugin, never()).log(anyString()); verify(plugin, never()).log(anyString());
} }
/** /**
* Test method for {@link world.bentobox.challenges.ChallengesAddon#onDisable()}. * Test method for {@link world.bentobox.challenges.ChallengesAddon#onDisable()}.
*/ */
@ -327,7 +328,7 @@ public class ChallengesAddonTest {
assertTrue(chDir.exists()); assertTrue(chDir.exists());
File lvDir = new File("database", "ChallengeLevel"); File lvDir = new File("database", "ChallengeLevel");
assertTrue(lvDir.exists()); assertTrue(lvDir.exists());
} }
/** /**
@ -376,7 +377,7 @@ public class ChallengesAddonTest {
assertNull(addon.getChallengesSettings()); assertNull(addon.getChallengesSettings());
addon.onLoad(); addon.onLoad();
assertNotNull(addon.getChallengesSettings()); assertNotNull(addon.getChallengesSettings());
} }
/** /**

View File

@ -7,7 +7,6 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
@ -754,7 +753,6 @@ public class ChallengesManagerTest {
cm.deleteChallenge(challenge); cm.deleteChallenge(challenge);
ch = cm.getChallenge(cName); ch = cm.getChallenge(cName);
assertNull(ch); assertNull(ch);
verify(plhm).unregisterPlaceholder(eq("challenges_challenge_repetition_count_" + cName));
} }
/** /**

View File

@ -94,7 +94,7 @@ public class TryToCompleteTest {
private World world; private World world;
private String topLabel = "island"; private String topLabel = "island";
private String permissionPrefix = "perm."; private String permissionPrefix = "perm.";
private String cName;
private String levelName; private String levelName;
@Mock @Mock
private ChallengesManager cm; private ChallengesManager cm;
@ -160,8 +160,8 @@ public class TryToCompleteTest {
challenge.setRepeatable(true); challenge.setRepeatable(true);
challenge.setMaxTimes(10); challenge.setMaxTimes(10);
InventoryRequirements req = new InventoryRequirements(); InventoryRequirements req = new InventoryRequirements();
challenge.setRequirements(req); challenge.setRequirements(req);
// Util // Util
PowerMockito.mockStatic(Util.class); PowerMockito.mockStatic(Util.class);
when(Util.getWorld(any())).thenReturn(world); when(Util.getWorld(any())).thenReturn(world);
@ -184,7 +184,7 @@ public class TryToCompleteTest {
// Island flags - everything is allowed by default // Island flags - everything is allowed by default
when(island.isAllowed(any(), any())).thenReturn(true); when(island.isAllowed(any(), any())).thenReturn(true);
// Island // Island
@Nullable @Nullable
Location loc = mock(Location.class); Location loc = mock(Location.class);
when(loc.toString()).thenReturn("center"); when(loc.toString()).thenReturn("center");
@ -219,15 +219,15 @@ public class TryToCompleteTest {
PlaceholdersManager phm = mock(PlaceholdersManager.class); PlaceholdersManager phm = mock(PlaceholdersManager.class);
when(plugin.getPlaceholdersManager()).thenReturn(phm); when(plugin.getPlaceholdersManager()).thenReturn(phm);
when(phm.replacePlaceholders(any(), any())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(1, String.class)); when(phm.replacePlaceholders(any(), any())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(1, String.class));
// Survival by default // Survival by default
when(player.getGameMode()).thenReturn(GameMode.SURVIVAL); when(player.getGameMode()).thenReturn(GameMode.SURVIVAL);
// Addon // Addon
when(addon.getChallengesSettings()).thenReturn(settings); when(addon.getChallengesSettings()).thenReturn(settings);
when(settings.isBroadcastMessages()).thenReturn(true); when(settings.isBroadcastMessages()).thenReturn(true);
// Bukkit - online players // Bukkit - online players
Map<UUID, String> online = new HashMap<>(); Map<UUID, String> online = new HashMap<>();
Set<Player> onlinePlayers = new HashSet<>(); Set<Player> onlinePlayers = new HashSet<>();
@ -247,12 +247,12 @@ public class TryToCompleteTest {
when(mySettings.getWorldFlags()).thenReturn(map); when(mySettings.getWorldFlags()).thenReturn(map);
when(iwm.getWorldSettings(any())).thenReturn(mySettings); when(iwm.getWorldSettings(any())).thenReturn(mySettings);
ChallengesAddon.CHALLENGES_WORLD_PROTECTION.setSetting(world, true); ChallengesAddon.CHALLENGES_WORLD_PROTECTION.setSetting(world, true);
// ItemFactory // ItemFactory
ItemFactory itemFactory = mock(ItemFactory.class); ItemFactory itemFactory = mock(ItemFactory.class);
when(Bukkit.getItemFactory()).thenReturn(itemFactory); when(Bukkit.getItemFactory()).thenReturn(itemFactory);
} }
/** /**
* @throws java.lang.Exception * @throws java.lang.Exception
@ -285,7 +285,7 @@ public class TryToCompleteTest {
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("challenges.errors.not-deployed"); verify(user).sendMessage("challenges.errors.not-deployed");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -295,7 +295,7 @@ public class TryToCompleteTest {
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("general.errors.wrong-world"); verify(user).sendMessage("general.errors.wrong-world");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -306,7 +306,7 @@ public class TryToCompleteTest {
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("challenges.errors.not-on-island"); verify(user).sendMessage("challenges.errors.not-on-island");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -317,7 +317,7 @@ public class TryToCompleteTest {
assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("challenges.messages.you-completed-challenge", "[value]", "name"); verify(user).sendMessage("challenges.messages.you-completed-challenge", "[value]", "name");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -327,7 +327,7 @@ public class TryToCompleteTest {
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("challenges.errors.challenge-level-not-available"); verify(user).sendMessage("challenges.errors.challenge-level-not-available");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -338,7 +338,7 @@ public class TryToCompleteTest {
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("challenges.errors.not-repeatable"); verify(user).sendMessage("challenges.errors.not-repeatable");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -350,7 +350,7 @@ public class TryToCompleteTest {
assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("challenges.messages.you-completed-challenge", "[value]", "name"); verify(user).sendMessage("challenges.messages.you-completed-challenge", "[value]", "name");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -388,7 +388,7 @@ public class TryToCompleteTest {
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix, 100)); assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix, 100));
verify(user).sendMessage("challenges.errors.wrong-environment"); verify(user).sendMessage("challenges.errors.wrong-environment");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String, int)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String, int)}.
*/ */
@ -397,7 +397,7 @@ public class TryToCompleteTest {
InventoryRequirements req = new InventoryRequirements(); InventoryRequirements req = new InventoryRequirements();
req.setRequiredPermissions(Collections.singleton("perm-you-dont-have")); req.setRequiredPermissions(Collections.singleton("perm-you-dont-have"));
when(user.hasPermission(anyString())).thenReturn(false); when(user.hasPermission(anyString())).thenReturn(false);
challenge.setRequirements(req); challenge.setRequirements(req);
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix, 100)); assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix, 100));
verify(user).sendMessage("general.errors.no-permission"); verify(user).sendMessage("general.errors.no-permission");
} }
@ -410,7 +410,7 @@ public class TryToCompleteTest {
assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("challenges.messages.you-completed-challenge", "[value]", "name"); verify(user).sendMessage("challenges.messages.you-completed-challenge", "[value]", "name");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -418,28 +418,28 @@ public class TryToCompleteTest {
public void testCompleteChallengesAddonUserChallengeWorldStringStringSuccessSingleReq() { public void testCompleteChallengesAddonUserChallengeWorldStringStringSuccessSingleReq() {
InventoryRequirements req = new InventoryRequirements(); InventoryRequirements req = new InventoryRequirements();
req.setRequiredItems(Collections.singletonList(new ItemStack(Material.EMERALD_BLOCK))); req.setRequiredItems(Collections.singletonList(new ItemStack(Material.EMERALD_BLOCK)));
challenge.setRequirements(req); challenge.setRequirements(req);
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("challenges.errors.not-enough-items", "[items]", "Emerald Block"); verify(user).sendMessage("challenges.errors.not-enough-items", "[items]", "Emerald Block");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@Test @Test
public void testCompleteChallengesAddonUserChallengeWorldStringStringSuccessMultipleReq() { public void testCompleteChallengesAddonUserChallengeWorldStringStringSuccessMultipleReq() {
InventoryRequirements req = new InventoryRequirements(); InventoryRequirements req = new InventoryRequirements();
ItemStack itemStackMock = mock(ItemStack.class); ItemStack itemStackMock = mock(ItemStack.class);
when(itemStackMock.getAmount()).thenReturn(3); when(itemStackMock.getAmount()).thenReturn(3);
when(itemStackMock.getType()).thenReturn(Material.EMERALD_BLOCK); when(itemStackMock.getType()).thenReturn(Material.EMERALD_BLOCK);
when(itemStackMock.clone()).thenReturn(itemStackMock); when(itemStackMock.clone()).thenReturn(itemStackMock);
ItemStack itemStackMock2 = mock(ItemStack.class); ItemStack itemStackMock2 = mock(ItemStack.class);
when(itemStackMock2.getType()).thenReturn(Material.ENCHANTED_BOOK); when(itemStackMock2.getType()).thenReturn(Material.ENCHANTED_BOOK);
when(itemStackMock2.getAmount()).thenReturn(10); when(itemStackMock2.getAmount()).thenReturn(10);
when(itemStackMock2.clone()).thenReturn(itemStackMock2); when(itemStackMock2.clone()).thenReturn(itemStackMock2);
ItemStack itemStackMock3 = mock(ItemStack.class); ItemStack itemStackMock3 = mock(ItemStack.class);
when(itemStackMock3.getType()).thenReturn(Material.EMERALD_BLOCK); when(itemStackMock3.getType()).thenReturn(Material.EMERALD_BLOCK);
when(itemStackMock3.getAmount()).thenReturn(15); when(itemStackMock3.getAmount()).thenReturn(15);
@ -447,9 +447,9 @@ public class TryToCompleteTest {
// itemStackMock and 3 are same type // itemStackMock and 3 are same type
when(itemStackMock3.isSimilar(eq(itemStackMock))).thenReturn(true); when(itemStackMock3.isSimilar(eq(itemStackMock))).thenReturn(true);
when(itemStackMock.isSimilar(eq(itemStackMock3))).thenReturn(true); when(itemStackMock.isSimilar(eq(itemStackMock3))).thenReturn(true);
req.setRequiredItems(Arrays.asList(itemStackMock , itemStackMock2)); req.setRequiredItems(Arrays.asList(itemStackMock , itemStackMock2));
challenge.setRequirements(req); challenge.setRequirements(req);
ItemStack[] newContents = {itemStackMock3}; ItemStack[] newContents = {itemStackMock3};
when(inv.getContents()).thenReturn(newContents); when(inv.getContents()).thenReturn(newContents);
@ -459,7 +459,7 @@ public class TryToCompleteTest {
// Not enough books // Not enough books
verify(user).sendMessage("challenges.errors.not-enough-items", "[items]", "Enchanted Book"); verify(user).sendMessage("challenges.errors.not-enough-items", "[items]", "Enchanted Book");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -469,7 +469,7 @@ public class TryToCompleteTest {
assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("challenges.messages.you-completed-challenge", "[value]", "name"); verify(user).sendMessage("challenges.messages.you-completed-challenge", "[value]", "name");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -478,15 +478,15 @@ public class TryToCompleteTest {
challenge.setChallengeType(ChallengeType.ISLAND); challenge.setChallengeType(ChallengeType.ISLAND);
IslandRequirements req = new IslandRequirements(); IslandRequirements req = new IslandRequirements();
req.setSearchRadius(1); req.setSearchRadius(1);
challenge.setRequirements(req); challenge.setRequirements(req);
// Trigger big bounding box error // Trigger big bounding box error
when(bb.getWidthX()).thenReturn(50000D); when(bb.getWidthX()).thenReturn(50000D);
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(addon).logError("BoundingBox is larger than SearchRadius. | BoundingBox: BoundingBox | Search Distance: 1 | Location: location | Center: center | Range: 0"); verify(addon).logError("BoundingBox is larger than SearchRadius. | BoundingBox: BoundingBox | Search Distance: 1 | Location: location | Center: center | Range: 0");
verify(bb).expand(1); verify(bb).expand(1);
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -495,12 +495,12 @@ public class TryToCompleteTest {
challenge.setChallengeType(ChallengeType.ISLAND); challenge.setChallengeType(ChallengeType.ISLAND);
IslandRequirements req = new IslandRequirements(); IslandRequirements req = new IslandRequirements();
req.setSearchRadius(1); req.setSearchRadius(1);
challenge.setRequirements(req); challenge.setRequirements(req);
assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("challenges.messages.you-completed-challenge", "[value]", "name"); verify(user).sendMessage("challenges.messages.you-completed-challenge", "[value]", "name");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -511,12 +511,12 @@ public class TryToCompleteTest {
Map<EntityType, Integer> requiredEntities = Collections.singletonMap(EntityType.GHAST, 3); Map<EntityType, Integer> requiredEntities = Collections.singletonMap(EntityType.GHAST, 3);
req.setRequiredEntities(requiredEntities); req.setRequiredEntities(requiredEntities);
req.setSearchRadius(1); req.setSearchRadius(1);
challenge.setRequirements(req); challenge.setRequirements(req);
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("challenges.errors.you-still-need", "[amount]", "3", "[item]", "Ghast"); verify(user).sendMessage("challenges.errors.you-still-need", "[amount]", "3", "[item]", "Ghast");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -530,14 +530,14 @@ public class TryToCompleteTest {
requiredEntities.put(EntityType.PUFFERFISH, 1); requiredEntities.put(EntityType.PUFFERFISH, 1);
req.setRequiredEntities(requiredEntities); req.setRequiredEntities(requiredEntities);
req.setSearchRadius(1); req.setSearchRadius(1);
challenge.setRequirements(req); challenge.setRequirements(req);
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix)); assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
verify(user).sendMessage("challenges.errors.you-still-need", "[amount]", "3", "[item]", "Ghast"); verify(user).sendMessage("challenges.errors.you-still-need", "[amount]", "3", "[item]", "Ghast");
verify(user).sendMessage("challenges.errors.you-still-need", "[amount]", "1", "[item]", "Pufferfish"); verify(user).sendMessage("challenges.errors.you-still-need", "[amount]", "1", "[item]", "Pufferfish");
verify(user).sendMessage("challenges.errors.you-still-need", "[amount]", "5", "[item]", "Chicken"); verify(user).sendMessage("challenges.errors.you-still-need", "[amount]", "5", "[item]", "Chicken");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -551,7 +551,7 @@ public class TryToCompleteTest {
requiredEntities.put(EntityType.PUFFERFISH, 1); requiredEntities.put(EntityType.PUFFERFISH, 1);
req.setRequiredEntities(requiredEntities); req.setRequiredEntities(requiredEntities);
req.setSearchRadius(1); req.setSearchRadius(1);
challenge.setRequirements(req); challenge.setRequirements(req);
Entity ent = mock(Entity.class); Entity ent = mock(Entity.class);
when(ent.getType()).thenReturn(EntityType.PUFFERFISH); when(ent.getType()).thenReturn(EntityType.PUFFERFISH);
Location loc = mock(Location.class); Location loc = mock(Location.class);
@ -562,9 +562,9 @@ public class TryToCompleteTest {
verify(user).sendMessage("challenges.errors.you-still-need", "[amount]", "3", "[item]", "Ghast"); verify(user).sendMessage("challenges.errors.you-still-need", "[amount]", "3", "[item]", "Ghast");
verify(user, never()).sendMessage("challenges.errors.you-still-need", "[amount]", "1", "[item]", "Pufferfish"); verify(user, never()).sendMessage("challenges.errors.you-still-need", "[amount]", "1", "[item]", "Pufferfish");
verify(user).sendMessage("challenges.errors.you-still-need", "[amount]", "5", "[item]", "Chicken"); verify(user).sendMessage("challenges.errors.you-still-need", "[amount]", "5", "[item]", "Chicken");
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#complete(world.bentobox.challenges.ChallengesAddon, world.bentobox.bentobox.api.user.User, world.bentobox.challenges.database.object.Challenge, org.bukkit.World, java.lang.String, java.lang.String)}.
*/ */
@ -576,7 +576,7 @@ public class TryToCompleteTest {
requiredEntities.put(EntityType.PUFFERFISH, 1); requiredEntities.put(EntityType.PUFFERFISH, 1);
req.setRequiredEntities(requiredEntities); req.setRequiredEntities(requiredEntities);
req.setSearchRadius(1); req.setSearchRadius(1);
challenge.setRequirements(req); challenge.setRequirements(req);
Entity ent = mock(Entity.class); Entity ent = mock(Entity.class);
when(ent.getType()).thenReturn(EntityType.PUFFERFISH); when(ent.getType()).thenReturn(EntityType.PUFFERFISH);
Location loc = mock(Location.class); Location loc = mock(Location.class);
@ -604,15 +604,17 @@ public class TryToCompleteTest {
public void testBuild() { public void testBuild() {
this.testTryToCompleteChallengesAddonUserChallengeWorldStringString(); this.testTryToCompleteChallengesAddonUserChallengeWorldStringString();
ChallengeResult result = this.ttc.build(10); ChallengeResult result = this.ttc.build(10);
assertTrue(result.isMeetsRequirements());
} }
/** /**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#removeItems(java.util.List, int)}. * Test method for {@link world.bentobox.challenges.tasks.TryToComplete#removeItems(java.util.List, int)}.
*/ */
@Test @Test
public void testRemoveItems() { public void testRemoveItemsNothing() {
this.testTryToCompleteChallengesAddonUserChallengeWorldStringString(); this.testTryToCompleteChallengesAddonUserChallengeWorldStringString();
ttc.removeItems(Collections.emptyList(), 1); assertTrue(ttc.removeItems(Collections.emptyList(), 1).isEmpty());
} }
} }

View File

@ -36,198 +36,207 @@ import world.bentobox.challenges.ChallengesAddon;
@PrepareForTest({ Bukkit.class}) @PrepareForTest({ Bukkit.class})
public class TryToCompleteTestOld { public class TryToCompleteTestOld {
private User user; private User user;
ItemStack[] stacks = { new ItemStack(Material.PAPER, 32), ItemStack[] stacks = { new ItemStack(Material.PAPER, 32),
new ItemStack(Material.ACACIA_BOAT), new ItemStack(Material.ACACIA_BOAT),
null, null,
null, null,
new ItemStack(Material.CACTUS, 32), new ItemStack(Material.CACTUS, 32),
new ItemStack(Material.CACTUS, 32), new ItemStack(Material.CACTUS, 32),
new ItemStack(Material.CACTUS, 32), new ItemStack(Material.CACTUS, 32),
new ItemStack(Material.BRICK_STAIRS, 64), new ItemStack(Material.BRICK_STAIRS, 64),
new ItemStack(Material.BRICK_STAIRS, 64), new ItemStack(Material.BRICK_STAIRS, 64),
new ItemStack(Material.BRICK_STAIRS, 5), new ItemStack(Material.BRICK_STAIRS, 5),
new ItemStack(Material.GOLD_BLOCK, 32) new ItemStack(Material.GOLD_BLOCK, 32)
}; };
List<ItemStack> required; List<ItemStack> required;
private ChallengesAddon addon; private ChallengesAddon addon;
private PlayerInventory inv; private PlayerInventory inv;
/** /**
* @throws java.lang.Exception * @throws java.lang.Exception
*/ */
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
Server server = mock(Server.class); Server server = mock(Server.class);
PowerMockito.mockStatic(Bukkit.class); PowerMockito.mockStatic(Bukkit.class);
when(Bukkit.getServer()).thenReturn(server); when(Bukkit.getServer()).thenReturn(server);
when(Bukkit.getBukkitVersion()).thenReturn("1.13.2"); when(Bukkit.getBukkitVersion()).thenReturn("1.13.2");
user = mock(User.class); user = mock(User.class);
inv = mock(PlayerInventory.class); inv = mock(PlayerInventory.class);
when(inv.getContents()).thenReturn(stacks); when(inv.getContents()).thenReturn(stacks);
when(user.getInventory()).thenReturn(inv); when(user.getInventory()).thenReturn(inv);
addon = mock(ChallengesAddon.class); addon = mock(ChallengesAddon.class);
required = new ArrayList<>(); required = new ArrayList<>();
ItemFactory itemFactory = mock(ItemFactory.class); ItemFactory itemFactory = mock(ItemFactory.class);
when(server.getItemFactory()).thenReturn(itemFactory); when(server.getItemFactory()).thenReturn(itemFactory);
// Test will not work with items that has meta data. // Test will not work with items that has meta data.
when(itemFactory.getItemMeta(any())).thenReturn(null); when(itemFactory.getItemMeta(any())).thenReturn(null);
when(itemFactory.equals(null, null)).thenReturn(true); when(itemFactory.equals(null, null)).thenReturn(true);
when(Bukkit.getItemFactory()).thenReturn(itemFactory); when(Bukkit.getItemFactory()).thenReturn(itemFactory);
when(Bukkit.getLogger()).thenReturn(Logger.getAnonymousLogger()); when(Bukkit.getLogger()).thenReturn(Logger.getAnonymousLogger());
} }
/** /**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}. * Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/ */
@Test @SuppressWarnings("deprecation")
public void testRemoveItemsSuccess() { @Test
Material requiredMaterial = Material.PAPER; public void testRemoveItemsSuccess() {
int requiredQuantity = 21; Material requiredMaterial = Material.PAPER;
int requiredQuantity = 21;
this.required.add(new ItemStack(requiredMaterial, requiredQuantity)); this.required.add(new ItemStack(requiredMaterial, requiredQuantity));
TryToComplete x = new TryToComplete(this.addon); TryToComplete x = new TryToComplete(this.addon);
x.user(this.user); x.user(this.user);
Map<ItemStack, Integer> removed = x.removeItems(this.required, 1); Map<ItemStack, Integer> removed = x.removeItems(this.required, 1);
assertEquals((int) removed.getOrDefault(new ItemStack(requiredMaterial, 1), 0), requiredQuantity); assertEquals((int) removed.getOrDefault(new ItemStack(requiredMaterial, 1), 0), requiredQuantity);
} }
/** /**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}. * Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/ */
@Test @SuppressWarnings("deprecation")
public void testRemoveItemsMax() { @Test
Material requiredMaterial = Material.PAPER; public void testRemoveItemsMax() {
int requiredQuantity = 50; Material requiredMaterial = Material.PAPER;
int requiredQuantity = 50;
this.required.add(new ItemStack(requiredMaterial, requiredQuantity)); this.required.add(new ItemStack(requiredMaterial, requiredQuantity));
TryToComplete x = new TryToComplete(this.addon); TryToComplete x = new TryToComplete(this.addon);
x.user(this.user); x.user(this.user);
Map<ItemStack, Integer> removed = x.removeItems(this.required, 1); Map<ItemStack, Integer> removed = x.removeItems(this.required, 1);
assertNotEquals((int) removed.getOrDefault(new ItemStack(requiredMaterial, 1), 0), requiredQuantity); assertNotEquals((int) removed.getOrDefault(new ItemStack(requiredMaterial, 1), 0), requiredQuantity);
} }
/** /**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}. * Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/ */
@Test @SuppressWarnings("deprecation")
public void testRemoveItemsZero() { @Test
Material requiredMaterial = Material.PAPER; public void testRemoveItemsZero() {
int requiredQuantity = 0; Material requiredMaterial = Material.PAPER;
int requiredQuantity = 0;
this.required.add(new ItemStack(requiredMaterial, requiredQuantity)); this.required.add(new ItemStack(requiredMaterial, requiredQuantity));
TryToComplete x = new TryToComplete(this.addon); TryToComplete x = new TryToComplete(this.addon);
x.user(this.user); x.user(this.user);
Map<ItemStack, Integer> removed = x.removeItems(this.required, 1); Map<ItemStack, Integer> removed = x.removeItems(this.required, 1);
assertTrue(removed.isEmpty()); assertTrue(removed.isEmpty());
} }
/** /**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}. * Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/ */
@Test @SuppressWarnings("deprecation")
public void testRemoveItemsSuccessMultiple() { @Test
required.add(new ItemStack(Material.PAPER, 11)); public void testRemoveItemsSuccessMultiple() {
required.add(new ItemStack(Material.PAPER, 5)); required.add(new ItemStack(Material.PAPER, 11));
required.add(new ItemStack(Material.PAPER, 5)); required.add(new ItemStack(Material.PAPER, 5));
TryToComplete x = new TryToComplete(addon); required.add(new ItemStack(Material.PAPER, 5));
x.user(user); TryToComplete x = new TryToComplete(addon);
Map<ItemStack, Integer> removed = x.removeItems(required, 1); x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 1);
assertEquals((int) removed.getOrDefault(new ItemStack(Material.PAPER, 1), 0), 21); assertEquals((int) removed.getOrDefault(new ItemStack(Material.PAPER, 1), 0), 21);
} }
/** /**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}. * Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/ */
@Test @SuppressWarnings("deprecation")
public void testRemoveItemsSuccessMultipleOther() { @Test
required.add(new ItemStack(Material.CACTUS, 5)); public void testRemoveItemsSuccessMultipleOther() {
required.add(new ItemStack(Material.PAPER, 11)); required.add(new ItemStack(Material.CACTUS, 5));
required.add(new ItemStack(Material.PAPER, 5)); required.add(new ItemStack(Material.PAPER, 11));
required.add(new ItemStack(Material.PAPER, 5)); required.add(new ItemStack(Material.PAPER, 5));
required.add(new ItemStack(Material.CACTUS, 5)); required.add(new ItemStack(Material.PAPER, 5));
TryToComplete x = new TryToComplete(addon); required.add(new ItemStack(Material.CACTUS, 5));
x.user(user); TryToComplete x = new TryToComplete(addon);
Map<ItemStack, Integer> removed = x.removeItems(required, 1); x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 1);
assertEquals((int) removed.getOrDefault(new ItemStack(Material.PAPER, 1), 0), 21); assertEquals((int) removed.getOrDefault(new ItemStack(Material.PAPER, 1), 0), 21);
assertEquals((int) removed.getOrDefault(new ItemStack(Material.CACTUS, 1), 0), 10); assertEquals((int) removed.getOrDefault(new ItemStack(Material.CACTUS, 1), 0), 10);
} }
/** /**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}. * Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/ */
@Test @SuppressWarnings("deprecation")
public void testRemoveItemsMultipleOtherFail() { @Test
required.add(new ItemStack(Material.ACACIA_FENCE, 5)); public void testRemoveItemsMultipleOtherFail() {
required.add(new ItemStack(Material.ARROW, 11)); required.add(new ItemStack(Material.ACACIA_FENCE, 5));
required.add(new ItemStack(Material.STONE, 5)); required.add(new ItemStack(Material.ARROW, 11));
required.add(new ItemStack(Material.BAKED_POTATO, 5)); required.add(new ItemStack(Material.STONE, 5));
required.add(new ItemStack(Material.GHAST_SPAWN_EGG, 5)); required.add(new ItemStack(Material.BAKED_POTATO, 5));
TryToComplete x = new TryToComplete(addon); required.add(new ItemStack(Material.GHAST_SPAWN_EGG, 5));
x.user(user); TryToComplete x = new TryToComplete(addon);
Map<ItemStack, Integer> removed = x.removeItems(required, 1); x.user(user);
assertTrue(removed.isEmpty()); Map<ItemStack, Integer> removed = x.removeItems(required, 1);
} assertTrue(removed.isEmpty());
}
/** /**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}. * Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/ */
@Test @SuppressWarnings("deprecation")
public void testRemoveItemsFail() { @Test
ItemStack input = new ItemStack(Material.GOLD_BLOCK, 55); public void testRemoveItemsFail() {
required.add(input); ItemStack input = new ItemStack(Material.GOLD_BLOCK, 55);
TryToComplete x = new TryToComplete(addon); required.add(input);
x.user(user); TryToComplete x = new TryToComplete(addon);
Map<ItemStack, Integer> removed = x.removeItems(required, 1); x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 1);
// It will remove 32, but not any more // It will remove 32, but not any more
assertEquals((int) removed.getOrDefault(new ItemStack(Material.GOLD_BLOCK, 1), 0), 32); assertEquals((int) removed.getOrDefault(new ItemStack(Material.GOLD_BLOCK, 1), 0), 32);
// An error will be thrown // An error will be thrown
Mockito.verify(addon, Mockito.times(1)).logError(Mockito.anyString()); Mockito.verify(addon, Mockito.times(1)).logError(Mockito.anyString());
} }
/** /**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}. * Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/ */
@Test @SuppressWarnings("deprecation")
public void testRequireTwoStacks() { @Test
required.add(new ItemStack(Material.BRICK_STAIRS, 64)); public void testRequireTwoStacks() {
required.add(new ItemStack(Material.BRICK_STAIRS, 64)); required.add(new ItemStack(Material.BRICK_STAIRS, 64));
required.add(new ItemStack(Material.BRICK_STAIRS, 64));
TryToComplete x = new TryToComplete(addon); TryToComplete x = new TryToComplete(addon);
x.user(user); x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 1); Map<ItemStack, Integer> removed = x.removeItems(required, 1);
// It should remove both stacks // It should remove both stacks
assertEquals((int) removed.getOrDefault(new ItemStack(Material.BRICK_STAIRS, 1), 0), 128); assertEquals((int) removed.getOrDefault(new ItemStack(Material.BRICK_STAIRS, 1), 0), 128);
} }
/** /**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}. * Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/ */
@Test @SuppressWarnings("deprecation")
public void testFactorStacks() { @Test
required.add(new ItemStack(Material.BRICK_STAIRS, 32)); public void testFactorStacks() {
required.add(new ItemStack(Material.BRICK_STAIRS, 32));
TryToComplete x = new TryToComplete(addon); TryToComplete x = new TryToComplete(addon);
x.user(user); x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 4); Map<ItemStack, Integer> removed = x.removeItems(required, 4);
// It should remove both stacks // It should remove both stacks
assertEquals((int) removed.getOrDefault(new ItemStack(Material.BRICK_STAIRS, 1), 0), 128); assertEquals((int) removed.getOrDefault(new ItemStack(Material.BRICK_STAIRS, 1), 0), 128);
} }
} }