diff options
author | Eduardo Pedroni <e.pedroni91@gmail.com> | 2016-03-25 22:51:03 +0100 |
---|---|---|
committer | Eduardo Pedroni <e.pedroni91@gmail.com> | 2016-03-25 22:51:03 +0100 |
commit | 5a9327b4721d50cee954369eaf25d096ac8b9c52 (patch) | |
tree | 9ddcceb564e14d9c2b8dbdf5544bbdb63c327234 | |
parent | f66651cdd6cf6d7449428caae712eeeba8300194 (diff) |
Sorting out tests for new class hierarchy
-rw-r--r-- | src/eu/equalparts/cardbase/Cardbase.java | 157 | ||||
-rw-r--r-- | src/eu/equalparts/cardbase/cli/CardbaseCLI.java | 34 | ||||
-rw-r--r-- | src/eu/equalparts/cardbase/comparator/CardComparator.java | 5 | ||||
-rw-r--r-- | src/eu/equalparts/cardbase/decks/Statistics.java | 2 | ||||
-rw-r--r-- | test/eu/equalparts/cardbase/CardbaseTest.java | 146 |
5 files changed, 102 insertions, 242 deletions
diff --git a/src/eu/equalparts/cardbase/Cardbase.java b/src/eu/equalparts/cardbase/Cardbase.java index cdceb75..be66127 100644 --- a/src/eu/equalparts/cardbase/Cardbase.java +++ b/src/eu/equalparts/cardbase/Cardbase.java @@ -14,6 +14,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import eu.equalparts.cardbase.cards.Card; +import eu.equalparts.cardbase.cardstorage.StandaloneCardContainer; import eu.equalparts.cardbase.comparator.CardComparator; import eu.equalparts.cardbase.decks.ReferenceDeck; import eu.equalparts.cardbase.utils.JSON; @@ -23,37 +24,33 @@ import eu.equalparts.cardbase.utils.JSON; * * @author Eduardo Pedroni */ -public class Cardbase { +public class Cardbase extends StandaloneCardContainer { - private static class DataContainer { - /** - * The cards in the cardbase, set in key-value pairs where the key is the card hash, - * generated using {makeHash()}. - */ - public Map<Integer, Card> cards; - /** - * TODO comment - */ - public Map<Integer, Integer> collection; - /** - * The decks which have been saved along with this collection of cards. - */ - public Map<String, ReferenceDeck> decks; - - public DataContainer() { - cards = new HashMap<Integer, Card>(); - collection = new HashMap<Integer, Integer>(); - decks = new HashMap<String, ReferenceDeck>(); - } - } +// private static class DataContainer { +// /** +// * The cards in the cardbase, set in key-value pairs where the key is the card hash, +// * generated using {makeHash()}. +// */ +// public Map<Integer, Card> cards; +// /** +// * TODO comment +// */ +// public Map<Integer, Integer> collection; + +// +// public DataContainer() { +// cards = new HashMap<Integer, Card>(); +// collection = new HashMap<Integer, Integer>(); +// decks = new HashMap<String, ReferenceDeck>(); +// } +// } - private DataContainer dataContainer; +// private DataContainer dataContainer; /** - * Debug flag is raised when the DEBUG environment variable is set. This causes additional - * information to be printed to the console. + * The decks which have been saved along with this collection of cards. */ - public static final boolean DEBUG = System.getenv("CB_DEBUG") != null; + public Map<String, ReferenceDeck> decks; /** * Initialises the cardbase with the contents of a file. @@ -64,15 +61,15 @@ public class Cardbase { * @throws JsonMappingException if the specified file structure does not match that of {@code Cardbase}. * @throws IOException if a low-level I/O problem (unexpected end-of-input, network error) occurs. */ - public Cardbase(File cardbaseFile) throws JsonParseException, JsonMappingException, IOException { - dataContainer = JSON.mapper.readValue(cardbaseFile, DataContainer.class); + public static Cardbase load(File cardbaseFile) throws JsonParseException, JsonMappingException, IOException { + return JSON.mapper.readValue(cardbaseFile, Cardbase.class); } /** * Initialises a clean cardbase. */ public Cardbase() { - dataContainer = new DataContainer(); + super(); } /** @@ -86,7 +83,7 @@ public class Cardbase { * @throws IOException if a low-level I/O problem (unexpected end-of-input, network error) occurs. */ public void writeCollection(File outputFile) throws JsonGenerationException, JsonMappingException, IOException { - JSON.mapper.writeValue(outputFile, dataContainer); + JSON.mapper.writeValue(outputFile, this); } /** @@ -99,20 +96,20 @@ public class Cardbase { * already exists. *TODO fix comment */ - public void addCard(Card cardToAdd, int addCount) { - Integer hashCode = cardToAdd.hashCode(); - - // ensure that card is in the card map - dataContainer.cards.putIfAbsent(hashCode, cardToAdd); - - // ensure that card is in the collection, with the correct count - Integer currentCount = dataContainer.collection.get(hashCode); - if (currentCount != null) { - dataContainer.collection.replace(hashCode, currentCount + addCount); - } else { - dataContainer.collection.put(hashCode, addCount); - } - } +// public void addCard(Card cardToAdd, int addCount) { +// Integer hashCode = cardToAdd.hashCode(); +// +// // ensure that card is in the card map +// dataContainer.cards.putIfAbsent(hashCode, cardToAdd); +// +// // ensure that card is in the collection, with the correct count +// Integer currentCount = dataContainer.collection.get(hashCode); +// if (currentCount != null) { +// dataContainer.collection.replace(hashCode, currentCount + addCount); +// } else { +// dataContainer.collection.put(hashCode, addCount); +// } +// } /** * Removes a specific amount of a card from the cardbase. @@ -131,23 +128,23 @@ public class Cardbase { * @return the number of cards actually removed. *TODO comment */ - public Integer removeCard(Card cardToRemove, int removeCount) { - Integer hashCode = cardToRemove.hashCode(); - int removed = 0; - - Integer currentCount = dataContainer.collection.get(hashCode); - if (currentCount != null) { - if (removeCount >= currentCount) { - dataContainer.collection.remove(hashCode); - dataContainer.cards.remove(hashCode); - removed = currentCount; - } else { - dataContainer.collection.replace(hashCode, currentCount - removeCount); - removed = removeCount; - } - } - return removed; - } +// public Integer removeCard(Card cardToRemove, int removeCount) { +// Integer hashCode = cardToRemove.hashCode(); +// int removed = 0; +// +// Integer currentCount = dataContainer.collection.get(hashCode); +// if (currentCount != null) { +// if (removeCount >= currentCount) { +// dataContainer.collection.remove(hashCode); +// dataContainer.cards.remove(hashCode); +// removed = currentCount; +// } else { +// dataContainer.collection.replace(hashCode, currentCount - removeCount); +// removed = removeCount; +// } +// } +// return removed; +// } /** * Returns a card from the cardbase by set code and number. @@ -157,9 +154,9 @@ public class Cardbase { * @param number the requested card's set number. * @return the requested {@code Card} or null if no card is found. */ - public Card getCard(String setCode, String number) { - return dataContainer.cards.get(Card.makeHash(setCode, number)); - } +// public Card getCard(String setCode, String number) { +// return dataContainer.cards.get(Card.makeHash(setCode, number)); +// } /** * Returns a card from the cardbase by hash. The card's hash @@ -169,21 +166,9 @@ public class Cardbase { * @param hash the Cardbase hash of the requested card. * @return the requested {@code Card} or null if no card is found. */ - protected Card getCardByHash(Integer hash) { - return dataContainer.cards.get(hash); - } - - /** - * This method is intended to allow iteration directly on the list of cards, - * while at the same time retaining control over the insert and remove procedures. - * The returned {@code List} is a read-only; trying to modify its structure will - * result in an {@code UnsupportedOperationException}. - * - * @return an unmodifiable list of all the cards in the cardbase. - */ - public Collection<Card> getCards() { - return Collections.unmodifiableCollection(dataContainer.cards.values()); - } +// protected Card getCardByHash(Integer hash) { +// return dataContainer.cards.get(hash); +// } /** * @param fieldName the name of the field by which to sort. @@ -191,19 +176,15 @@ public class Cardbase { * @throws NoSuchFieldException if the field provided is invalid. */ public Collection<Card> sortByField(String fieldName) throws NoSuchFieldException { - List<Card> sortedCards = new ArrayList<Card>(dataContainer.cards.values()); + List<Card> sortedCards = new ArrayList<Card>(getCards()); sortedCards.sort(new CardComparator(Card.class.getDeclaredField(fieldName))); return Collections.unmodifiableCollection(sortedCards); } - - public Map<String, ReferenceDeck> getDecks() { - return Collections.unmodifiableMap(dataContainer.decks); - } - public int getCount(Card card) { - Integer count = dataContainer.collection.get(Card.makeHash(card.setCode, card.number)); - return count != null ? count : 0; - } +// public int getCount(Card card) { +// Integer count = dataContainer.collection.get(Card.makeHash(card.setCode, card.number)); +// return count != null ? count : 0; +// } // public List<Card> getMissingCards(StandaloneDeck deckToCheck) { // List<Card> missingCards = new ArrayList<Card>(); diff --git a/src/eu/equalparts/cardbase/cli/CardbaseCLI.java b/src/eu/equalparts/cardbase/cli/CardbaseCLI.java index b1a4028..cbce4f9 100644 --- a/src/eu/equalparts/cardbase/cli/CardbaseCLI.java +++ b/src/eu/equalparts/cardbase/cli/CardbaseCLI.java @@ -35,7 +35,12 @@ public final class CardbaseCLI { public Card card; public int count; } - + + /** + * Debug flag is raised when the DEBUG environment variable is set. This causes additional + * information to be printed to the console. + */ + public static final boolean DEBUG = System.getenv("CB_DEBUG") != null; /** * Location of the help file. */ @@ -95,19 +100,19 @@ public final class CardbaseCLI { } catch (JsonParseException e) { System.out.println("Error: poorly formatted cardbase, check the syntax and try again."); // although the problem could also be with the upstream CardSetList json. - if (Cardbase.DEBUG) e.printStackTrace(); + if (DEBUG) e.printStackTrace(); System.exit(1); } catch (JsonMappingException e) { System.out.println("Error: unexpected fields found in cardbase, is it from an old version?"); - if (Cardbase.DEBUG) e.printStackTrace(); + if (DEBUG) e.printStackTrace(); System.exit(1); } catch (IOException e) { System.out.println("Error: something went wrong reading cardbase file, abort..."); - if (Cardbase.DEBUG) e.printStackTrace(); + if (DEBUG) e.printStackTrace(); System.exit(1); } catch (IllegalArgumentException e) { System.out.println("Error: the file provided is invalid."); - if (Cardbase.DEBUG) e.printStackTrace(); + if (DEBUG) e.printStackTrace(); System.exit(1); } } @@ -127,7 +132,7 @@ public final class CardbaseCLI { System.out.println("Welcome to Cardbase CLI!"); // set debug flag if we are debugging - if (Cardbase.DEBUG) System.out.println("Debug mode is on."); + if (DEBUG) System.out.println("Debug mode is on."); // initialise the universe mtgUniverse = new MTGUniverse(remoteURL); @@ -137,7 +142,7 @@ public final class CardbaseCLI { cardbaseFile = new File(args[0]); if (cardbaseFile.exists() && cardbaseFile.isFile() && cardbaseFile.canRead()) { System.out.println("Loading cardbase from \"" + args[0] + "\"."); - cardbase = new Cardbase(cardbaseFile); + cardbase = Cardbase.load(cardbaseFile); } else { throw new IllegalArgumentException(); } @@ -180,7 +185,7 @@ public final class CardbaseCLI { } } catch (IOException e) { System.out.println("Error: something went wrong with stdin, exiting..."); - if (Cardbase.DEBUG) e.printStackTrace(); + if (DEBUG) e.printStackTrace(); } } @@ -211,7 +216,8 @@ public final class CardbaseCLI { set(args); } else if (command.equalsIgnoreCase("glance")) { glance(); - } else if (command.equalsIgnoreCase("peruse")) { + } else if (command.equalsIgnoreCase("peruse") + || command.equalsIgnoreCase("p")) { peruse(args); } else if (command.equalsIgnoreCase("undo")) { undo(); @@ -258,10 +264,10 @@ public final class CardbaseCLI { savePrompt = false; } catch (JsonGenerationException | JsonMappingException e) { System.out.println("Error: something terrible happened to the internal cardbase data structure. Oops."); - if (Cardbase.DEBUG) e.printStackTrace(); + if (DEBUG) e.printStackTrace(); } catch (IOException e) { System.out.println("Error: lost contact with the output file."); - if (Cardbase.DEBUG) e.printStackTrace(); + if (DEBUG) e.printStackTrace(); } } } else { @@ -317,13 +323,13 @@ public final class CardbaseCLI { } } catch (JsonParseException e) { System.out.println("Error: JSON fetched from upstream was not formatted properly."); - if (Cardbase.DEBUG) e.printStackTrace(); + if (DEBUG) e.printStackTrace(); } catch (JsonMappingException e) { System.out.println("Error: JSON fetched from upstream does not match the data structure used internally."); - if (Cardbase.DEBUG) e.printStackTrace(); + if (DEBUG) e.printStackTrace(); } catch (IOException e) { System.out.println("Error: JSON could not be fetched from upstream."); - if (Cardbase.DEBUG) e.printStackTrace(); + if (DEBUG) e.printStackTrace(); } } else { System.out.println("Please enter a set code (use \"sets\" to see all valid set codes)."); diff --git a/src/eu/equalparts/cardbase/comparator/CardComparator.java b/src/eu/equalparts/cardbase/comparator/CardComparator.java index 7173109..c3ff736 100644 --- a/src/eu/equalparts/cardbase/comparator/CardComparator.java +++ b/src/eu/equalparts/cardbase/comparator/CardComparator.java @@ -7,7 +7,6 @@ import java.lang.reflect.Type; import java.util.Comparator; import java.util.function.BiFunction; -import eu.equalparts.cardbase.Cardbase; import eu.equalparts.cardbase.cards.Card; import eu.equalparts.cardbase.comparator.SpecialFields.DirtyNumber; import eu.equalparts.cardbase.comparator.SpecialFields.Rarity; @@ -93,10 +92,10 @@ public class CardComparator implements Comparator<Card> { } catch (IllegalArgumentException e) { System.out.println("Error: class Card does not define field \"" + fieldToCompare.getName() + "\"."); - if (Cardbase.DEBUG) e.printStackTrace(); + e.printStackTrace(); } catch (IllegalAccessException e) { System.out.println("Error: field " + fieldToCompare.getName() + " in Card is not visible."); - if (Cardbase.DEBUG) e.printStackTrace(); + e.printStackTrace(); } // fallback, this shouldn't happen diff --git a/src/eu/equalparts/cardbase/decks/Statistics.java b/src/eu/equalparts/cardbase/decks/Statistics.java index d48dd59..b2c4108 100644 --- a/src/eu/equalparts/cardbase/decks/Statistics.java +++ b/src/eu/equalparts/cardbase/decks/Statistics.java @@ -6,8 +6,6 @@ public final class Statistics { private Statistics() {} - - public static double calculatePercentage(StandaloneDeck deck, String type) { double allCardsByType = count(deck, type); double allCards = count(deck); diff --git a/test/eu/equalparts/cardbase/CardbaseTest.java b/test/eu/equalparts/cardbase/CardbaseTest.java index 64009a3..1a54298 100644 --- a/test/eu/equalparts/cardbase/CardbaseTest.java +++ b/test/eu/equalparts/cardbase/CardbaseTest.java @@ -1,12 +1,11 @@ package eu.equalparts.cardbase; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.FileWriter; import java.io.IOException; -import java.lang.reflect.Field; -import java.util.Map; import org.junit.AfterClass; import org.junit.Before; @@ -17,12 +16,9 @@ import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import eu.equalparts.cardbase.Cardbase; import eu.equalparts.cardbase.cards.Card; /** @@ -67,7 +63,7 @@ public class CardbaseTest { @Test public void fileCardbaseIsInitialised() throws Exception { - uut = new Cardbase(new File(getClass().getResource("/testbase.cb").getFile())); + uut = Cardbase.load(new File(getClass().getResource("/testbase.cb").getFile())); assertEquals("Card collection contains the wrong number of card entries.", 6, uut.getCards().size()); @@ -101,7 +97,7 @@ public class CardbaseTest { @Test public void loadFileIsNull() throws Exception { exception.expect(NullPointerException.class); - uut = new Cardbase(null); + uut = Cardbase.load(null); } @Test @@ -110,7 +106,7 @@ public class CardbaseTest { tempFolder.delete(); exception.expect(IOException.class); - uut = new Cardbase(notAFile); + uut = Cardbase.load(notAFile); } @Test @@ -121,7 +117,7 @@ public class CardbaseTest { } exception.expect(JsonMappingException.class); - uut = new Cardbase(wrongStructure); + uut = Cardbase.load(wrongStructure); } @Test @@ -131,7 +127,7 @@ public class CardbaseTest { writer.write("{\"field1\":\"content\",\"field2\":50,\"field3\":{\"subfield\":10},\"list\":[10,20,30]}"); } - uut = new Cardbase(unkownStructure); + uut = Cardbase.load(unkownStructure); assertEquals("Cardbase should contain 0 cards.", 0, uut.getCards().size()); } @@ -144,7 +140,7 @@ public class CardbaseTest { } exception.expect(JsonParseException.class); - uut = new Cardbase(notJson); + uut = Cardbase.load(notJson); } /*********************************************************************************** @@ -156,13 +152,13 @@ public class CardbaseTest { File testFile = tempFolder.newFile("saveTest.cb"); uut.writeCollection(testFile); - uut = new Cardbase(testFile); + uut = Cardbase.load(testFile); assertEquals("Cardbase should contain no cards.", 0, uut.getCards().size()); uut.addCard(testCard, testCount); uut.writeCollection(testFile); - uut = new Cardbase(testFile); + uut = Cardbase.load(testFile); assertEquals("Cardbase should contain 1 card.", 1, uut.getCards().size()); Card card = uut.getCard("M15", "281"); assertNotNull("Cardbase should contain a Shivan Dragon.", card); @@ -183,126 +179,6 @@ public class CardbaseTest { @Test public void saveFileIsNull() throws Exception { exception.expect(NullPointerException.class); - uut = new Cardbase(null); - } - - /*********************************************************************************** - * Adding card tests, happy path - ***********************************************************************************/ - @Test - public void newCardIsAdded() throws Exception { - uut.addCard(testCard, 1); - Card addedCard = uut.getCard("M15", "281"); - - assertNotNull("Card was not found in cardbase.", addedCard); - assertEquals(testCard, addedCard); - } - - @Test - public void existingCardIsIncremented() throws Exception { - uut.addCard(testCard, 2); - uut.addCard(testCard, 4); - - Card addedCard = uut.getCard("M15", "281"); - assertNotNull("Card was not found in cardbase.", addedCard); - assertEquals("Card count was not updated correctly.", 6, uut.getCount(addedCard)); - } - - /* - * Edge cases - */ - @Test - public void cardAddedIsNull() throws Exception { - exception.expect(NullPointerException.class); - uut.addCard(null, 0); - } - - /*********************************************************************************** - * Removing card tests, happy path - ***********************************************************************************/ - @Test - public void cardRemoveCountIsLessThanCardCount() throws Exception { - uut.addCard(testCard, 5); - - int removed = uut.removeCard(testCard, 3); - - Card removedCard = uut.getCard("M15", "281"); - assertNotNull("Card was not found in cardbase.", removedCard); - assertEquals("Card count was not updated correctly.", 2, uut.getCount(removedCard)); - assertEquals("Cardbase reports wrong removed count.", 3, removed); - } - - @Test - public void cardRemoveCountIsEqualToCardCount() throws Exception { - uut.addCard(testCard, 5); - - int removed = uut.removeCard(testCard, 5); - - Card removedCard = uut.getCard("M15", "281"); - assertNull("Card was not removed from cardbase.", removedCard); - assertEquals("Cardbase reports wrong removed count.", 5, removed); - } - - @Test - public void cardRemoveCountIsGreaterThanCardCount() throws Exception { - uut.addCard(testCard, 3); - int removed = uut.removeCard(testCard, 5); - - Card removedCard = uut.getCard("M15", "281"); - assertNull("Card was not removed from cardbase.", removedCard); - assertEquals("Cardbase reports wrong removed count.", 3, removed); - } - - /* - * Edge cases - */ - @Test - public void removedCardIsNull() throws Exception { - exception.expect(NullPointerException.class); - uut.removeCard(null, 0); - } - - @Test - public void removedCardIsNotInCardbase() throws Exception { - int removed = uut.removeCard(testCard, 1); - - assertEquals("Removed count should be 0.", 0, removed); - } - - /*********************************************************************************** - * Card getter tests, happy path - ***********************************************************************************/ - @Test - public void correctCardIsReturnedByGetter() throws Exception { - uut.addCard(testCard, 1); - - Card card = uut.getCard("M15", "281"); - - for (Field field : Card.class.getFields()) { - assertEquals("Field " + field.getName(), field.get(testCard), field.get(card)); - } - } - - @Test - public void correctCardCollectionIsReturnedByGetter() throws Exception { - uut = new Cardbase(new File(getClass().getResource("/testbase.cb").getFile())); - ObjectMapper mapper = new ObjectMapper(); - JsonNode rawFile = mapper.readTree(getClass().getResourceAsStream("/testbase.cb")); - Map<Integer, Card> cards = rawFile.get("cards").traverse(mapper).readValueAs(new TypeReference<Map<Integer, Card>>() {}); - - assertTrue("Not all cards were returned by the getter.", uut.getCards().containsAll(cards.values())); - } - - /* - * Edge cases - */ - @Test - public void getCardIsNotInCardbase() throws Exception { - assertNull("Method should have returned null", uut.getCard("M15", "281")); - } - - @Test - public void cardCollectionWhenCardbaseIsEmpty() throws Exception { - assertEquals("Returned collection size should have been 0.", 0, uut.getCards().size()); + uut = Cardbase.load(null); } } |