Test framework: added commands for real time checks/assertions:

* new checks: color, subtype, ability, PT, permanent and hand count;
 * more info in #4936;
This commit is contained in:
Oleg Agafonov 2018-05-14 02:31:19 +04:00
parent f30c0a7054
commit 4851ba9e84
5 changed files with 344 additions and 106 deletions

View file

@ -1,46 +1,47 @@
/* /*
* Copyright 2012 BetaSteward_at_googlemail.com. All rights reserved. * Copyright 2012 BetaSteward_at_googlemail.com. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without modification, are * Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met: * permitted provided that the following conditions are met:
* *
* 1. Redistributions of source code must retain the above copyright notice, this list of * 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer. * conditions and the following disclaimer.
* *
* 2. Redistributions in binary form must reproduce the above copyright notice, this list * 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials * of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution. * provided with the distribution.
* *
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
* The views and conclusions contained in the software and documentation are those of the * The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed * authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com. * or implied, of BetaSteward_at_googlemail.com.
*/ */
package org.mage.test.player; package org.mage.test.player;
import mage.constants.PhaseStep; import mage.constants.PhaseStep;
/** /**
*
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
public class PlayerAction { public class PlayerAction {
private final String actionName;
private final int turnNum; private final int turnNum;
private final PhaseStep step; private final PhaseStep step;
private final String action; private final String action;
public PlayerAction(int turnNum, PhaseStep step, String action) { public PlayerAction(String actionName, int turnNum, PhaseStep step, String action) {
this.actionName = actionName;
this.turnNum = turnNum; this.turnNum = turnNum;
this.step = step; this.step = step;
this.action = action; this.action = action;
@ -58,4 +59,7 @@ public class PlayerAction {
return action; return action;
} }
public String getActionName() {
return this.actionName;
}
} }

View file

@ -31,8 +31,11 @@ import java.io.Serializable;
import java.util.*; import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import com.sun.org.apache.xpath.internal.operations.Bool;
import mage.MageObject; import mage.MageObject;
import mage.MageObjectReference; import mage.MageObjectReference;
import mage.ObjectColor;
import mage.abilities.*; import mage.abilities.*;
import mage.abilities.costs.AlternativeSourceCosts; import mage.abilities.costs.AlternativeSourceCosts;
import mage.abilities.costs.Cost; import mage.abilities.costs.Cost;
@ -76,11 +79,15 @@ import mage.players.Player;
import mage.players.net.UserData; import mage.players.net.UserData;
import mage.target.*; import mage.target.*;
import mage.target.common.*; import mage.target.common.*;
import org.junit.Assert;
import org.junit.Ignore; import org.junit.Ignore;
import static org.mage.test.serverside.base.impl.CardTestPlayerAPIImpl.*;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
* @author Simown * @author Simown
* @author JayDi85
*/ */
@Ignore @Ignore
public class TestPlayer implements Player { public class TestPlayer implements Player {
@ -136,7 +143,11 @@ public class TestPlayer implements Player {
} }
public void addAction(int turnNum, PhaseStep step, String action) { public void addAction(int turnNum, PhaseStep step, String action) {
actions.add(new PlayerAction(turnNum, step, action)); actions.add(new PlayerAction("", turnNum, step, action));
}
public void addAction(String actionName, int turnNum, PhaseStep step, String action) {
actions.add(new PlayerAction(actionName, turnNum, step, action));
} }
public List<PlayerAction> getActions() { public List<PlayerAction> getActions() {
@ -145,7 +156,7 @@ public class TestPlayer implements Player {
/** /**
* @param maxCallsWithoutAction max number of priority passes a player may * @param maxCallsWithoutAction max number of priority passes a player may
* have for this test (default = 100) * have for this test (default = 100)
*/ */
public void setMaxCallsWithoutAction(int maxCallsWithoutAction) { public void setMaxCallsWithoutAction(int maxCallsWithoutAction) {
this.maxCallsWithoutAction = maxCallsWithoutAction; this.maxCallsWithoutAction = maxCallsWithoutAction;
@ -162,27 +173,27 @@ public class TestPlayer implements Player {
/** /**
* Finds a permanent based on a general filter an their name and possible * Finds a permanent based on a general filter an their name and possible
* index. * index.
* * <p>
* An index is permitted after the permanent's name to denote their index on * An index is permitted after the permanent's name to denote their index on
* the battlefield Either use name="<permanent>" which will get the first * the battlefield Either use name="<permanent>" which will get the first
* permanent with that name on the battlefield that meets the filter * permanent with that name on the battlefield that meets the filter
* criteria or name="<permanent>:<index>" to get the named permanent with * criteria or name="<permanent>:<index>" to get the named permanent with
* that index on the battlefield. * that index on the battlefield.
* * <p>
* Permanents are zero indexed in the order they entered the battlefield for * Permanents are zero indexed in the order they entered the battlefield for
* each controller: * each controller:
* * <p>
* findPermanent(new AttackingCreatureFilter(), "Human", <controllerID>, * findPermanent(new AttackingCreatureFilter(), "Human", <controllerID>,
* <game>) Will find the first "Human" creature that entered the battlefield * <game>) Will find the first "Human" creature that entered the battlefield
* under this controller and is attacking. * under this controller and is attacking.
* * <p>
* findPermanent(new FilterControllerPermanent(), "Fabled Hero:3", * findPermanent(new FilterControllerPermanent(), "Fabled Hero:3",
* <controllerID>, <game>) Will find the 4th permanent named "Fabled Hero" * <controllerID>, <game>) Will find the 4th permanent named "Fabled Hero"
* that entered the battlefield under this controller * that entered the battlefield under this controller
* * <p>
* An exception will be thrown if no permanents match the criteria or the * An exception will be thrown if no permanents match the criteria or the
* index is larger than the number of permanents found with that name. * index is larger than the number of permanents found with that name.
* * <p>
* failOnNotFound boolean controls if this function returns null for a * failOnNotFound boolean controls if this function returns null for a
* permanent not found on the battlefield. Currently used only as a * permanent not found on the battlefield. Currently used only as a
* workaround for attackers in selectAttackers() being able to attack * workaround for attackers in selectAttackers() being able to attack
@ -431,7 +442,7 @@ public class TestPlayer implements Player {
if (groups.length > 2 && !checkExecuteCondition(groups, game)) { if (groups.length > 2 && !checkExecuteCondition(groups, game)) {
break; break;
} }
for (Ability ability : computerPlayer.getPlayable(game, true)) { for (Ability ability : computerPlayer.getPlayable(game, true)) { // add wrong action log?
if (ability.toString().startsWith(groups[0])) { if (ability.toString().startsWith(groups[0])) {
int bookmark = game.bookmarkState(); int bookmark = game.bookmarkState();
Ability newAbility = ability.copy(); Ability newAbility = ability.copy();
@ -526,6 +537,60 @@ public class TestPlayer implements Player {
actions.remove(action); actions.remove(action);
} }
} }
} else if (action.getAction().startsWith("check:")) {
String command = action.getAction();
command = command.substring(command.indexOf("check:") + 6);
String[] params = command.split("@");
boolean checkProccessed = false;
if (params.length > 0) {
// check PT: card name, P, T
if (params[0].equals(CHECK_COMMAND_PT) && params.length == 4) {
assertPT(action, game, computerPlayer, params[1], Integer.parseInt(params[2]), Integer.parseInt(params[3]));
actions.remove(action);
checkProccessed = true;
}
// check ability: card name, ability class, must have
if (params[0].equals(CHECK_COMMAND_ABILITY) && params.length == 4) {
assertAbility(action, game, computerPlayer, params[1], params[2], Boolean.parseBoolean(params[3]));
actions.remove(action);
checkProccessed = true;
}
// check battlefield count: card name, count
if (params[0].equals(CHECK_COMMAND_PERMANENT_COUNT) && params.length == 3) {
assertPermanentCount(action, game, computerPlayer, params[1], Integer.parseInt(params[2]));
actions.remove(action);
checkProccessed = true;
}
// check hand count: count
if (params[0].equals(CHECK_COMMAND_HAND_COUNT) && params.length == 2) {
assertHandCount(action, game, computerPlayer, Integer.parseInt(params[1]));
actions.remove(action);
checkProccessed = true;
}
// check color: card name, colors, must have
if (params[0].equals(CHECK_COMMAND_COLOR) && params.length == 4) {
assertColor(action, game, computerPlayer, params[1], params[2], Boolean.parseBoolean(params[3]));
actions.remove(action);
checkProccessed = true;
}
// check subtype: card name, subtype, must have
if (params[0].equals(CHECK_COMMAND_SUBTYPE) && params.length == 4) {
assertSubType(action, game, computerPlayer, params[1], SubType.fromString(params[2]), Boolean.parseBoolean(params[3]));
actions.remove(action);
checkProccessed = true;
}
}
if (!checkProccessed) {
Assert.fail("Unknow check command or params: " + command);
}
} }
} }
} }
@ -546,8 +611,105 @@ public class TestPlayer implements Player {
return false; return false;
} }
private Permanent findPermanentWithAssert(PlayerAction action, Game game, Player player, String cardName) {
Permanent founded = null;
for (Permanent perm : game.getBattlefield().getAllPermanents()) {
if (perm.getName().equals(cardName) && perm.getControllerId().equals(player.getId())) {
return perm;
}
}
Assert.assertNotNull(action.getActionName() + " - can''t find permanent to check PT: " + cardName, founded);
return null;
}
private void assertPT(PlayerAction action, Game game, Player player, String permanentName, int Power, int Toughness) {
Permanent perm = findPermanentWithAssert(action, game, player, permanentName);
Assert.assertEquals(action.getActionName() + " - permanent " + permanentName + " have wrong power: " + perm.getPower().getValue() + " <> " + Power,
Power, perm.getPower().getValue());
Assert.assertEquals(action.getActionName() + " - permanent " + permanentName + " have wrong toughness: " + perm.getToughness().getValue() + " <> " + Toughness,
Toughness, perm.getToughness().getValue());
}
private void assertAbility(PlayerAction action, Game game, Player player, String permanentName, String abilityClass, boolean mustHave) {
Permanent perm = findPermanentWithAssert(action, game, player, permanentName);
boolean founded = false;
for (Ability ability : perm.getAbilities(game)) {
if (ability.getClass().getName().equals(abilityClass)) {
founded = true;
break;
}
}
if (mustHave) {
Assert.assertEquals(action.getActionName() + " - permanent " + permanentName + " must have ability " + abilityClass, true, founded);
} else {
Assert.assertEquals(action.getActionName() + " - permanent " + permanentName + " must have not ability " + abilityClass, false, founded);
}
}
private void assertPermanentCount(PlayerAction action, Game game, Player player, String permanentName, int count) {
int foundedCount = 0;
for (Permanent perm : game.getBattlefield().getAllPermanents()) {
if (perm.getName().equals(permanentName) && perm.getControllerId().equals(player.getId())) {
foundedCount++;
}
}
Assert.assertEquals(action.getActionName() + " - permanent " + permanentName + " must exists in " + count + " instances", count, foundedCount);
}
private void assertHandCount(PlayerAction action, Game game, Player player, int count) {
Assert.assertEquals(action.getActionName() + " - hand must contain " + count, count, player.getHand().size());
}
private void assertColor(PlayerAction action, Game game, Player player, String permanentName, String colors, boolean mustHave) {
Assert.assertNotEquals(action.getActionName() + " - must setup colors", "", colors);
Permanent card = findPermanentWithAssert(action, game, player, permanentName);
ObjectColor cardColor = card.getColor(game);
ObjectColor searchColors = new ObjectColor(colors);
List<ObjectColor> colorsHave = new ArrayList<>();
List<ObjectColor> colorsDontHave = new ArrayList<>();
for (ObjectColor searchColor : searchColors.getColors()) {
if (cardColor.shares(searchColor)) {
colorsHave.add(searchColor);
} else {
colorsDontHave.add(searchColor);
}
}
if (mustHave) {
Assert.assertEquals(action.getActionName() + " - must contain colors [" + searchColors.toString() + "] but found only [" + cardColor.toString() + "]", 0, colorsDontHave.size());
} else {
Assert.assertEquals(action.getActionName() + " - must not contain colors [" + searchColors.toString() + "] but found [" + cardColor.toString() + "]", 0, colorsHave.size());
}
}
private void assertSubType(PlayerAction action, Game game, Player player, String permanentName, SubType subType, boolean mustHave) {
Permanent perm = findPermanentWithAssert(action, game, player, permanentName);
boolean founded = false;
for (SubType st : perm.getSubtype(game)) {
if (st.equals(subType)) {
founded = true;
break;
}
}
if (mustHave) {
Assert.assertEquals(action.getActionName() + " - permanent " + permanentName + " must have subtype " + subType, true, founded);
} else {
Assert.assertEquals(action.getActionName() + " - permanent " + permanentName + " must have not subtype " + subType, false, founded);
}
}
/* /*
* Iterates through each player on the current turn and asserts if they can attack or block legally this turn * Iterates through each player on the current turn and asserts if they can attack or block legally this turn
*/ */
private void checkLegalMovesThisTurn(Game game) { private void checkLegalMovesThisTurn(Game game) {
// Each player is given priority before actual turns start for e.g. leylines and pre-game initialisation // Each player is given priority before actual turns start for e.g. leylines and pre-game initialisation
@ -589,7 +751,7 @@ public class TestPlayer implements Player {
// Loop through players and validate can attack/block this turn // Loop through players and validate can attack/block this turn
UUID defenderId = null; UUID defenderId = null;
//List<PlayerAction> //List<PlayerAction>
for (Iterator<org.mage.test.player.PlayerAction> it = actions.iterator(); it.hasNext();) { for (Iterator<org.mage.test.player.PlayerAction> it = actions.iterator(); it.hasNext(); ) {
PlayerAction action = it.next(); PlayerAction action = it.next();
if (action.getTurnNum() == game.getTurnNum() && action.getAction().startsWith("attack:")) { if (action.getTurnNum() == game.getTurnNum() && action.getAction().startsWith("attack:")) {
String command = action.getAction(); String command = action.getAction();
@ -2242,7 +2404,7 @@ public class TestPlayer implements Player {
@Override @Override
public boolean choose(Outcome outcome, Target target, public boolean choose(Outcome outcome, Target target,
UUID sourceId, Game game UUID sourceId, Game game
) { ) {
// needed to call here the TestPlayer because it's overwitten // needed to call here the TestPlayer because it's overwitten
return choose(outcome, target, sourceId, game, null); return choose(outcome, target, sourceId, game, null);
@ -2250,7 +2412,7 @@ public class TestPlayer implements Player {
@Override @Override
public boolean choose(Outcome outcome, Cards cards, public boolean choose(Outcome outcome, Cards cards,
TargetCard target, Game game TargetCard target, Game game
) { ) {
if (!choices.isEmpty()) { if (!choices.isEmpty()) {
for (String choose2 : choices) { for (String choose2 : choices) {
@ -2282,7 +2444,7 @@ public class TestPlayer implements Player {
@Override @Override
public boolean chooseTargetAmount(Outcome outcome, TargetAmount target, public boolean chooseTargetAmount(Outcome outcome, TargetAmount target,
Ability source, Game game Ability source, Game game
) { ) {
return computerPlayer.chooseTargetAmount(outcome, target, source, game); return computerPlayer.chooseTargetAmount(outcome, target, source, game);
} }
@ -2295,15 +2457,15 @@ public class TestPlayer implements Player {
@Override @Override
public boolean choosePile(Outcome outcome, String message, public boolean choosePile(Outcome outcome, String message,
List<? extends Card> pile1, List<? extends Card> pile2, List<? extends Card> pile1, List<? extends Card> pile2,
Game game Game game
) { ) {
return computerPlayer.choosePile(outcome, message, pile1, pile2, game); return computerPlayer.choosePile(outcome, message, pile1, pile2, game);
} }
@Override @Override
public boolean playMana(Ability ability, ManaCost unpaid, public boolean playMana(Ability ability, ManaCost unpaid,
String promptText, Game game String promptText, Game game
) { ) {
groupsForTargetHandling = null; groupsForTargetHandling = null;
return computerPlayer.playMana(ability, unpaid, promptText, game); return computerPlayer.playMana(ability, unpaid, promptText, game);
@ -2317,15 +2479,15 @@ public class TestPlayer implements Player {
@Override @Override
public UUID chooseBlockerOrder(List<Permanent> blockers, CombatGroup combatGroup, public UUID chooseBlockerOrder(List<Permanent> blockers, CombatGroup combatGroup,
List<UUID> blockerOrder, Game game List<UUID> blockerOrder, Game game
) { ) {
return computerPlayer.chooseBlockerOrder(blockers, combatGroup, blockerOrder, game); return computerPlayer.chooseBlockerOrder(blockers, combatGroup, blockerOrder, game);
} }
@Override @Override
public void assignDamage(int damage, List<UUID> targets, public void assignDamage(int damage, List<UUID> targets,
String singleTargetName, UUID sourceId, String singleTargetName, UUID sourceId,
Game game Game game
) { ) {
computerPlayer.assignDamage(damage, targets, singleTargetName, sourceId, game); computerPlayer.assignDamage(damage, targets, singleTargetName, sourceId, game);
} }
@ -2344,14 +2506,14 @@ public class TestPlayer implements Player {
@Override @Override
public void pickCard(List<Card> cards, Deck deck, public void pickCard(List<Card> cards, Deck deck,
Draft draft Draft draft
) { ) {
computerPlayer.pickCard(cards, deck, draft); computerPlayer.pickCard(cards, deck, draft);
} }
@Override @Override
public boolean scry(int value, Ability source, public boolean scry(int value, Ability source,
Game game Game game
) { ) {
// Don't scry at the start of the game. // Don't scry at the start of the game.
if (game.getTurnNum() == 1 && game.getStep() == null) { if (game.getTurnNum() == 1 && game.getStep() == null) {
@ -2362,37 +2524,37 @@ public class TestPlayer implements Player {
@Override @Override
public boolean moveCards(Card card, Zone toZone, public boolean moveCards(Card card, Zone toZone,
Ability source, Game game Ability source, Game game
) { ) {
return computerPlayer.moveCards(card, toZone, source, game); return computerPlayer.moveCards(card, toZone, source, game);
} }
@Override @Override
public boolean moveCards(Card card, Zone toZone, public boolean moveCards(Card card, Zone toZone,
Ability source, Game game, Ability source, Game game,
boolean tapped, boolean faceDown, boolean byOwner, List<UUID> appliedEffects boolean tapped, boolean faceDown, boolean byOwner, List<UUID> appliedEffects
) { ) {
return computerPlayer.moveCards(card, toZone, source, game, tapped, faceDown, byOwner, appliedEffects); return computerPlayer.moveCards(card, toZone, source, game, tapped, faceDown, byOwner, appliedEffects);
} }
@Override @Override
public boolean moveCards(Cards cards, Zone toZone, public boolean moveCards(Cards cards, Zone toZone,
Ability source, Game game Ability source, Game game
) { ) {
return computerPlayer.moveCards(cards, toZone, source, game); return computerPlayer.moveCards(cards, toZone, source, game);
} }
@Override @Override
public boolean moveCards(Set<Card> cards, Zone toZone, public boolean moveCards(Set<Card> cards, Zone toZone,
Ability source, Game game Ability source, Game game
) { ) {
return computerPlayer.moveCards(cards, toZone, source, game); return computerPlayer.moveCards(cards, toZone, source, game);
} }
@Override @Override
public boolean moveCards(Set<Card> cards, Zone toZone, public boolean moveCards(Set<Card> cards, Zone toZone,
Ability source, Game game, Ability source, Game game,
boolean tapped, boolean faceDown, boolean byOwner, List<UUID> appliedEffects boolean tapped, boolean faceDown, boolean byOwner, List<UUID> appliedEffects
) { ) {
return computerPlayer.moveCards(cards, toZone, source, game, tapped, faceDown, byOwner, appliedEffects); return computerPlayer.moveCards(cards, toZone, source, game, tapped, faceDown, byOwner, appliedEffects);
} }

View file

@ -1,5 +1,6 @@
package org.mage.test.serverside.base.impl; package org.mage.test.serverside.base.impl;
import mage.MageInt;
import mage.Mana; import mage.Mana;
import mage.ObjectColor; import mage.ObjectColor;
import mage.abilities.Ability; import mage.abilities.Ability;
@ -47,6 +48,13 @@ public abstract class CardTestPlayerAPIImpl extends MageTestPlayerBase implement
// Defines the constant if for activate ability is not target but a ability on the stack to define // Defines the constant if for activate ability is not target but a ability on the stack to define
public static final String NO_TARGET = "NO_TARGET"; public static final String NO_TARGET = "NO_TARGET";
public static final String CHECK_COMMAND_PT = "PT";
public static final String CHECK_COMMAND_ABILITY = "ABILITY";
public static final String CHECK_COMMAND_PERMANENT_COUNT = "PERMANENT_COUNT";
public static final String CHECK_COMMAND_HAND_COUNT = "HAND_COUNT";
public static final String CHECK_COMMAND_COLOR = "COLOR";
public static final String CHECK_COMMAND_SUBTYPE = "SUBTYPE";
protected GameOptions gameOptions; protected GameOptions gameOptions;
protected String deckNameA; protected String deckNameA;
@ -64,7 +72,7 @@ public abstract class CardTestPlayerAPIImpl extends MageTestPlayerBase implement
UNKNOWN UNKNOWN
} }
public CardTestPlayerAPIImpl(){ public CardTestPlayerAPIImpl() {
// load all cards to db from class list // load all cards to db from class list
ArrayList<String> errorsList = new ArrayList<>(); ArrayList<String> errorsList = new ArrayList<>();
CardScanner.scan(errorsList); CardScanner.scan(errorsList);
@ -219,6 +227,38 @@ public abstract class CardTestPlayerAPIImpl extends MageTestPlayerBase implement
return player; return player;
} }
private void check(String checkName, int turnNum, PhaseStep step, TestPlayer player, String command, String... params) {
String res = "check:" + command;
for (String param : params) {
res += "@" + param;
}
player.addAction(checkName, turnNum, step, res);
}
public void checkPT(String checkName, int turnNum, PhaseStep step, TestPlayer player, String permanentName, Integer power, Integer toughness) {
check(checkName, turnNum, step, player, CHECK_COMMAND_PT, permanentName, power.toString(), toughness.toString());
}
public void checkAbility(String checkName, int turnNum, PhaseStep step, TestPlayer player, String permanentName, Class<?> abilityClass, Boolean mustHave) {
check(checkName, turnNum, step, player, CHECK_COMMAND_ABILITY, permanentName, abilityClass.getName(), mustHave.toString());
}
public void checkPermanentCount(String checkName, int turnNum, PhaseStep step, TestPlayer player, String permanentName, Integer count) {
check(checkName, turnNum, step, player, CHECK_COMMAND_PERMANENT_COUNT, permanentName, count.toString());
}
public void checkHandCount(String checkName, int turnNum, PhaseStep step, TestPlayer player, Integer count) {
check(checkName, turnNum, step, player, CHECK_COMMAND_HAND_COUNT, count.toString());
}
public void checkColor(String checkName, int turnNum, PhaseStep step, TestPlayer player, String permanentName, String colors, Boolean mustHave) {
check(checkName, turnNum, step, player, CHECK_COMMAND_COLOR, permanentName, colors, mustHave.toString());
}
public void checkSubType(String checkName, int turnNum, PhaseStep step, TestPlayer player, String permanentName, SubType subType, Boolean mustHave) {
check(checkName, turnNum, step, player, CHECK_COMMAND_SUBTYPE, permanentName, subType.toString(), mustHave.toString());
}
/** /**
* Removes all cards from player's library from the game. Usually this * Removes all cards from player's library from the game. Usually this
* should be used once before initialization to form the library in certain * should be used once before initialization to form the library in certain
@ -525,7 +565,7 @@ public abstract class CardTestPlayerAPIImpl extends MageTestPlayerBase implement
* @param player * @param player
* @param cardName * @param cardName
* @param ability * @param ability
* @param mustHave true if creature should contain ability, false if it should * @param mustHave true if creature should contain ability, false if it should
* NOT contain it instead * NOT contain it instead
* @param count number of permanents with that ability * @param count number of permanents with that ability
* @throws AssertionError * @throws AssertionError
@ -683,7 +723,7 @@ public abstract class CardTestPlayerAPIImpl extends MageTestPlayerBase implement
* *
* @param cardName Name of the permanent that should be checked. * @param cardName Name of the permanent that should be checked.
* @param type A type to test for * @param type A type to test for
* @param mustHave true if creature should have type, false if it should not * @param mustHave true if creature should have type, false if it should not
*/ */
public void assertType(String cardName, CardType type, boolean mustHave) throws AssertionError { public void assertType(String cardName, CardType type, boolean mustHave) throws AssertionError {
Permanent found = null; Permanent found = null;
@ -742,10 +782,10 @@ public abstract class CardTestPlayerAPIImpl extends MageTestPlayerBase implement
/** /**
* Assert permanent color * Assert permanent color
* *
* @param player player to check * @param player player to check
* @param cardName card name on battlefield from player * @param cardName card name on battlefield from player
* @param searchColors colors list with searchable values * @param searchColors colors list with searchable values
* @param mustHave must or not must have that colors * @param mustHave must or not must have that colors
*/ */
public void assertColor(Player player, String cardName, ObjectColor searchColors, boolean mustHave) { public void assertColor(Player player, String cardName, ObjectColor searchColors, boolean mustHave) {
Assert.assertNotEquals("must setup colors to search", 0, searchColors.getColorCount()); Assert.assertNotEquals("must setup colors to search", 0, searchColors.getColorCount());
@ -876,26 +916,26 @@ public abstract class CardTestPlayerAPIImpl extends MageTestPlayerBase implement
} }
public void assertManaPool(Player player, ManaType color, int amount){ public void assertManaPool(Player player, ManaType color, int amount) {
ManaPool manaPool = currentGame.getPlayer(player.getId()).getManaPool(); ManaPool manaPool = currentGame.getPlayer(player.getId()).getManaPool();
switch (color){ switch (color) {
case COLORLESS: case COLORLESS:
Assert.assertEquals(amount,manaPool.getColorless() + manaPool.getConditionalMana().stream().mapToInt(Mana::getColorless).sum()); Assert.assertEquals(amount, manaPool.getColorless() + manaPool.getConditionalMana().stream().mapToInt(Mana::getColorless).sum());
break; break;
case RED: case RED:
Assert.assertEquals(amount,manaPool.getRed() + manaPool.getConditionalMana().stream().mapToInt(Mana::getRed).sum()); Assert.assertEquals(amount, manaPool.getRed() + manaPool.getConditionalMana().stream().mapToInt(Mana::getRed).sum());
break; break;
case BLUE: case BLUE:
Assert.assertEquals(amount,manaPool.getBlue() + manaPool.getConditionalMana().stream().mapToInt(Mana::getBlue).sum()); Assert.assertEquals(amount, manaPool.getBlue() + manaPool.getConditionalMana().stream().mapToInt(Mana::getBlue).sum());
break; break;
case WHITE: case WHITE:
Assert.assertEquals(amount,manaPool.getWhite() + manaPool.getConditionalMana().stream().mapToInt(Mana::getWhite).sum()); Assert.assertEquals(amount, manaPool.getWhite() + manaPool.getConditionalMana().stream().mapToInt(Mana::getWhite).sum());
break; break;
case GREEN: case GREEN:
Assert.assertEquals(amount,manaPool.getGreen() + manaPool.getConditionalMana().stream().mapToInt(Mana::getGreen).sum()); Assert.assertEquals(amount, manaPool.getGreen() + manaPool.getConditionalMana().stream().mapToInt(Mana::getGreen).sum());
break; break;
case BLACK: case BLACK:
Assert.assertEquals(amount,manaPool.getBlack() + manaPool.getConditionalMana().stream().mapToInt(Mana::getBlack).sum()); Assert.assertEquals(amount, manaPool.getBlack() + manaPool.getConditionalMana().stream().mapToInt(Mana::getBlack).sum());
break; break;
} }
} }

View file

@ -30,7 +30,6 @@ import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
*
* @author JayDi85 * @author JayDi85
*/ */
public class VerifyCardDataTest { public class VerifyCardDataTest {
@ -39,9 +38,18 @@ public class VerifyCardDataTest {
private static final boolean CHECK_SOURCE_TOKENS = false; private static final boolean CHECK_SOURCE_TOKENS = false;
private static final HashMap<String, Set<String>> skipCheckLists = new HashMap<>(); private static final HashMap<String, Set<String>> skipCheckLists = new HashMap<>();
private static void skipListCreate(String listName){ skipCheckLists.put(listName, new LinkedHashSet<>()); }
private static void skipListAddName(String listName, String name){ skipCheckLists.get(listName).add(name); } private static void skipListCreate(String listName) {
private static boolean skipListHaveName(String listName, String name){ return skipCheckLists.get(listName).contains(name); } skipCheckLists.put(listName, new LinkedHashSet<>());
}
private static void skipListAddName(String listName, String name) {
skipCheckLists.get(listName).add(name);
}
private static boolean skipListHaveName(String listName, String name) {
return skipCheckLists.get(listName).contains(name);
}
static { static {
// skip lists for checks (example: unstable cards with same name may have different stats) // skip lists for checks (example: unstable cards with same name may have different stats)
@ -114,7 +122,7 @@ public class VerifyCardDataTest {
private void fail(Card card, String category, String message) { private void fail(Card card, String category, String message) {
failed++; failed++;
System.out.println("Error: (" + category + ") " + message + " for " + card.getName() + " (" + card.getExpansionSetCode() + ")"); System.out.println("Error: (" + category + ") " + message + " for " + card.getName() + " (" + card.getExpansionSetCode() + ")");
} }
private int failed = 0; private int failed = 0;
@ -136,31 +144,31 @@ public class VerifyCardDataTest {
} }
@Test @Test
public void checkDuplicateCardNumbersInDB(){ public void checkDuplicateCardNumbersInDB() {
Collection<String> doubleErrors = new ArrayList<>(); Collection<String> doubleErrors = new ArrayList<>();
Collection<ExpansionSet> sets = Sets.getInstance().values(); Collection<ExpansionSet> sets = Sets.getInstance().values();
for (ExpansionSet set : sets) { for (ExpansionSet set : sets) {
Map<String, ExpansionSet.SetCardInfo> cardsList = new HashMap<>(); Map<String, ExpansionSet.SetCardInfo> cardsList = new HashMap<>();
for (ExpansionSet.SetCardInfo checkCard: set.getSetCardInfo()) { for (ExpansionSet.SetCardInfo checkCard : set.getSetCardInfo()) {
String cardNumber = checkCard.getCardNumber(); String cardNumber = checkCard.getCardNumber();
// ignore double faced // ignore double faced
Card realCard = CardImpl.createCard(checkCard.getCardClass(), new CardSetInfo(checkCard.getName(), set.getCode(), Card realCard = CardImpl.createCard(checkCard.getCardClass(), new CardSetInfo(checkCard.getName(), set.getCode(),
checkCard.getCardNumber(), checkCard.getRarity(), checkCard.getGraphicInfo())); checkCard.getCardNumber(), checkCard.getRarity(), checkCard.getGraphicInfo()));
if (realCard.isNightCard()){ if (realCard.isNightCard()) {
continue; continue;
} }
if (cardsList.containsKey(cardNumber)){ if (cardsList.containsKey(cardNumber)) {
ExpansionSet.SetCardInfo prevCard = cardsList.get(cardNumber); ExpansionSet.SetCardInfo prevCard = cardsList.get(cardNumber);
String errorType; String errorType;
if (checkCard.getName().equals(prevCard.getName())){ if (checkCard.getName().equals(prevCard.getName())) {
errorType = " founded DUPLICATED cards" errorType = " founded DUPLICATED cards"
+ " set (" + set.getCode() + " - " + set.getName() + ")" + " set (" + set.getCode() + " - " + set.getName() + ")"
+ " (" + checkCard.getCardNumber() + " - " + checkCard.getName() + ")"; + " (" + checkCard.getCardNumber() + " - " + checkCard.getName() + ")";
}else{ } else {
errorType = " founded TYPOS in card numbers" errorType = " founded TYPOS in card numbers"
+ " set (" + set.getCode() + " - " + set.getName() + ")" + " set (" + set.getCode() + " - " + set.getName() + ")"
+ " (" + prevCard.getCardNumber() + " - " + prevCard.getName() + ")" + " (" + prevCard.getCardNumber() + " - " + prevCard.getName() + ")"
@ -171,23 +179,23 @@ public class VerifyCardDataTest {
String error = "Error: " + errorType; String error = "Error: " + errorType;
doubleErrors.add(error); doubleErrors.add(error);
}else{ } else {
cardsList.put(cardNumber, checkCard); cardsList.put(cardNumber, checkCard);
} }
} }
} }
for (String error: doubleErrors) { for (String error : doubleErrors) {
System.out.println(error); System.out.println(error);
} }
if (doubleErrors.size() > 0){ if (doubleErrors.size() > 0) {
Assert.fail("DB have duplicated card numbers, founded errors: " + doubleErrors.size()); Assert.fail("DB have duplicated card numbers, founded errors: " + doubleErrors.size());
} }
} }
@Test @Test
public void checkWrongCardClasses(){ public void checkWrongCardClasses() {
Collection<String> errorsList = new ArrayList<>(); Collection<String> errorsList = new ArrayList<>();
Map<String, String> classesIndex = new HashMap<>(); Map<String, String> classesIndex = new HashMap<>();
int totalCards = 0; int totalCards = 0;
@ -202,7 +210,7 @@ public class VerifyCardDataTest {
String needClass = classesIndex.get(checkCard.getName()); String needClass = classesIndex.get(checkCard.getName());
if (!needClass.equals(currentClass)) { if (!needClass.equals(currentClass)) {
// workaround to star wars set with same card names // workaround to star wars set with same card names
if(!checkCard.getName().equals("Syndicate Enforcer")) { if (!checkCard.getName().equals("Syndicate Enforcer")) {
errorsList.add("Error: founded wrong class in set " + set.getCode() + " - " + checkCard.getName() + " (" + currentClass + " <> " + needClass + ")"); errorsList.add("Error: founded wrong class in set " + set.getCode() + " - " + checkCard.getName() + " (" + currentClass + " <> " + needClass + ")");
} }
} }
@ -212,45 +220,45 @@ public class VerifyCardDataTest {
} }
} }
for (String error: errorsList) { for (String error : errorsList) {
System.out.println(error); System.out.println(error);
} }
// unique cards stats // unique cards stats
System.out.println("Total unique cards: " + classesIndex.size() + ", total non unique cards (reprints): " + totalCards); System.out.println("Total unique cards: " + classesIndex.size() + ", total non unique cards (reprints): " + totalCards);
if (errorsList.size() > 0){ if (errorsList.size() > 0) {
Assert.fail("DB have wrong card classes, founded errors: " + errorsList.size()); Assert.fail("DB have wrong card classes, founded errors: " + errorsList.size());
} }
} }
@Test @Test
public void checkMissingSets(){ public void checkMissingSets() {
Collection<String> errorsList = new ArrayList<>(); Collection<String> errorsList = new ArrayList<>();
int totalMissingSets = 0; int totalMissingSets = 0;
int totalMissingCards = 0; int totalMissingCards = 0;
Collection<ExpansionSet> sets = Sets.getInstance().values(); Collection<ExpansionSet> sets = Sets.getInstance().values();
for(Map.Entry<String, JsonSet> refEntry: MtgJson.sets().entrySet()){ for (Map.Entry<String, JsonSet> refEntry : MtgJson.sets().entrySet()) {
JsonSet refSet = refEntry.getValue(); JsonSet refSet = refEntry.getValue();
// replace codes for aliases // replace codes for aliases
String searchSet = MtgJson.mtgJsonToXMageCodes.getOrDefault(refSet.code, refSet.code); String searchSet = MtgJson.mtgJsonToXMageCodes.getOrDefault(refSet.code, refSet.code);
ExpansionSet mageSet = Sets.findSet(searchSet); ExpansionSet mageSet = Sets.findSet(searchSet);
if(mageSet == null){ if (mageSet == null) {
totalMissingSets = totalMissingSets + 1; totalMissingSets = totalMissingSets + 1;
totalMissingCards = totalMissingCards + refSet.cards.size(); totalMissingCards = totalMissingCards + refSet.cards.size();
errorsList.add("Warning: missing set " + refSet.code + " - " + refSet.name + " (cards: " + refSet.cards.size() + ")"); errorsList.add("Warning: missing set " + refSet.code + " - " + refSet.name + " (cards: " + refSet.cards.size() + ")");
} }
} }
if(errorsList.size() > 0){ if (errorsList.size() > 0) {
errorsList.add("Warning: total missing sets: " + totalMissingSets + ", with missing cards: " + totalMissingCards); errorsList.add("Warning: total missing sets: " + totalMissingSets + ", with missing cards: " + totalMissingCards);
} }
// only warnings // only warnings
for (String error: errorsList) { for (String error : errorsList) {
System.out.println(error); System.out.println(error);
} }
} }
@ -383,7 +391,7 @@ public class VerifyCardDataTest {
printMessages(warningsList); printMessages(warningsList);
printMessages(errorsList); printMessages(errorsList);
if(errorsList.size() > 0){ if (errorsList.size() > 0) {
Assert.fail("Founded token errors: " + errorsList.size()); Assert.fail("Founded token errors: " + errorsList.size());
} }
} }
@ -455,7 +463,9 @@ public class VerifyCardDataTest {
} }
private void checkColors(Card card, JsonCard ref) { private void checkColors(Card card, JsonCard ref) {
if (skipListHaveName("COLOR", card.getName())){ return; } if (skipListHaveName("COLOR", card.getName())) {
return;
}
Collection<String> expected = ref.colors; Collection<String> expected = ref.colors;
ObjectColor color = card.getColor(null); ObjectColor color = card.getColor(null);
@ -473,14 +483,16 @@ public class VerifyCardDataTest {
} }
private void checkSubtypes(Card card, JsonCard ref) { private void checkSubtypes(Card card, JsonCard ref) {
if (skipListHaveName("SUBTYPE", card.getName())){ return; } if (skipListHaveName("SUBTYPE", card.getName())) {
return;
}
Collection<String> expected = ref.subtypes; Collection<String> expected = ref.subtypes;
// fix names (e.g. Urzas to Urza's) // fix names (e.g. Urzas to Urza's)
if (expected != null && expected.contains("Urzas")) { if (expected != null && expected.contains("Urzas")) {
expected = new ArrayList<>(expected); expected = new ArrayList<>(expected);
for (ListIterator<String> it = ((List<String>) expected).listIterator(); it.hasNext();) { for (ListIterator<String> it = ((List<String>) expected).listIterator(); it.hasNext(); ) {
if (it.next().equals("Urzas")) { if (it.next().equals("Urzas")) {
it.set("Urza's"); it.set("Urza's");
} }
@ -493,7 +505,9 @@ public class VerifyCardDataTest {
} }
private void checkSupertypes(Card card, JsonCard ref) { private void checkSupertypes(Card card, JsonCard ref) {
if (skipListHaveName("SUPERTYPE", card.getName())){ return; } if (skipListHaveName("SUPERTYPE", card.getName())) {
return;
}
Collection<String> expected = ref.supertypes; Collection<String> expected = ref.supertypes;
if (!eqSet(card.getSuperType().stream().map(s -> s.toString()).collect(Collectors.toList()), expected)) { if (!eqSet(card.getSuperType().stream().map(s -> s.toString()).collect(Collectors.toList()), expected)) {
@ -502,7 +516,9 @@ public class VerifyCardDataTest {
} }
private void checkTypes(Card card, JsonCard ref) { private void checkTypes(Card card, JsonCard ref) {
if (skipListHaveName("TYPE", card.getName())){ return; } if (skipListHaveName("TYPE", card.getName())) {
return;
}
Collection<String> expected = ref.types; Collection<String> expected = ref.types;
List<String> type = new ArrayList<>(); List<String> type = new ArrayList<>();
@ -522,7 +538,9 @@ public class VerifyCardDataTest {
} }
private void checkPT(Card card, JsonCard ref) { private void checkPT(Card card, JsonCard ref) {
if (skipListHaveName("PT", card.getName())){ return; } if (skipListHaveName("PT", card.getName())) {
return;
}
if (!eqPT(card.getPower().toString(), ref.power) || !eqPT(card.getToughness().toString(), ref.toughness)) { if (!eqPT(card.getPower().toString(), ref.power) || !eqPT(card.getToughness().toString(), ref.toughness)) {
String pt = card.getPower() + "/" + card.getToughness(); String pt = card.getPower() + "/" + card.getToughness();
@ -540,7 +558,9 @@ public class VerifyCardDataTest {
} }
private void checkCost(Card card, JsonCard ref) { private void checkCost(Card card, JsonCard ref) {
if (skipListHaveName("COST", card.getName())){ return; } if (skipListHaveName("COST", card.getName())) {
return;
}
String expected = ref.manaCost; String expected = ref.manaCost;
String cost = join(card.getManaCost().getSymbols()); String cost = join(card.getManaCost().getSymbols());
@ -556,7 +576,9 @@ public class VerifyCardDataTest {
} }
private void checkNumbers(Card card, JsonCard ref) { private void checkNumbers(Card card, JsonCard ref) {
if (skipListHaveName("NUMBER", card.getName())){ return; } if (skipListHaveName("NUMBER", card.getName())) {
return;
}
String expected = ref.number; String expected = ref.number;
String current = card.getCardNumber(); String current = card.getCardNumber();

View file

@ -4,6 +4,7 @@ import java.util.Arrays;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import mage.util.SubTypeList; import mage.util.SubTypeList;
public enum SubType { public enum SubType {
@ -328,17 +329,16 @@ public enum SubType {
TROOPER("Trooper", SubTypeSet.CreatureType, true), // Star Wars TROOPER("Trooper", SubTypeSet.CreatureType, true), // Star Wars
TRILOBITE("Trilobite", SubTypeSet.CreatureType), TRILOBITE("Trilobite", SubTypeSet.CreatureType),
TWILEK("Twi'lek", SubTypeSet.CreatureType, true), // Star Wars TWILEK("Twi'lek", SubTypeSet.CreatureType, true), // Star Wars
// U // U
UGNAUGHT("Ugnaught", SubTypeSet.CreatureType, true), UGNAUGHT("Ugnaught", SubTypeSet.CreatureType, true),
UNICORN("Unicorn", SubTypeSet.CreatureType), UNICORN("Unicorn", SubTypeSet.CreatureType),
//V // V
VAMPIRE("Vampire", SubTypeSet.CreatureType), VAMPIRE("Vampire", SubTypeSet.CreatureType),
VEDALKEN("Vedalken", SubTypeSet.CreatureType), VEDALKEN("Vedalken", SubTypeSet.CreatureType),
VIASHINO("Viashino", SubTypeSet.CreatureType), VIASHINO("Viashino", SubTypeSet.CreatureType),
VILLAIN("Villain", SubTypeSet.CreatureType, true), // Unstable VILLAIN("Villain", SubTypeSet.CreatureType, true), // Unstable
VOLVER("Volver", SubTypeSet.CreatureType), VOLVER("Volver", SubTypeSet.CreatureType),
//W // W
WALL("Wall", SubTypeSet.CreatureType), WALL("Wall", SubTypeSet.CreatureType),
WARRIOR("Warrior", SubTypeSet.CreatureType), WARRIOR("Warrior", SubTypeSet.CreatureType),
WEEQUAY("Weequay", SubTypeSet.CreatureType, true), WEEQUAY("Weequay", SubTypeSet.CreatureType, true),
@ -429,6 +429,16 @@ public enum SubType {
return description; return description;
} }
public static SubType fromString(String value) {
for (SubType st : SubType.values()) {
if (st.toString().equals(value)) {
return st;
}
}
throw new IllegalArgumentException("Can''t find subtype enum value: " + value);
}
public static SubType byDescription(String subType) { public static SubType byDescription(String subType) {
for (SubType s : values()) { for (SubType s : values()) {
if (s.getDescription().equals(subType)) { if (s.getDescription().equals(subType)) {