Merge pull request #118 from allentiak/reorganize-tests

forge-gui-desktop: Reorganize tests (forge.card)
This commit is contained in:
Agetian
2022-04-24 07:47:02 +03:00
committed by GitHub
10 changed files with 1125 additions and 893 deletions

View File

@@ -1,21 +1,24 @@
package forge.card;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import org.powermock.api.mockito.PowerMockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import forge.StaticData;
import forge.gamesimulationtests.util.CardDatabaseHelper;
import forge.item.PaperCard;
import forge.model.FModel;
import org.powermock.api.mockito.PowerMockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class CardDbTestLazyCardLoading extends ForgeCardMockTestCase {
public class CardDbLazyCardLoadingCardMockTestCase extends CardMockTestCase {
protected CardDb cardDb;
@BeforeMethod
public void setup(){
public void setup() {
StaticData data = FModel.getMagicDb();
this.cardDb = data.getCommonCards();
}
@@ -27,9 +30,9 @@ public class CardDbTestLazyCardLoading extends ForgeCardMockTestCase {
}
@Test
public void testLoadAndGetBorrowing100_000ArrowsCardFromAllEditions(){
public void testLoadAndGetBorrowing100_000ArrowsCardFromAllEditions() {
String cardName = "Borrowing 100,000 Arrows";
String[] allAvailableEds = new String[] {"PTK", "ME3", "C13", "CMA", "A25", "MB1"};
String[] allAvailableEds = new String[] { "PTK", "ME3", "C13", "CMA", "A25", "MB1" };
assertEquals(this.cardDb.getCardArtPreference(), CardDb.CardArtPreference.LATEST_ART_ALL_EDITIONS);
@@ -45,7 +48,7 @@ public class CardDbTestLazyCardLoading extends ForgeCardMockTestCase {
assertEquals(borrowingCard.getEdition(), "MB1");
// Now get card from all the specified editions
for (String setCode : allAvailableEds){
for (String setCode : allAvailableEds) {
borrowingCard = this.cardDb.getCard(cardName, setCode);
assertNotNull(borrowingCard);
assertEquals(borrowingCard.getName(), cardName);
@@ -54,8 +57,8 @@ public class CardDbTestLazyCardLoading extends ForgeCardMockTestCase {
}
@Test
public void testLoadAndGetAinokBondKinFromKTKWithCaseInsensitiveCardName(){
String cardName = "aiNOk Bond-kin"; // wrong case
public void testLoadAndGetAinokBondKinFromKTKWithCaseInsensitiveCardName() {
String cardName = "aiNOk Bond-kin"; // wrong case
String expectedCardName = "Ainok Bond-Kin";
String setCode = "KTK";
@@ -72,12 +75,12 @@ public class CardDbTestLazyCardLoading extends ForgeCardMockTestCase {
assertEquals(borrowingCard.getName(), expectedCardName);
assertEquals(borrowingCard.getEdition(), setCode);
assertNull(this.cardDb.getCard(cardName, "IMA")); // not added yet
assertNull(this.cardDb.getCard(cardName, "IMA")); // not added yet
}
@Test
public void tesLoadAndGetAetherVialWithWrongCase(){
String cardName = "AEther vial"; // wrong case
public void tesLoadAndGetAetherVialWithWrongCase() {
String cardName = "AEther vial"; // wrong case
String expectedCardName = "Aether Vial";
PaperCard aetherVialCard = this.cardDb.getCard(cardName);
assertNull(aetherVialCard);
@@ -91,10 +94,10 @@ public class CardDbTestLazyCardLoading extends ForgeCardMockTestCase {
}
@Test
public void tesLoadAndGetUnsupportedCardHavingWrongSetCode(){
public void tesLoadAndGetUnsupportedCardHavingWrongSetCode() {
String cardName = "Dominating Licid";
String wrongSetCode = "AA";
String expectedSetCode = "EXO"; // Exodus
String expectedSetCode = "EXO"; // Exodus
CardRarity expectedCardRarity = CardRarity.Rare;
PaperCard dominatingLycidCard = this.cardDb.getCard(cardName);

View File

@@ -1,16 +1,17 @@
package forge.card;
import forge.item.PaperCard;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.assertNotNull;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
import static org.testng.Assert.assertNotNull;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class CardDbPerformanceTests extends CardDbTestCase {
import forge.item.PaperCard;
public class CardDbPerformanceTests extends CardDbCardMockTestCase {
private Set<String> fullDbCardNames = new TreeSet<>();
@@ -23,11 +24,11 @@ public class CardDbPerformanceTests extends CardDbTestCase {
this.fullDbCardNames.add(card.getName());
}
@Test(enabled = false) // disabled to not run in battery
@Test(enabled = false) // disabled to not run in battery
public void testBenchmarkFullDbGetCardLegacyImplementation() {
int nRuns = 100;
long averageTime = 0;
long minTime = 10000; // 10 secs
long minTime = 10000; // 10 secs
long maxTime = 0;
for (int r = 1; r <= nRuns; r++) {
long start = System.currentTimeMillis();
@@ -42,17 +43,17 @@ public class CardDbPerformanceTests extends CardDbTestCase {
if (timeRun > maxTime)
maxTime = timeRun;
}
System.out.println("[LEGACY] Total Time (in sec): " + ((double) averageTime)/ 1000);
System.out.println("[LEGACY] Average Time (in sec): " + ((double) averageTime / nRuns)/ 1000);
System.out.println("[LEGACY] Best Time (in sec): " + ((double) minTime)/ 1000);
System.out.println("[LEGACY] Worst Time (in sec): " + ((double) maxTime)/ 1000);
System.out.println("[LEGACY] Total Time (in sec): " + ((double) averageTime) / 1000);
System.out.println("[LEGACY] Average Time (in sec): " + ((double) averageTime / nRuns) / 1000);
System.out.println("[LEGACY] Best Time (in sec): " + ((double) minTime) / 1000);
System.out.println("[LEGACY] Worst Time (in sec): " + ((double) maxTime) / 1000);
}
@Test(enabled = false) // disabled to not run in battery
@Test(enabled = false) // disabled to not run in battery
public void testBenchmarkFullDbGetCardNewDbImplementation() {
int nRuns = 100;
long averageTime = 0;
long minTime = 10000; // 10 secs
long minTime = 10000; // 10 secs
long maxTime = 0;
for (int r = 1; r <= nRuns; r++) {
long start = System.currentTimeMillis();
@@ -67,14 +68,14 @@ public class CardDbPerformanceTests extends CardDbTestCase {
if (timeRun > maxTime)
maxTime = timeRun;
}
System.out.println("[NEW] Total Time (in sec): " + ((double) averageTime)/ 1000);
System.out.println("[NEW] Average Time (in sec): " + ((double) averageTime / nRuns)/ 1000);
System.out.println("[NEW] Best Time (in sec): " + ((double) minTime)/ 1000);
System.out.println("[NEW] Worst Time (in sec): " + ((double) maxTime)/ 1000);
System.out.println("[NEW] Total Time (in sec): " + ((double) averageTime) / 1000);
System.out.println("[NEW] Average Time (in sec): " + ((double) averageTime / nRuns) / 1000);
System.out.println("[NEW] Best Time (in sec): " + ((double) minTime) / 1000);
System.out.println("[NEW] Worst Time (in sec): " + ((double) maxTime) / 1000);
}
@Test
public void testGetCardFullDbNewImplementationToProfile(){
public void testGetCardFullDbNewImplementationToProfile() {
for (String name : this.fullDbCardNames) {
PaperCard card = this.cardDb.getCard(name);
assertNotNull(card);
@@ -82,7 +83,7 @@ public class CardDbPerformanceTests extends CardDbTestCase {
}
@Test
public void testGetCardFullDbLegacyImplementationToProfile(){
public void testGetCardFullDbLegacyImplementationToProfile() {
for (String name : this.fullDbCardNames) {
PaperCard card = this.legacyCardDb.getCard(name);
assertNotNull(card);

View File

@@ -1,30 +1,31 @@
package forge.card;
import forge.ImageCache;
import forge.ImageKeys;
import forge.item.PaperCard;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import javax.imageio.ImageIO;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.imageio.ImageIO;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import forge.ImageCache;
import forge.ImageKeys;
import forge.item.PaperCard;
/**
* Test Case for CardDb forcing No Image for all the cards.
* Check that everything still applies the same.
* Test Case for CardDb forcing No Image for all the cards. Check that
* everything still applies the same.
*
* Note: Run test for the class, being subclass will also run all
* other tests as regression.
* Note: Run test for the class, being subclass will also run all other tests as
* regression.
*/
public class CardDbTestWithNoImage extends CardDbTestCase {
public class CardDbWithNoImageCardDbMockTestCase extends CardDbCardMockTestCase {
@Override
@BeforeMethod
public void setup(){
public void setup() {
super.setup();
}
@@ -37,7 +38,7 @@ public class CardDbTestWithNoImage extends CardDbTestCase {
}
@Test
public void testCardIsReturnedEvenIfThereIsNoImage(){
public void testCardIsReturnedEvenIfThereIsNoImage() {
PaperCard shivanDragon = this.cardDb.getCard(cardNameShivanDragon);
assertNotNull(shivanDragon);
assertFalse(ImageKeys.hasImage(shivanDragon));

View File

@@ -1,26 +1,27 @@
package forge.card;
import forge.deck.CardPool;
import forge.item.PaperCard;
import forge.model.FModel;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
public class CardEditionCollectionTestCase extends ForgeCardMockTestCase {
import forge.deck.CardPool;
import forge.item.PaperCard;
import forge.model.FModel;
public class CardEditionCollectionCardMockTestCase extends CardMockTestCase {
@Test
public void testGetTheLatestOfAllTheOriginalEditionsOfCardsInPoolWithOriginalSets(){
public void testGetTheLatestOfAllTheOriginalEditionsOfCardsInPoolWithOriginalSets() {
CardEdition.Collection editions = FModel.getMagicDb().getEditions();
CardDb cardDb = FModel.getMagicDb().getCommonCards();
String[] cardNames = {"Shivan Dragon", "Animate Wall", "Balance", "Blessing", "Force of Will"};
String[] expectedSets = {"LEA", "LEA", "LEA", "LEA", "ALL"};
String[] cardNames = { "Shivan Dragon", "Animate Wall", "Balance", "Blessing", "Force of Will" };
String[] expectedSets = { "LEA", "LEA", "LEA", "LEA", "ALL" };
List<PaperCard> cards = new ArrayList<>();
for (int i=0; i < 5; i++){
for (int i = 0; i < 5; i++) {
String cardName = cardNames[i];
String expectedSet = expectedSets[i];
PaperCard card = cardDb.getCardFromEditions(cardName, CardDb.CardArtPreference.ORIGINAL_ART_ALL_EDITIONS);
@@ -35,18 +36,18 @@ public class CardEditionCollectionTestCase extends ForgeCardMockTestCase {
}
@Test
public void testGetTheLatestOfAllTheOriginalEditionsOfCardsInPoolWithLatestArtSets(){
public void testGetTheLatestOfAllTheOriginalEditionsOfCardsInPoolWithLatestArtSets() {
CardEdition.Collection editions = FModel.getMagicDb().getEditions();
CardDb cardDb = FModel.getMagicDb().getCommonCards();
String[] cardNames = {"Shivan Dragon", "Animate Wall", "Balance", "Blessing", "Force of Will"};
String[] expectedSets = {"M20", "MED", "SLD", "M14", "2XM"};
String[] cardNames = { "Shivan Dragon", "Animate Wall", "Balance", "Blessing", "Force of Will" };
String[] expectedSets = { "M20", "MED", "SLD", "M14", "2XM" };
List<PaperCard> cards = new ArrayList<>();
for (int i=0; i < 5; i++){
for (int i = 0; i < 5; i++) {
String cardName = cardNames[i];
String expectedSet = expectedSets[i];
PaperCard card = cardDb.getCardFromEditions(cardName, CardDb.CardArtPreference.LATEST_ART_ALL_EDITIONS);
assertEquals(card.getEdition(), expectedSet, "Assertion Failed for "+cardName);
assertEquals(card.getEdition(), expectedSet, "Assertion Failed for " + cardName);
cards.add(card);
}

View File

@@ -1,5 +1,25 @@
package forge.card;
import java.io.File;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.IObjectFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.ObjectFactory;
import forge.ImageCache;
import forge.ImageKeys;
import forge.Singletons;
@@ -11,31 +31,13 @@ import forge.localinstance.properties.ForgePreferences;
import forge.model.FModel;
import forge.util.Localizer;
import forge.util.TextUtil;
import org.apache.commons.lang3.StringUtils;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.IObjectFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.ObjectFactory;
import javax.imageio.ImageIO;
import java.io.File;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
@PrepareForTest(value = {FModel.class, Singletons.class, ResourceBundle.class,
ImageCache.class, ImageIO.class, ImageKeys.class,
ForgeConstants.class, Localizer.class})
@SuppressStaticInitializationFor({"forge.ImageCache", "forge.localinstance.properties.ForgeConstants"})
@PowerMockIgnore({"javax.xml.*", "org.xml.sax.*", "com.sun.org.apache.xerces.*", "org.w3c.dom.*", "org.springframework.context.*", "org.apache.log4j.*"})
public class ForgeCardMockTestCase extends PowerMockTestCase {
@PrepareForTest(value = { FModel.class, Singletons.class, ResourceBundle.class, ImageCache.class, ImageIO.class,
ImageKeys.class, ForgeConstants.class, Localizer.class })
@SuppressStaticInitializationFor({ "forge.ImageCache", "forge.localinstance.properties.ForgeConstants" })
@PowerMockIgnore({ "javax.xml.*", "org.xml.sax.*", "com.sun.org.apache.xerces.*", "org.w3c.dom.*",
"org.springframework.context.*", "org.apache.log4j.*" })
public class CardMockTestCase extends PowerMockTestCase {
public static final String MOCKED_LOCALISED_STRING = "any localised string";
@@ -73,7 +75,7 @@ public class ForgeCardMockTestCase extends PowerMockTestCase {
Field fAssetsDir = PowerMockito.field(ForgeConstants.class, "ASSETS_DIR");
fAssetsDir.set(ForgeConstants.class, assetDir);
// User Dir
String homeDir = ForgeCardMockTestCase.getUserDir();
String homeDir = CardMockTestCase.getUserDir();
Field fUserDir = PowerMockito.field(ForgeConstants.class, "USER_DIR");
fUserDir.set(ForgeConstants.class, homeDir);
// User Pref Dir
@@ -130,11 +132,14 @@ public class ForgeCardMockTestCase extends PowerMockTestCase {
@BeforeMethod
protected void initMocks() throws Exception {
//Loading a card also automatically loads the image, which we do not want (even if it wouldn't cause exceptions).
//The static initializer block in ImageCache can't fully be mocked (https://code.google.com/p/powermock/issues/detail?id=256), so we also need to mess with ImageIO...
// Loading a card also automatically loads the image, which we do not want (even
// if it wouldn't cause exceptions).
// The static initializer block in ImageCache can't fully be mocked
// (https://code.google.com/p/powermock/issues/detail?id=256), so we also need
// to mess with ImageIO...
initCardImageMocks();
initForgeConstants();
//Mocking some more static stuff
// Mocking some more static stuff
initForgePreferences();
initializeStaticData();
}
@@ -166,7 +171,8 @@ public class ForgeCardMockTestCase extends PowerMockTestCase {
}
protected void initCardImageMocks() {
//make sure that loading images only happens in a GUI environment, so we no longer need to mock this
// make sure that loading images only happens in a GUI environment, so we no
// longer need to mock this
PowerMockito.mockStatic(ImageIO.class);
PowerMockito.mockStatic(ImageCache.class);
PowerMockito.mockStatic(ImageKeys.class);

View File

@@ -1,14 +1,19 @@
package forge.card;
import forge.card.CardDb.CardRequest;
import forge.item.IPaperCard;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import forge.card.CardDb.CardRequest;
import forge.item.IPaperCard;
@Test(timeOut = 1000, enabled = true)
public class CardRequestTestCase {
public class CardRequestTest {
private String cardName;
private String edition;
@@ -20,7 +25,7 @@ public class CardRequestTestCase {
private final char sep = CardDb.NameSetSeparator;
@BeforeTest
public void setup(){
public void setup() {
cardName = "Shivan Dragon";
edition = "2ED";
collNr = "175";
@@ -31,7 +36,7 @@ public class CardRequestTestCase {
foilCollNr = "202";
}
public void testComposeCardNameAndSet(){
public void testComposeCardNameAndSet() {
// OK request
String requestInfo = CardRequest.compose(cardName, edition);
String expected = cardName + sep + edition;
@@ -50,7 +55,7 @@ public class CardRequestTestCase {
assertEquals(requestInfoFoil, foilCardName + sep + foilEdition);
}
public void testComposeCardNameSetAndArtIndex(){
public void testComposeCardNameSetAndArtIndex() {
String requestInfo = CardRequest.compose(cardName, edition, 2);
String expected = cardName + sep + edition + sep + 2;
assertEquals(requestInfo, expected);
@@ -61,20 +66,21 @@ public class CardRequestTestCase {
assertEquals(requestNegativeArtIndex, expected);
}
public void testComposeCardNameSetAndCollectorNumber(){
public void testComposeCardNameSetAndCollectorNumber() {
String requestInfo = CardRequest.compose(cardName, edition, collNr);
String expCN = "[" + collNr + "]";
String expected = cardName + sep + edition + sep + expCN;
assertEquals(requestInfo, expected);
// collNr only one bracket
requestInfo = CardRequest.compose(cardName, edition, "["+collNr);
requestInfo = CardRequest.compose(cardName, edition, "[" + collNr);
assertEquals(requestInfo, expected);
requestInfo = CardRequest.compose(cardName, edition, collNr+"]");
requestInfo = CardRequest.compose(cardName, edition, collNr + "]");
assertEquals(requestInfo, expected);
// collNr with leading spaces, as possible result from a wrong parsing in a deck file
// collNr with leading spaces, as possible result from a wrong parsing in a deck
// file
requestInfo = CardRequest.compose(cardName, edition, "\t\t 175 ");
assertEquals(requestInfo, expected);
@@ -83,13 +89,13 @@ public class CardRequestTestCase {
assertEquals(requestInfo, cardName + sep + edition + sep);
}
public void testComposeFullRequest(){
public void testComposeFullRequest() {
String requestInfo = CardRequest.compose(cardName, edition, 1, collNr);
String expected = cardName + sep + edition + sep + 1 + sep + "[" + collNr + "]";
assertEquals(requestInfo, expected);
}
public void testFromStringCardNameOnly(){
public void testFromStringCardNameOnly() {
CardRequest request = CardRequest.fromString(cardName);
assertEquals(request.cardName, cardName);
assertEquals(request.artIndex, IPaperCard.DEFAULT_ART_INDEX);
@@ -97,7 +103,7 @@ public class CardRequestTestCase {
assertEquals(request.collectorNumber, IPaperCard.NO_COLLECTOR_NUMBER);
}
public void testFromStringCardNameAndSetCode(){
public void testFromStringCardNameAndSetCode() {
String requestString = cardName + sep + edition;
CardRequest request = CardRequest.fromString(requestString);
assertEquals(request.cardName, cardName);
@@ -115,7 +121,7 @@ public class CardRequestTestCase {
assertEquals(request.collectorNumber, IPaperCard.NO_COLLECTOR_NUMBER);
}
public void testFromStringCardNameAndSetCodeAndArtIndex(){
public void testFromStringCardNameAndSetCodeAndArtIndex() {
String requestString = cardName + sep + edition + sep + 2;
CardRequest request = CardRequest.fromString(requestString);
assertEquals(request.cardName, cardName);
@@ -131,7 +137,6 @@ public class CardRequestTestCase {
assertEquals(request.artIndex, 20);
assertEquals(request.collectorNumber, IPaperCard.NO_COLLECTOR_NUMBER);
// foil
requestString = foilCardNameFoil + sep + foilEdition + sep + IPaperCard.DEFAULT_ART_INDEX;
request = CardRequest.fromString(requestString);
@@ -142,7 +147,7 @@ public class CardRequestTestCase {
assertEquals(request.collectorNumber, IPaperCard.NO_COLLECTOR_NUMBER);
}
public void testFromStringCardNameAndSetCodeAndCollectorNumber(){
public void testFromStringCardNameAndSetCodeAndCollectorNumber() {
String requestString = cardName + sep + edition + sep + "[" + collNr + "]";
CardRequest request = CardRequest.fromString(requestString);
assertEquals(request.cardName, cardName);
@@ -168,7 +173,7 @@ public class CardRequestTestCase {
assertEquals(request.collectorNumber, foilCollNr);
}
public void fromStringFullInfo(){
public void fromStringFullInfo() {
String requestString = cardName + sep + edition + sep + 2 + sep + "[" + collNr + "]";
CardRequest request = CardRequest.fromString(requestString);
assertEquals(request.cardName, cardName);
@@ -185,17 +190,17 @@ public class CardRequestTestCase {
assertEquals(request.collectorNumber, IPaperCard.NO_COLLECTOR_NUMBER);
// foil
requestString = foilCardNameFoil + sep + foilEdition + sep + 3 + sep +"[" + foilCollNr + "]";
requestString = foilCardNameFoil + sep + foilEdition + sep + 3 + sep + "[" + foilCollNr + "]";
request = CardRequest.fromString(requestString);
assertEquals(request.cardName, foilCardName);
assertEquals(request.edition, foilEdition);
assertEquals(request.artIndex,3);
assertEquals(request.artIndex, 3);
assertTrue(request.isFoil);
assertEquals(request.collectorNumber, foilCollNr);
}
@Test
public void testCreatingCardRequestUsingAnotherRequestStringAsCardName(){
public void testCreatingCardRequestUsingAnotherRequestStringAsCardName() {
String requestString = CardRequest.compose(cardName, edition, 1);
CardRequest request = CardRequest.fromString(requestString);
@@ -216,7 +221,7 @@ public class CardRequestTestCase {
}
@Test
public void testCreatingCardRequestWithArtIndexGreaterThanNine(){
public void testCreatingCardRequestWithArtIndexGreaterThanNine() {
String requestString = CardRequest.compose("Island", "SLD", 13);
CardRequest request = CardRequest.fromString(requestString);
@@ -226,14 +231,16 @@ public class CardRequestTestCase {
assertEquals(request.collectorNumber, IPaperCard.NO_COLLECTOR_NUMBER);
}
@Test void isFoilCardNameMethod(){
@Test
void isFoilCardNameMethod() {
assertTrue(CardRequest.isFoilCardName("Counterspell+"));
assertFalse(CardRequest.isFoilCardName("Counterspell"));
assertTrue(CardRequest.isFoilCardName(" Counterspell+ "));
assertFalse(CardRequest.isFoilCardName(" Counterspell "));
}
@Test void testComposeCardRequestWithCardNameAndFoil(){
@Test
void testComposeCardRequestWithCardNameAndFoil() {
String cardName = "Counterspell";
String foilCardName = "Counterspell+";

View File

@@ -1,49 +1,54 @@
package forge.card;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimaps;
import forge.item.PaperCard;
import forge.util.Aggregates;
import forge.util.CollectionSuppliers;
import forge.util.MyRandom;
import forge.util.TextUtil;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
/**
* Test Class (only for test purposes) to compare previous method implementations
* with the new refactored ones. This class has been updated to the latest version
* available of methods' implementation before the change is going to be submitted.
* This is also a useful way to keep a backlog of changes whenever major
* API changes like this MR are going to happen.
* Test Class (only for test purposes) to compare previous method
* implementations with the new refactored ones. This class has been updated to
* the latest version available of methods' implementation before the change is
* going to be submitted. This is also a useful way to keep a backlog of changes
* whenever major API changes like this MR are going to happen.
*/
public class LegacyCardDb {
public CardEdition.Collection editions;
public ListMultimap<String, PaperCard> allCardsByName = Multimaps.newListMultimap(new TreeMap<>(String.CASE_INSENSITIVE_ORDER), CollectionSuppliers.arrayLists());
public ListMultimap<String, PaperCard> allCardsByName = Multimaps
.newListMultimap(new TreeMap<>(String.CASE_INSENSITIVE_ORDER), CollectionSuppliers.arrayLists());
public enum LegacySetPreference {
Latest(false),
LatestCoreExp(true),
Earliest(false),
EarliestCoreExp(true),
Random(false);
Latest(false), LatestCoreExp(true), Earliest(false), EarliestCoreExp(true), Random(false);
final boolean filterSets;
LegacySetPreference(boolean filterIrregularSets) {
filterSets = filterIrregularSets;
}
public boolean accept(CardEdition ed) {
if (ed == null) return false;
return !filterSets || ed.getType() == CardEdition.Type.CORE || ed.getType() == CardEdition.Type.EXPANSION || ed.getType() == CardEdition.Type.REPRINT;
if (ed == null)
return false;
return !filterSets || ed.getType() == CardEdition.Type.CORE || ed.getType() == CardEdition.Type.EXPANSION
|| ed.getType() == CardEdition.Type.REPRINT;
}
}
public final static String foilSuffix = "+";
public final static char NameSetSeparator = '|';
@@ -53,7 +58,7 @@ public class LegacyCardDb {
public String edition;
public int artIndex;
public boolean isFoil;
private LegacyCardRequest(String name, String edition, int artIndex, boolean isFoil) {
cardName = name;
this.edition = edition;
@@ -70,7 +75,8 @@ public class LegacyCardDb {
String[] nameParts = TextUtil.split(name, NameSetSeparator);
int setPos = nameParts.length >= 2 && !StringUtils.isNumeric(nameParts[1]) ? 1 : -1;
int artPos = nameParts.length >= 2 && StringUtils.isNumeric(nameParts[1]) ? 1 : nameParts.length >= 3 && StringUtils.isNumeric(nameParts[2]) ? 2 : -1;
int artPos = nameParts.length >= 2 && StringUtils.isNumeric(nameParts[1]) ? 1
: nameParts.length >= 3 && StringUtils.isNumeric(nameParts[2]) ? 2 : -1;
String cardName = nameParts[0];
if (cardName.endsWith(foilSuffix)) {
@@ -88,9 +94,9 @@ public class LegacyCardDb {
}
}
public LegacyCardDb(Collection<PaperCard> cards0, CardEdition.Collection editions){
public LegacyCardDb(Collection<PaperCard> cards0, CardEdition.Collection editions) {
this.editions = editions;
for (PaperCard card : cards0){
for (PaperCard card : cards0) {
allCardsByName.put(card.getName(), card);
}
}
@@ -133,7 +139,9 @@ public class LegacyCardDb {
private PaperCard tryGetCard(LegacyCardDb.LegacyCardRequest request) {
Collection<PaperCard> cards = getAllCards(request.cardName);
if (cards == null) { return null; }
if (cards == null) {
return null;
}
PaperCard result = null;
@@ -149,8 +157,7 @@ public class LegacyCardDb {
Collection<PaperCard> candidates;
if (reqEdition == null) {
candidates = new ArrayList<>(cards);
}
else {
} else {
candidates = new ArrayList<>();
for (PaperCard pc : cards) {
if (pc.getEdition().equalsIgnoreCase(reqEdition)) {
@@ -163,13 +170,12 @@ public class LegacyCardDb {
}
result = Aggregates.random(candidates);
//if card image doesn't exist for chosen candidate, try another one if possible
// if card image doesn't exist for chosen candidate, try another one if possible
while (candidates.size() > 1 && !result.hasImage()) {
candidates.remove(result);
result = Aggregates.random(candidates);
}
}
else {
} else {
for (PaperCard pc : cards) {
if (pc.getEdition().equalsIgnoreCase(reqEdition) && request.artIndex == pc.getArtIndex()) {
result = pc;
@@ -177,7 +183,9 @@ public class LegacyCardDb {
}
}
}
if (result == null) { return null; }
if (result == null) {
return null;
}
return request.isFoil ? getFoiled(result) : result;
}
@@ -185,28 +193,32 @@ public class LegacyCardDb {
public PaperCard getFoiled(PaperCard card0) {
return card0.getFoiled();
}
public PaperCard getCardFromEdition(final String cardName, LegacySetPreference fromSet) {
return getCardFromEdition(cardName, null, fromSet);
}
public PaperCard getCardFromEdition(final String cardName, final Date printedBefore, final LegacySetPreference fromSet) {
public PaperCard getCardFromEdition(final String cardName, final Date printedBefore,
final LegacySetPreference fromSet) {
return getCardFromEdition(cardName, printedBefore, fromSet, -1);
}
public PaperCard getCardFromEdition(final String cardName, final Date printedBefore, final LegacySetPreference fromSets, int artIndex) {
public PaperCard getCardFromEdition(final String cardName, final Date printedBefore,
final LegacySetPreference fromSets, int artIndex) {
final CardDb.CardRequest cr = CardDb.CardRequest.fromString(cardName);
LegacySetPreference fromSet = fromSets;
List<PaperCard> cards = getAllCards(cr.cardName);
if (printedBefore != null){
if (printedBefore != null) {
cards = Lists.newArrayList(Iterables.filter(cards, new Predicate<PaperCard>() {
@Override public boolean apply(PaperCard c) {
@Override
public boolean apply(PaperCard c) {
CardEdition ed = editions.get(c.getEdition());
return ed.getDate().before(printedBefore); }
return ed.getDate().before(printedBefore);
}
}));
}
if (cards.size() == 0) // Don't bother continuing! No cards has been found!
if (cards.size() == 0) // Don't bother continuing! No cards has been found!
return null;
boolean cardsListReadOnly = true;
@@ -217,7 +229,10 @@ public class LegacyCardDb {
if (StringUtils.isNotBlank(cr.edition)) {
cards = Lists.newArrayList(Iterables.filter(cards, new Predicate<PaperCard>() {
@Override public boolean apply(PaperCard input) { return input.getEdition().equalsIgnoreCase(cr.edition); }
@Override
public boolean apply(PaperCard input) {
return input.getEdition().equalsIgnoreCase(cr.edition);
}
}));
}
if (artIndex == -1 && cr.artIndex > 0) {
@@ -227,25 +242,25 @@ public class LegacyCardDb {
int sz = cards.size();
if (fromSet == LegacySetPreference.Earliest || fromSet == LegacySetPreference.EarliestCoreExp) {
PaperCard firstWithoutImage = null;
for (int i = sz - 1 ; i >= 0 ; i--) {
for (int i = sz - 1; i >= 0; i--) {
PaperCard pc = cards.get(i);
CardEdition ed = editions.get(pc.getEdition());
if (!fromSet.accept(ed)) {
continue;
}
if ((artIndex <= 0 || pc.getArtIndex() == artIndex) && (printedBefore == null || ed.getDate().before(printedBefore))) {
if ((artIndex <= 0 || pc.getArtIndex() == artIndex)
&& (printedBefore == null || ed.getDate().before(printedBefore))) {
if (pc.hasImage()) {
return pc;
}
else if (firstWithoutImage == null) {
firstWithoutImage = pc; //ensure first without image returns if none have image
} else if (firstWithoutImage == null) {
firstWithoutImage = pc; // ensure first without image returns if none have image
}
}
}
return firstWithoutImage;
}
else if (fromSet == LegacySetPreference.LatestCoreExp || fromSet == LegacySetPreference.Latest || fromSet == null || fromSet == LegacySetPreference.Random) {
} else if (fromSet == LegacySetPreference.LatestCoreExp || fromSet == LegacySetPreference.Latest
|| fromSet == null || fromSet == LegacySetPreference.Random) {
PaperCard firstWithoutImage = null;
for (int i = 0; i < sz; i++) {
PaperCard pc = cards.get(i);
@@ -254,31 +269,29 @@ public class LegacyCardDb {
continue;
}
if ((artIndex < 0 || pc.getArtIndex() == artIndex) && (printedBefore == null || ed.getDate().before(printedBefore))) {
if ((artIndex < 0 || pc.getArtIndex() == artIndex)
&& (printedBefore == null || ed.getDate().before(printedBefore))) {
if (fromSet == LegacySetPreference.LatestCoreExp || fromSet == LegacySetPreference.Latest) {
if (pc.hasImage()) {
return pc;
} else if (firstWithoutImage == null) {
firstWithoutImage = pc; // ensure first without image returns if none have image
}
else if (firstWithoutImage == null) {
firstWithoutImage = pc; //ensure first without image returns if none have image
}
}
else {
} else {
while (sz > i) {
int randomIndex = i + MyRandom.getRandom().nextInt(sz - i);
pc = cards.get(randomIndex);
if (pc.hasImage()) {
return pc;
}
else {
} else {
if (firstWithoutImage == null) {
firstWithoutImage = pc; //ensure first without image returns if none have image
firstWithoutImage = pc; // ensure first without image returns if none have image
}
if (cardsListReadOnly) { //ensure we don't modify a cached collection
if (cardsListReadOnly) { // ensure we don't modify a cached collection
cards = new ArrayList<>(cards);
cardsListReadOnly = false;
}
cards.remove(randomIndex); //remove card from collection and try another random card
cards.remove(randomIndex); // remove card from collection and try another random card
sz--;
}
}

View File

@@ -3,7 +3,7 @@ package forge.gamesimulationtests;
import forge.ImageCache;
import forge.ImageKeys;
import forge.Singletons;
import forge.card.ForgeCardMockTestCase;
import forge.card.CardMockTestCase;
import forge.game.GameLogFormatter;
import forge.gamesimulationtests.util.GameWrapper;
import forge.gamesimulationtests.util.player.PlayerSpecification;
@@ -24,44 +24,46 @@ import org.testng.annotations.BeforeMethod;
import javax.imageio.ImageIO;
import java.util.ResourceBundle;
@PrepareForTest(value = {FModel.class, Singletons.class, ResourceBundle.class,
ImageCache.class, ImageIO.class, ImageKeys.class,
ForgeConstants.class, Localizer.class, Sentry.class, GameLogFormatter.class})
@SuppressStaticInitializationFor({"forge.ImageCache", "forge.localinstance.properties.ForgeConstants"})
@PowerMockIgnore({"javax.xml.*", "org.xml.sax.*", "com.sun.org.apache.xerces.*", "org.w3c.dom.*", "org.springframework.context.*", "org.apache.log4j.*"})
public class BaseGameSimulationTest extends ForgeCardMockTestCase {
@PrepareForTest(value = { FModel.class, Singletons.class, ResourceBundle.class, ImageCache.class, ImageIO.class,
ImageKeys.class, ForgeConstants.class, Localizer.class, Sentry.class, GameLogFormatter.class })
@SuppressStaticInitializationFor({ "forge.ImageCache", "forge.localinstance.properties.ForgeConstants" })
@PowerMockIgnore({ "javax.xml.*", "org.xml.sax.*", "com.sun.org.apache.xerces.*", "org.w3c.dom.*",
"org.springframework.context.*", "org.apache.log4j.*" })
public class BaseGameSimulationTest extends CardMockTestCase {
@BeforeMethod
@Override
protected void initMocks() throws Exception {
super.initMocks();
PowerMockito.mockStatic(Sentry.class);
PowerMockito.mockStatic(GameLogFormatter.class);
//PowerMockito.when(Sentry.getContext()).thenReturn(new Context());
Lang.createInstance("en-US");
}
@BeforeMethod
@Override
protected void initMocks() throws Exception {
super.initMocks();
PowerMockito.mockStatic(Sentry.class);
PowerMockito.mockStatic(GameLogFormatter.class);
// PowerMockito.when(Sentry.getContext()).thenReturn(new Context());
Lang.createInstance("en-US");
}
protected void runGame(GameWrapper game, PlayerSpecification expectedWinner, int finalTurn, AssertAction... postGameAssertActions) {
try {
initMocks();
game.runGame();
verifyThatTheGameHasFinishedAndThatPlayerHasWonOnTurn(game, expectedWinner, finalTurn);
if(postGameAssertActions != null && postGameAssertActions.length > 0) {
for(AssertAction assertAction : postGameAssertActions) {
assertAction.performAssertion(game.getGame());
}
}
} catch (Throwable t) {
System.out.println(game.toString());
throw new RuntimeException(t);
}
}
protected void verifyThatTheGameHasFinishedAndThatPlayerHasWonOnTurn(GameWrapper game, PlayerSpecification expectedWinner, int finalTurn) {
Assert.assertTrue(game.getGame().isGameOver());
Assert.assertEquals(game.getGame().getOutcome().getLastTurnNumber(), finalTurn);
Assert.assertEquals(game.getGame().getOutcome().getWinningPlayer().getPlayer().getName(),
PlayerSpecificationHandler.INSTANCE.find(game.getGame(), expectedWinner).getName());
Assert.assertTrue(game.getPlayerActions() == null || game.getPlayerActions().isEmpty());
}
protected void runGame(GameWrapper game, PlayerSpecification expectedWinner, int finalTurn,
AssertAction... postGameAssertActions) {
try {
initMocks();
game.runGame();
verifyThatTheGameHasFinishedAndThatPlayerHasWonOnTurn(game, expectedWinner, finalTurn);
if (postGameAssertActions != null && postGameAssertActions.length > 0) {
for (AssertAction assertAction : postGameAssertActions) {
assertAction.performAssertion(game.getGame());
}
}
} catch (Throwable t) {
System.out.println(game.toString());
throw new RuntimeException(t);
}
}
protected void verifyThatTheGameHasFinishedAndThatPlayerHasWonOnTurn(GameWrapper game,
PlayerSpecification expectedWinner, int finalTurn) {
Assert.assertTrue(game.getGame().isGameOver());
Assert.assertEquals(game.getGame().getOutcome().getLastTurnNumber(), finalTurn);
Assert.assertEquals(game.getGame().getOutcome().getWinningPlayer().getPlayer().getName(),
PlayerSpecificationHandler.INSTANCE.find(game.getGame(), expectedWinner).getName());
Assert.assertTrue(game.getPlayerActions() == null || game.getPlayerActions().isEmpty());
}
}