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

View File

@ -48,9 +48,9 @@ import world.bentobox.challenges.utils.Utils;
*/
public class TryToComplete
{
// ---------------------------------------------------------------------
// Section: Variables
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// Section: Variables
// ---------------------------------------------------------------------
/**
* Challenges addon variable.
@ -92,9 +92,9 @@ public class TryToComplete
*/
private final ChallengeResult EMPTY_RESULT = new ChallengeResult();
// ---------------------------------------------------------------------
// Section: Builder
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// Section: Builder
// ---------------------------------------------------------------------
@Deprecated
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.
*/
public TryToComplete(ChallengesAddon addon,
User user,
Challenge challenge,
World world,
String topLabel,
String permissionPrefix)
User user,
Challenge challenge,
World world,
String topLabel,
String permissionPrefix)
{
this.addon = addon;
this.world = world;
@ -194,11 +194,11 @@ public class TryToComplete
* @return true, if challenge is completed, otherwise false.
*/
public static boolean complete(ChallengesAddon addon,
User user,
Challenge challenge,
World world,
String topLabel,
String permissionPrefix)
User user,
Challenge challenge,
World world,
String topLabel,
String permissionPrefix)
{
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.
*/
public static boolean complete(ChallengesAddon addon,
User user,
Challenge challenge,
World world,
String topLabel,
String permissionPrefix,
int maxTimes)
User user,
Challenge challenge,
World world,
String topLabel,
String permissionPrefix,
int maxTimes)
{
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);
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
// amount.
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
@ -308,8 +308,8 @@ public class TryToComplete
if (!player.getUniqueId().equals(this.user.getUniqueId()))
{
User.getInstance(player).sendMessage("challenges.messages.name-has-completed-challenge",
"[name]", this.user.getName(),
"[value]", this.challenge.getFriendlyName());
"[name]", this.user.getName(),
"[value]", this.challenge.getFriendlyName());
}
}
}
@ -318,11 +318,11 @@ public class TryToComplete
if (this.addon.getChallengesSettings().isShowCompletionTitle())
{
this.user.getPlayer().sendTitle(
this.parseChallenge(this.user.getTranslation("challenges.titles.challenge-title"), this.challenge),
this.parseChallenge(this.user.getTranslation("challenges.titles.challenge-subtitle"), this.challenge),
10,
this.addon.getChallengesSettings().getTitleShowtime(),
20);
this.parseChallenge(this.user.getTranslation("challenges.titles.challenge-title"), this.challenge),
this.parseChallenge(this.user.getTranslation("challenges.titles.challenge-subtitle"), this.challenge),
10,
this.addon.getChallengesSettings().getTitleShowtime(),
20);
}
}
@ -339,7 +339,7 @@ public class TryToComplete
for (int i = 0; i < rewardFactor; i++)
{
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())
{
this.addon.getEconomyProvider().deposit(this.user,
(double)this.challenge.getRepeatMoneyReward() * rewardFactor);
(double)this.challenge.getRepeatMoneyReward() * rewardFactor);
}
// Experience Repeat Reward
this.user.getPlayer().giveExp(
this.challenge.getRepeatExperienceReward() * rewardFactor);
this.challenge.getRepeatExperienceReward() * rewardFactor);
// Run commands
for (int i = 0; i < rewardFactor; i++)
@ -363,8 +363,8 @@ public class TryToComplete
if (result.getFactor() > 1)
{
this.user.sendMessage("challenges.messages.you-repeated-challenge-multiple",
"[value]", this.challenge.getFriendlyName(),
"[count]", Integer.toString(result.getFactor()));
"[value]", this.challenge.getFriendlyName(),
"[count]", Integer.toString(result.getFactor()));
}
else
{
@ -377,7 +377,7 @@ public class TryToComplete
// Check level completion for non-free challenges
if (!result.wasCompleted() &&
!this.challenge.getLevel().equals(ChallengesManager.FREE))
!this.challenge.getLevel().equals(ChallengesManager.FREE))
{
ChallengeLevel level = this.manager.getLevel(this.challenge);
@ -391,7 +391,7 @@ public class TryToComplete
// Clone is necessary because otherwise it will chane reward itemstack
// amount.
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
@ -416,7 +416,7 @@ public class TryToComplete
if (!player.getUniqueId().equals(this.user.getUniqueId()))
{
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())
{
this.user.getPlayer().sendTitle(
this.parseLevel(this.user.getTranslation("challenges.titles.level-title"), level),
this.parseLevel(this.user.getTranslation("challenges.titles.level-subtitle"), level),
10,
this.addon.getChallengesSettings().getTitleShowtime(),
20);
this.parseLevel(this.user.getTranslation("challenges.titles.level-title"), level),
this.parseLevel(this.user.getTranslation("challenges.titles.level-subtitle"), level),
10,
this.addon.getChallengesSettings().getTitleShowtime(),
20);
}
}
}
@ -452,15 +452,15 @@ public class TryToComplete
IslandRequirements requirements = this.challenge.getRequirements();
if (result.meetsRequirements &&
requirements.isRemoveEntities() &&
!requirements.getRequiredEntities().isEmpty())
requirements.isRemoveEntities() &&
!requirements.getRequiredEntities().isEmpty())
{
this.removeEntities(result.entities, result.getFactor());
}
if (result.meetsRequirements &&
requirements.isRemoveBlocks() &&
!requirements.getRequiredBlocks().isEmpty())
requirements.isRemoveBlocks() &&
!requirements.getRequiredBlocks().isEmpty())
{
this.removeBlocks(result.blocks, result.getFactor());
}
@ -471,11 +471,11 @@ public class TryToComplete
if (this.getInventoryRequirements().isTakeItems())
{
int sumEverything = result.requiredItems.stream().
mapToInt(itemStack -> itemStack.getAmount() * result.getFactor()).
sum();
mapToInt(itemStack -> itemStack.getAmount() * result.getFactor()).
sum();
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();
@ -499,11 +499,11 @@ public class TryToComplete
}
if (requirements.isTakeExperience() &&
this.user.getPlayer().getGameMode() != GameMode.CREATIVE)
this.user.getPlayer().getGameMode() != GameMode.CREATIVE)
{
// Cannot take anything from creative game mode.
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;
}
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");
result = EMPTY_RESULT;
}
// Player is not on island
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");
result = EMPTY_RESULT;
}
// Check player permission
else if (!this.addon.getIslands().getIslandAt(this.user.getLocation()).
map(i -> i.isAllowed(this.user, ChallengesAddon.CHALLENGES_ISLAND_PROTECTION)).
orElse(false))
map(i -> i.isAllowed(this.user, ChallengesAddon.CHALLENGES_ISLAND_PROTECTION)).
orElse(false))
{
this.user.sendMessage("challenges.errors.no-rank");
result = EMPTY_RESULT;
}
// Check if user has unlocked challenges level.
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");
result = EMPTY_RESULT;
}
// Check max times
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");
result = EMPTY_RESULT;
@ -573,7 +573,7 @@ public class TryToComplete
}
// Check environment
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");
result = EMPTY_RESULT;
@ -618,7 +618,7 @@ public class TryToComplete
private boolean checkPermissions()
{
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
{
if (!this.addon.getServer().dispatchCommand(this.addon.getServer().getConsoleSender(),
cmd.replace("[player]", this.user.getName())))
cmd.replace("[player]", this.user.getName())))
{
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()))
{
numInInventory =
Arrays.stream(this.user.getInventory().getContents()).
Arrays.stream(this.user.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
mapToInt(ItemStack::getAmount).
@ -747,7 +747,7 @@ public class TryToComplete
else
{
numInInventory =
Arrays.stream(this.user.getInventory().getContents()).
Arrays.stream(this.user.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
mapToInt(ItemStack::getAmount).
@ -757,8 +757,8 @@ public class TryToComplete
if (numInInventory < required.getAmount())
{
this.user.sendMessage("challenges.errors.not-enough-items",
"[items]",
Util.prettifyText(required.getType().toString()));
"[items]",
Util.prettifyText(required.getType().toString()));
return EMPTY_RESULT;
}
@ -772,9 +772,9 @@ public class TryToComplete
// Return the result
return new ChallengeResult().
setMeetsRequirements().
setCompleteFactor(maxTimes).
setRequiredItems(requiredItems);
setMeetsRequirements().
setCompleteFactor(maxTimes).
setRequiredItems(requiredItems);
}
@ -790,26 +790,24 @@ public class TryToComplete
for (ItemStack required : requiredItemList)
{
int amountToBeRemoved = required.getAmount() * factor;
List<ItemStack> itemsInInventory;
if (Utils.canIgnoreMeta(required.getType()))
{
// Use collecting method that ignores item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
collect(Collectors.toList());
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
collect(Collectors.toList());
}
else
{
// Use collecting method that compares item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
collect(Collectors.toList());
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
collect(Collectors.toList());
}
for (ItemStack itemStack : itemsInInventory)
{
if (amountToBeRemoved > 0)
@ -836,7 +834,7 @@ public class TryToComplete
if (amountToBeRemoved > 0)
{
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.
Island island = this.addon.getIslands().getIsland(this.world, this.user);
if (island == null) {
// Just in case. Should never hit because there is a check if the player is on this island further up
return EMPTY_RESULT;
@ -907,15 +905,15 @@ public class TryToComplete
// Protection code. Do not allow to select too large region for completing challenge.
if (boundingBox.getWidthX() > distance * 2 + 3 ||
boundingBox.getWidthZ() > distance * 2 + 3 ||
boundingBox.getHeight() > distance * 2 + 3)
boundingBox.getWidthZ() > distance * 2 + 3 ||
boundingBox.getHeight() > distance * 2 + 3)
{
this.addon.logError("BoundingBox is larger than SearchRadius. " +
" | BoundingBox: " + boundingBox.toString() +
" | Search Distance: " + requirements.getSearchRadius() +
" | Location: " + this.user.getLocation().toString() +
" | Center: " + island.getCenter().toString() +
" | Range: " + range);
" | BoundingBox: " + boundingBox.toString() +
" | Search Distance: " + requirements.getSearchRadius() +
" | Location: " + this.user.getLocation().toString() +
" | Center: " + island.getCenter().toString() +
" | Range: " + range);
return EMPTY_RESULT;
}
@ -952,15 +950,15 @@ public class TryToComplete
// This queue will contain only blocks whit required type ordered by distance till player.
Queue<Block> blockFromWorld = new PriorityQueue<>((o1, o2) -> {
if (o1.getType().equals(o2.getType()))
{
return Double.compare(o1.getLocation().distance(this.user.getLocation()),
o2.getLocation().distance(this.user.getLocation()));
}
else
{
return o1.getType().compareTo(o2.getType());
}
if (o1.getType().equals(o2.getType()))
{
return Double.compare(o1.getLocation().distance(this.user.getLocation()),
o2.getLocation().distance(this.user.getLocation()));
}
else
{
return o1.getType().compareTo(o2.getType());
}
});
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())
{
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",
"[number]",
String.valueOf(this.getIslandRequirements().getSearchRadius()));
"[number]",
String.valueOf(this.getIslandRequirements().getSearchRadius()));
blocks.forEach((k, v) -> user.sendMessage("challenges.errors.you-still-need",
"[amount]", String.valueOf(v),
"[item]", Util.prettifyText(k.toString())));
"[amount]", String.valueOf(v),
"[item]", Util.prettifyText(k.toString())));
// kick garbage collector
@ -1038,8 +1036,8 @@ public class TryToComplete
* @return ChallengeResult
*/
private ChallengeResult searchForEntities(Map<EntityType, Integer> requiredMap,
int factor,
BoundingBox boundingBox)
int factor,
BoundingBox boundingBox)
{
if (requiredMap.isEmpty())
{
@ -1055,7 +1053,7 @@ public class TryToComplete
if (o1.getType().equals(o2.getType()))
{
return Double.compare(o1.getLocation().distance(this.user.getLocation()),
o2.getLocation().distance(this.user.getLocation()));
o2.getLocation().distance(this.user.getLocation()));
}
else
{
@ -1067,7 +1065,7 @@ public class TryToComplete
// Check if entity is inside challenge bounding box
if (requiredMap.containsKey(entity.getType()))
{
entityQueue.add(entity);
entityQueue.add(entity);
entitiesFound.putIfAbsent(entity.getType(), 1);
entitiesFound.computeIfPresent(entity.getType(), (reqEntity, amount) -> amount + 1);
@ -1087,7 +1085,7 @@ public class TryToComplete
for (Map.Entry<EntityType, Integer> entry : entitiesFound.entrySet())
{
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",
"[amount]", String.valueOf(amount),
"[item]", Util.prettifyText(reqEnt.toString())));
"[amount]", String.valueOf(amount),
"[item]", Util.prettifyText(reqEnt.toString())));
// Kick garbage collector
entitiesFound.clear();
@ -1142,26 +1140,26 @@ public class TryToComplete
private void removeEntities(Queue<Entity> entityQueue, int factor)
{
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.
entities.entrySet().forEach(entry -> entry.setValue(entry.getValue() * factor));
// Increase required entities by factor.
entities.entrySet().forEach(entry -> entry.setValue(entry.getValue() * factor));
// Go through entity queue and remove entities that are requried.
entityQueue.forEach(entity -> {
if (entities.containsKey(entity.getType()))
{
entities.computeIfPresent(entity.getType(), (reqEntity, amount) -> amount - 1);
entities.entrySet().removeIf(e -> e.getValue() == 0);
entity.remove();
}
});
// Go through entity queue and remove entities that are requried.
entityQueue.forEach(entity -> {
if (entities.containsKey(entity.getType()))
{
entities.computeIfPresent(entity.getType(), (reqEntity, amount) -> amount - 1);
entities.entrySet().removeIf(e -> e.getValue() == 0);
entity.remove();
}
});
}
// ---------------------------------------------------------------------
// Section: Other challenge
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// Section: Other challenge
// ---------------------------------------------------------------------
/**
@ -1173,60 +1171,60 @@ public class TryToComplete
{
OtherRequirements requirements = this.getOtherRequirements();
if (!this.addon.isLevelProvided() &&
requirements.getRequiredIslandLevel() != 0)
{
this.user.sendMessage("challenges.errors.missing-addon");
}
else if (!this.addon.isEconomyProvided() &&
requirements.getRequiredMoney() != 0)
{
this.user.sendMessage("challenges.errors.missing-addon");
}
else if (this.addon.isEconomyProvided() && requirements.getRequiredMoney() < 0)
{
this.user.sendMessage("challenges.errors.incorrect");
}
else if (this.addon.isEconomyProvided() &&
!this.addon.getEconomyProvider().has(this.user, requirements.getRequiredMoney()))
if (!this.addon.isLevelProvided() &&
requirements.getRequiredIslandLevel() != 0)
{
this.user.sendMessage("challenges.errors.missing-addon");
}
else if (!this.addon.isEconomyProvided() &&
requirements.getRequiredMoney() != 0)
{
this.user.sendMessage("challenges.errors.missing-addon");
}
else if (this.addon.isEconomyProvided() && requirements.getRequiredMoney() < 0)
{
this.user.sendMessage("challenges.errors.incorrect");
}
else if (this.addon.isEconomyProvided() &&
!this.addon.getEconomyProvider().has(this.user, requirements.getRequiredMoney()))
{
this.user.sendMessage("challenges.errors.not-enough-money",
"[value]",
Double.toString(requirements.getRequiredMoney()));
"[value]",
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() &&
this.user.getPlayer().getGameMode() != GameMode.CREATIVE)
this.user.getPlayer().getGameMode() != GameMode.CREATIVE)
{
// Players in creative gamemode has infinite amount of EXP.
this.user.sendMessage("challenges.errors.not-enough-experience",
"[value]",
Integer.toString(requirements.getRequiredExperience()));
"[value]",
Integer.toString(requirements.getRequiredExperience()));
}
else if (this.addon.isLevelProvided() &&
this.addon.getLevelAddon().getIslandLevel(this.world, this.user.getUniqueId()) < requirements.getRequiredIslandLevel())
else if (this.addon.isLevelProvided() &&
this.addon.getLevelAddon().getIslandLevel(this.world, this.user.getUniqueId()) < requirements.getRequiredIslandLevel())
{
this.user.sendMessage("challenges.errors.island-level",
TextVariables.NUMBER,
String.valueOf(requirements.getRequiredIslandLevel()));
TextVariables.NUMBER,
String.valueOf(requirements.getRequiredIslandLevel()));
}
else
{
// calculate factor
// calculate factor
if (this.addon.isEconomyProvided() && requirements.isTakeMoney())
{
factor = Math.min(factor, (int) (this.addon.getEconomyProvider().getBalance(this.user) / requirements.getRequiredMoney()));
}
if (this.addon.isEconomyProvided() && requirements.isTakeMoney())
{
factor = Math.min(factor, (int) (this.addon.getEconomyProvider().getBalance(this.user) / requirements.getRequiredMoney()));
}
if (requirements.getRequiredExperience() > 0 && requirements.isTakeExperience())
{
factor = Math.min(factor, this.user.getPlayer().getTotalExperience() / requirements.getRequiredExperience());
}
if (requirements.getRequiredExperience() > 0 && requirements.isTakeExperience())
{
factor = Math.min(factor, this.user.getPlayer().getTotalExperience() / requirements.getRequiredExperience());
}
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.
*/
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
*
*/
@SuppressWarnings("deprecation")
@RunWith(PowerMockRunner.class)
@PrepareForTest({Bukkit.class, BentoBox.class, User.class, Config.class })
public class ChallengesAddonTest {
@ -179,7 +180,7 @@ public class ChallengesAddonTest {
when(gameMode.getPlayerCommand()).thenReturn(opCmd);
// Admin command
when(gameMode.getAdminCommand()).thenReturn(opCmd);
// Flags manager
when(plugin.getFlagsManager()).thenReturn(fm);
when(fm.getFlags()).thenReturn(Collections.emptyList());
@ -188,9 +189,9 @@ public class ChallengesAddonTest {
when(plugin.getSettings()).thenReturn(settings);
DatabaseType value = DatabaseType.JSON;
when(settings.getDatabaseType()).thenReturn(value);
// Bukkit
PowerMockito.mockStatic(Bukkit.class);
PowerMockito.mockStatic(Bukkit.class);
when(Bukkit.getScheduler()).thenReturn(scheduler);
ItemMeta meta = mock(ItemMeta.class);
ItemFactory itemFactory = mock(ItemFactory.class);
@ -199,7 +200,7 @@ public class ChallengesAddonTest {
UnsafeValues unsafe = mock(UnsafeValues.class);
when(unsafe.getDataVersion()).thenReturn(777);
when(Bukkit.getUnsafe()).thenReturn(unsafe);
}
@ -212,7 +213,7 @@ public class ChallengesAddonTest {
new File("config.yml").delete();
deleteAll(new File("addons"));
deleteAll(new File("database"));
}
private void deleteAll(File file) throws IOException {
@ -222,7 +223,7 @@ public class ChallengesAddonTest {
.map(Path::toFile)
.forEach(File::delete);
}
}
/**
@ -235,7 +236,7 @@ public class ChallengesAddonTest {
File check = new File("addons/Challenges","config.yml");
assertTrue(check.exists());
}
/**
* 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!");
assertEquals(Addon.State.DISABLED, addon.getState());
}
/**
* Test method for {@link world.bentobox.challenges.ChallengesAddon#onEnable()}.
*/
@Test
public void testOnEnableDisabledAddon() {
public void testOnEnableDisabledAddon() {
when(plugin.isEnabled()).thenReturn(true);
addon.setState(State.DISABLED);
addon.onEnable();
verify(plugin).logError("[challenges] Challenges Addon is not available or disabled!");
}
/**
* 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.");
assertEquals(State.INCOMPATIBLE, addon.getState());
}
/**
* 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).log("[challenges] Loading challenges...");
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()}.
*/
@ -302,7 +303,7 @@ public class ChallengesAddonTest {
addon.onEnable();
verify(plugin).log("[challenges] Loading challenges...");
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();
verify(plugin, never()).log(anyString());
}
/**
* Test method for {@link world.bentobox.challenges.ChallengesAddon#onDisable()}.
*/
@ -327,7 +328,7 @@ public class ChallengesAddonTest {
assertTrue(chDir.exists());
File lvDir = new File("database", "ChallengeLevel");
assertTrue(lvDir.exists());
}
/**
@ -376,7 +377,7 @@ public class ChallengesAddonTest {
assertNull(addon.getChallengesSettings());
addon.onLoad();
assertNotNull(addon.getChallengesSettings());
}
/**

View File

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

View File

@ -94,7 +94,7 @@ public class TryToCompleteTest {
private World world;
private String topLabel = "island";
private String permissionPrefix = "perm.";
private String cName;
private String levelName;
@Mock
private ChallengesManager cm;
@ -160,8 +160,8 @@ public class TryToCompleteTest {
challenge.setRepeatable(true);
challenge.setMaxTimes(10);
InventoryRequirements req = new InventoryRequirements();
challenge.setRequirements(req);
challenge.setRequirements(req);
// Util
PowerMockito.mockStatic(Util.class);
when(Util.getWorld(any())).thenReturn(world);
@ -184,7 +184,7 @@ public class TryToCompleteTest {
// Island flags - everything is allowed by default
when(island.isAllowed(any(), any())).thenReturn(true);
// Island
@Nullable
Location loc = mock(Location.class);
when(loc.toString()).thenReturn("center");
@ -219,15 +219,15 @@ public class TryToCompleteTest {
PlaceholdersManager phm = mock(PlaceholdersManager.class);
when(plugin.getPlaceholdersManager()).thenReturn(phm);
when(phm.replacePlaceholders(any(), any())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(1, String.class));
// Survival by default
when(player.getGameMode()).thenReturn(GameMode.SURVIVAL);
// Addon
when(addon.getChallengesSettings()).thenReturn(settings);
when(settings.isBroadcastMessages()).thenReturn(true);
// Bukkit - online players
// Bukkit - online players
Map<UUID, String> online = new HashMap<>();
Set<Player> onlinePlayers = new HashSet<>();
@ -247,12 +247,12 @@ public class TryToCompleteTest {
when(mySettings.getWorldFlags()).thenReturn(map);
when(iwm.getWorldSettings(any())).thenReturn(mySettings);
ChallengesAddon.CHALLENGES_WORLD_PROTECTION.setSetting(world, true);
// ItemFactory
ItemFactory itemFactory = mock(ItemFactory.class);
when(Bukkit.getItemFactory()).thenReturn(itemFactory);
}
}
/**
* @throws java.lang.Exception
@ -285,7 +285,7 @@ public class TryToCompleteTest {
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
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)}.
*/
@ -295,7 +295,7 @@ public class TryToCompleteTest {
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
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)}.
*/
@ -306,7 +306,7 @@ public class TryToCompleteTest {
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
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)}.
*/
@ -317,7 +317,7 @@ public class TryToCompleteTest {
assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
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)}.
*/
@ -327,7 +327,7 @@ public class TryToCompleteTest {
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
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)}.
*/
@ -338,7 +338,7 @@ public class TryToCompleteTest {
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
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)}.
*/
@ -350,7 +350,7 @@ public class TryToCompleteTest {
assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
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)}.
*/
@ -388,7 +388,7 @@ public class TryToCompleteTest {
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix, 100));
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)}.
*/
@ -397,7 +397,7 @@ public class TryToCompleteTest {
InventoryRequirements req = new InventoryRequirements();
req.setRequiredPermissions(Collections.singleton("perm-you-dont-have"));
when(user.hasPermission(anyString())).thenReturn(false);
challenge.setRequirements(req);
challenge.setRequirements(req);
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix, 100));
verify(user).sendMessage("general.errors.no-permission");
}
@ -410,7 +410,7 @@ public class TryToCompleteTest {
assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
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)}.
*/
@ -418,28 +418,28 @@ public class TryToCompleteTest {
public void testCompleteChallengesAddonUserChallengeWorldStringStringSuccessSingleReq() {
InventoryRequirements req = new InventoryRequirements();
req.setRequiredItems(Collections.singletonList(new ItemStack(Material.EMERALD_BLOCK)));
challenge.setRequirements(req);
challenge.setRequirements(req);
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
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
public void testCompleteChallengesAddonUserChallengeWorldStringStringSuccessMultipleReq() {
InventoryRequirements req = new InventoryRequirements();
ItemStack itemStackMock = mock(ItemStack.class);
when(itemStackMock.getAmount()).thenReturn(3);
when(itemStackMock.getType()).thenReturn(Material.EMERALD_BLOCK);
when(itemStackMock.clone()).thenReturn(itemStackMock);
ItemStack itemStackMock2 = mock(ItemStack.class);
when(itemStackMock2.getType()).thenReturn(Material.ENCHANTED_BOOK);
when(itemStackMock2.getAmount()).thenReturn(10);
when(itemStackMock2.clone()).thenReturn(itemStackMock2);
ItemStack itemStackMock3 = mock(ItemStack.class);
when(itemStackMock3.getType()).thenReturn(Material.EMERALD_BLOCK);
when(itemStackMock3.getAmount()).thenReturn(15);
@ -447,9 +447,9 @@ public class TryToCompleteTest {
// itemStackMock and 3 are same type
when(itemStackMock3.isSimilar(eq(itemStackMock))).thenReturn(true);
when(itemStackMock.isSimilar(eq(itemStackMock3))).thenReturn(true);
req.setRequiredItems(Arrays.asList(itemStackMock , itemStackMock2));
challenge.setRequirements(req);
challenge.setRequirements(req);
ItemStack[] newContents = {itemStackMock3};
when(inv.getContents()).thenReturn(newContents);
@ -459,7 +459,7 @@ public class TryToCompleteTest {
// Not enough books
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)}.
*/
@ -469,7 +469,7 @@ public class TryToCompleteTest {
assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
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)}.
*/
@ -478,15 +478,15 @@ public class TryToCompleteTest {
challenge.setChallengeType(ChallengeType.ISLAND);
IslandRequirements req = new IslandRequirements();
req.setSearchRadius(1);
challenge.setRequirements(req);
challenge.setRequirements(req);
// Trigger big bounding box error
when(bb.getWidthX()).thenReturn(50000D);
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(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)}.
*/
@ -495,12 +495,12 @@ public class TryToCompleteTest {
challenge.setChallengeType(ChallengeType.ISLAND);
IslandRequirements req = new IslandRequirements();
req.setSearchRadius(1);
challenge.setRequirements(req);
challenge.setRequirements(req);
assertTrue(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
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)}.
*/
@ -511,12 +511,12 @@ public class TryToCompleteTest {
Map<EntityType, Integer> requiredEntities = Collections.singletonMap(EntityType.GHAST, 3);
req.setRequiredEntities(requiredEntities);
req.setSearchRadius(1);
challenge.setRequirements(req);
challenge.setRequirements(req);
assertFalse(TryToComplete.complete(addon, user, challenge, world, topLabel, permissionPrefix));
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)}.
*/
@ -530,14 +530,14 @@ public class TryToCompleteTest {
requiredEntities.put(EntityType.PUFFERFISH, 1);
req.setRequiredEntities(requiredEntities);
req.setSearchRadius(1);
challenge.setRequirements(req);
challenge.setRequirements(req);
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]", "1", "[item]", "Pufferfish");
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)}.
*/
@ -551,7 +551,7 @@ public class TryToCompleteTest {
requiredEntities.put(EntityType.PUFFERFISH, 1);
req.setRequiredEntities(requiredEntities);
req.setSearchRadius(1);
challenge.setRequirements(req);
challenge.setRequirements(req);
Entity ent = mock(Entity.class);
when(ent.getType()).thenReturn(EntityType.PUFFERFISH);
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, never()).sendMessage("challenges.errors.you-still-need", "[amount]", "1", "[item]", "Pufferfish");
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)}.
*/
@ -576,7 +576,7 @@ public class TryToCompleteTest {
requiredEntities.put(EntityType.PUFFERFISH, 1);
req.setRequiredEntities(requiredEntities);
req.setSearchRadius(1);
challenge.setRequirements(req);
challenge.setRequirements(req);
Entity ent = mock(Entity.class);
when(ent.getType()).thenReturn(EntityType.PUFFERFISH);
Location loc = mock(Location.class);
@ -604,15 +604,17 @@ public class TryToCompleteTest {
public void testBuild() {
this.testTryToCompleteChallengesAddonUserChallengeWorldStringString();
ChallengeResult result = this.ttc.build(10);
assertTrue(result.isMeetsRequirements());
}
/**
* Test method for {@link world.bentobox.challenges.tasks.TryToComplete#removeItems(java.util.List, int)}.
*/
@Test
public void testRemoveItems() {
public void testRemoveItemsNothing() {
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})
public class TryToCompleteTestOld {
private User user;
ItemStack[] stacks = { new ItemStack(Material.PAPER, 32),
new ItemStack(Material.ACACIA_BOAT),
null,
null,
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, 5),
new ItemStack(Material.GOLD_BLOCK, 32)
};
List<ItemStack> required;
private ChallengesAddon addon;
private PlayerInventory inv;
private User user;
ItemStack[] stacks = { new ItemStack(Material.PAPER, 32),
new ItemStack(Material.ACACIA_BOAT),
null,
null,
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, 5),
new ItemStack(Material.GOLD_BLOCK, 32)
};
List<ItemStack> required;
private ChallengesAddon addon;
private PlayerInventory inv;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
Server server = mock(Server.class);
PowerMockito.mockStatic(Bukkit.class);
when(Bukkit.getServer()).thenReturn(server);
when(Bukkit.getBukkitVersion()).thenReturn("1.13.2");
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
Server server = mock(Server.class);
PowerMockito.mockStatic(Bukkit.class);
when(Bukkit.getServer()).thenReturn(server);
when(Bukkit.getBukkitVersion()).thenReturn("1.13.2");
user = mock(User.class);
inv = mock(PlayerInventory.class);
when(inv.getContents()).thenReturn(stacks);
when(user.getInventory()).thenReturn(inv);
addon = mock(ChallengesAddon.class);
required = new ArrayList<>();
user = mock(User.class);
inv = mock(PlayerInventory.class);
when(inv.getContents()).thenReturn(stacks);
when(user.getInventory()).thenReturn(inv);
addon = mock(ChallengesAddon.class);
required = new ArrayList<>();
ItemFactory itemFactory = mock(ItemFactory.class);
when(server.getItemFactory()).thenReturn(itemFactory);
ItemFactory itemFactory = mock(ItemFactory.class);
when(server.getItemFactory()).thenReturn(itemFactory);
// Test will not work with items that has meta data.
when(itemFactory.getItemMeta(any())).thenReturn(null);
when(itemFactory.equals(null, null)).thenReturn(true);
// Test will not work with items that has meta data.
when(itemFactory.getItemMeta(any())).thenReturn(null);
when(itemFactory.equals(null, null)).thenReturn(true);
when(Bukkit.getItemFactory()).thenReturn(itemFactory);
when(Bukkit.getLogger()).thenReturn(Logger.getAnonymousLogger());
}
when(Bukkit.getItemFactory()).thenReturn(itemFactory);
when(Bukkit.getLogger()).thenReturn(Logger.getAnonymousLogger());
}
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@Test
public void testRemoveItemsSuccess() {
Material requiredMaterial = Material.PAPER;
int requiredQuantity = 21;
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@SuppressWarnings("deprecation")
@Test
public void testRemoveItemsSuccess() {
Material requiredMaterial = Material.PAPER;
int requiredQuantity = 21;
this.required.add(new ItemStack(requiredMaterial, requiredQuantity));
TryToComplete x = new TryToComplete(this.addon);
x.user(this.user);
Map<ItemStack, Integer> removed = x.removeItems(this.required, 1);
this.required.add(new ItemStack(requiredMaterial, requiredQuantity));
TryToComplete x = new TryToComplete(this.addon);
x.user(this.user);
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
public void testRemoveItemsMax() {
Material requiredMaterial = Material.PAPER;
int requiredQuantity = 50;
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@SuppressWarnings("deprecation")
@Test
public void testRemoveItemsMax() {
Material requiredMaterial = Material.PAPER;
int requiredQuantity = 50;
this.required.add(new ItemStack(requiredMaterial, requiredQuantity));
TryToComplete x = new TryToComplete(this.addon);
x.user(this.user);
Map<ItemStack, Integer> removed = x.removeItems(this.required, 1);
this.required.add(new ItemStack(requiredMaterial, requiredQuantity));
TryToComplete x = new TryToComplete(this.addon);
x.user(this.user);
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
public void testRemoveItemsZero() {
Material requiredMaterial = Material.PAPER;
int requiredQuantity = 0;
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@SuppressWarnings("deprecation")
@Test
public void testRemoveItemsZero() {
Material requiredMaterial = Material.PAPER;
int requiredQuantity = 0;
this.required.add(new ItemStack(requiredMaterial, requiredQuantity));
TryToComplete x = new TryToComplete(this.addon);
x.user(this.user);
Map<ItemStack, Integer> removed = x.removeItems(this.required, 1);
this.required.add(new ItemStack(requiredMaterial, requiredQuantity));
TryToComplete x = new TryToComplete(this.addon);
x.user(this.user);
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
public void testRemoveItemsSuccessMultiple() {
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);
x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 1);
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@SuppressWarnings("deprecation")
@Test
public void testRemoveItemsSuccessMultiple() {
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);
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
public void testRemoveItemsSuccessMultipleOther() {
required.add(new ItemStack(Material.CACTUS, 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));
TryToComplete x = new TryToComplete(addon);
x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 1);
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@SuppressWarnings("deprecation")
@Test
public void testRemoveItemsSuccessMultipleOther() {
required.add(new ItemStack(Material.CACTUS, 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));
TryToComplete x = new TryToComplete(addon);
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.CACTUS, 1), 0), 10);
}
assertEquals((int) removed.getOrDefault(new ItemStack(Material.PAPER, 1), 0), 21);
assertEquals((int) removed.getOrDefault(new ItemStack(Material.CACTUS, 1), 0), 10);
}
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@Test
public void testRemoveItemsMultipleOtherFail() {
required.add(new ItemStack(Material.ACACIA_FENCE, 5));
required.add(new ItemStack(Material.ARROW, 11));
required.add(new ItemStack(Material.STONE, 5));
required.add(new ItemStack(Material.BAKED_POTATO, 5));
required.add(new ItemStack(Material.GHAST_SPAWN_EGG, 5));
TryToComplete x = new TryToComplete(addon);
x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 1);
assertTrue(removed.isEmpty());
}
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@SuppressWarnings("deprecation")
@Test
public void testRemoveItemsMultipleOtherFail() {
required.add(new ItemStack(Material.ACACIA_FENCE, 5));
required.add(new ItemStack(Material.ARROW, 11));
required.add(new ItemStack(Material.STONE, 5));
required.add(new ItemStack(Material.BAKED_POTATO, 5));
required.add(new ItemStack(Material.GHAST_SPAWN_EGG, 5));
TryToComplete x = new TryToComplete(addon);
x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 1);
assertTrue(removed.isEmpty());
}
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@Test
public void testRemoveItemsFail() {
ItemStack input = new ItemStack(Material.GOLD_BLOCK, 55);
required.add(input);
TryToComplete x = new TryToComplete(addon);
x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 1);
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@SuppressWarnings("deprecation")
@Test
public void testRemoveItemsFail() {
ItemStack input = new ItemStack(Material.GOLD_BLOCK, 55);
required.add(input);
TryToComplete x = new TryToComplete(addon);
x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 1);
// It will remove 32, but not any more
assertEquals((int) removed.getOrDefault(new ItemStack(Material.GOLD_BLOCK, 1), 0), 32);
// It will remove 32, but not any more
assertEquals((int) removed.getOrDefault(new ItemStack(Material.GOLD_BLOCK, 1), 0), 32);
// An error will be thrown
Mockito.verify(addon, Mockito.times(1)).logError(Mockito.anyString());
}
// An error will be thrown
Mockito.verify(addon, Mockito.times(1)).logError(Mockito.anyString());
}
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@Test
public void testRequireTwoStacks() {
required.add(new ItemStack(Material.BRICK_STAIRS, 64));
required.add(new ItemStack(Material.BRICK_STAIRS, 64));
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@SuppressWarnings("deprecation")
@Test
public void testRequireTwoStacks() {
required.add(new ItemStack(Material.BRICK_STAIRS, 64));
required.add(new ItemStack(Material.BRICK_STAIRS, 64));
TryToComplete x = new TryToComplete(addon);
x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 1);
TryToComplete x = new TryToComplete(addon);
x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 1);
// It should remove both stacks
assertEquals((int) removed.getOrDefault(new ItemStack(Material.BRICK_STAIRS, 1), 0), 128);
}
// It should remove both stacks
assertEquals((int) removed.getOrDefault(new ItemStack(Material.BRICK_STAIRS, 1), 0), 128);
}
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@Test
public void testFactorStacks() {
required.add(new ItemStack(Material.BRICK_STAIRS, 32));
/**
* Test method for {@link TryToComplete#removeItems(java.util.List, int)}.
*/
@SuppressWarnings("deprecation")
@Test
public void testFactorStacks() {
required.add(new ItemStack(Material.BRICK_STAIRS, 32));
TryToComplete x = new TryToComplete(addon);
x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 4);
TryToComplete x = new TryToComplete(addon);
x.user(user);
Map<ItemStack, Integer> removed = x.removeItems(required, 4);
// It should remove both stacks
assertEquals((int) removed.getOrDefault(new ItemStack(Material.BRICK_STAIRS, 1), 0), 128);
}
// It should remove both stacks
assertEquals((int) removed.getOrDefault(new ItemStack(Material.BRICK_STAIRS, 1), 0), 128);
}
}