import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; /** * Project 07 tester. * * javac *.java * java Project07Tester * * Checks the two timing methods you write in WordCounter: timeLookups and * timeRemoveAll. It runs every check and keeps going after a failure, then * prints a summary. A method that still has its "not written yet" line is * reported as SKIP. * * To see exactly which map methods your code calls, the tester puts a "spy" * map inside your WordCounter: it passes every call on to your real BSTMap or * HashMap, and counts the calls. It reads the field wordCounts in * WordCounter.java, so keep that name. */ public class Project07Tester { private static int passed = 0, failed = 0, skipped = 0; private static void check(boolean condition, String message) { if (condition) { passed++; System.out.println(" [PASS] " + message); } else { fail(message); } } private static boolean checkEquals(Object shouldBe, Object yours, String message) { boolean same = shouldBe == null ? yours == null : shouldBe.equals(yours); if (same) { check(true, message); } else { fail(message + "\n should be: " + shouldBe + "\n yours: " + yours); } return same; } private static void fail(String message) { failed++; System.out.println(" [FAIL] " + message); } private static void skip(String message) { skipped++; System.out.println(" [SKIP] " + message); } private static void hint(String text) { System.out.println(" Hint: " + text); } private static final int SECONDS = 20; /** Runs one section; a missing method is a SKIP, a crash or a hang is a FAIL. */ private static void runSection(Runnable section) { final Throwable[] thrown = new Throwable[1]; Thread worker = new Thread(null, () -> { try { section.run(); } catch (Throwable e) { thrown[0] = e; } }, "section", 1 << 24); worker.setDaemon(true); worker.start(); try { worker.join(SECONDS * 1000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } Throwable e = thrown[0]; while (e instanceof InvocationTargetException) { e = e.getCause(); } if (worker.isAlive()) { fail("this section did not finish in " + SECONDS + " seconds. Look for an infinite loop."); } else if (e instanceof UnsupportedOperationException) { skip(e.getMessage() + "; the rest of this section waits until you write it"); } else if (e instanceof NullPointerException) { fail("this section stopped because your code threw " + e); hint("does your method use the field wordCounts, the map WordCounter already has?"); } else if (e != null) { fail("this section stopped early because your code threw " + e); } } private static void section(String title, String what) { System.out.println(); System.out.println("== " + title + " =="); System.out.println(" " + what); } // ------------------------------------------------------------------ // The spy map: passes every call on to the real map, and counts them // ------------------------------------------------------------------ static class SpyMap implements MapSet { final MapSet real; int gets, puts, removes, keySets, others; ArrayList removed = new ArrayList(); SpyMap(MapSet real) { this.real = real; } void reset() { gets = 0; puts = 0; removes = 0; keySets = 0; others = 0; removed.clear(); } public V put(K key, V value) { puts++; return real.put(key, value); } public V get(K key) { gets++; return real.get(key); } public boolean containsKey(K key) { others++; return real.containsKey(key); } public V remove(K key) { removes++; removed.add(key); return real.remove(key); } public int size() { return real.size(); } public void clear() { others++; real.clear(); } public ArrayList keySet() { keySets++; return real.keySet(); } public ArrayList values() { others++; return real.values(); } public int maxDepth() { return real.maxDepth(); } } /** Puts a spy around the WordCounter's own map, and returns the spy. */ @SuppressWarnings("unchecked") private static SpyMap spyOn(WordCounter counter) { try { Field f = WordCounter.class.getDeclaredField("wordCounts"); f.setAccessible(true); SpyMap spy = new SpyMap((MapSet) f.get(counter)); f.set(counter, spy); return spy; } catch (ReflectiveOperationException e) { throw new IllegalStateException("can't find the field wordCounts in WordCounter.java"); } } /** A WordCounter with a spy map, already holding the words of tiny.txt. */ private static SpyMap built(WordCounter counter, ArrayList words) { SpyMap spy = spyOn(counter); counter.buildMap(words); spy.reset(); return spy; } private static String name(String structure) { return structure.equals("BST") ? "BSTMap" : "HashMap"; } // ------------------------------------------------------------------ // The checks // ------------------------------------------------------------------ private static ArrayList tiny; private static void provided() { section("Setup: your maps in the provided WordCounter", "Counts tiny.txt with each of your maps. If this fails, finish Lab 07 (and Project 06's BSTMap) first."); runSection(() -> { WordCounter reader = new WordCounter("HashMap"); tiny = reader.readWords("tiny.txt"); if (!checkEquals(60, tiny.size(), "tiny.txt has 60 words")) { hint("tiny.txt must be in this folder, the same file as in Labs 06 and 07."); return; } for (String structure : new String[] {"BST", "HashMap"}) { WordCounter counter = new WordCounter(structure); counter.buildMap(tiny); checkEquals(20, counter.uniqueWordCount(), name(structure) + ": tiny.txt has 20 different words"); checkEquals(2, counter.getCount("times"), name(structure) + ": \"times\" appears 2 times"); } }); } private static void lookups() { section("Task 2: timeLookups", "Builds the map of tiny.txt, then calls your timeLookups with the same 60 words."); runSection(() -> { if (tiny == null) { fail("tiny.txt could not be read: see the Setup section"); return; } for (String structure : new String[] {"BST", "HashMap"}) { WordCounter counter = new WordCounter(structure); SpyMap spy = built(counter, tiny); double time = counter.timeLookups(tiny); String m = name(structure) + ": "; if (!checkEquals(60, spy.gets, m + "timeLookups calls get once for each of the 60 words")) { if (spy.gets == 20) { hint("look up every word of the list, repeats included, not each different word."); } } if (!checkEquals(0, spy.puts, m + "timeLookups never calls put: looking up doesn't change the map")) { hint("did you call buildMap, or copy its put lines? timeLookups only calls get."); } checkEquals(0, spy.removes, m + "timeLookups never calls remove"); checkEquals(20, counter.uniqueWordCount(), m + "after timeLookups, the map still has 20 different words"); checkEquals(60, counter.totalWordCount(), m + "after timeLookups, the total word count is still 60"); check(time >= 0 && !Double.isNaN(time), m + "timeLookups returns a time of 0 ms or more (yours: " + time + ")"); } // Is the time in milliseconds? Time a long list and compare with the tester's own clock. ArrayList many = new ArrayList(); for (int i = 0; i < 20000; i++) { many.addAll(tiny); } WordCounter counter = new WordCounter("HashMap"); counter.buildMap(tiny); long start = System.nanoTime(); double yours = counter.timeLookups(many); double clock = (System.nanoTime() - start) / 1e6; boolean ok = yours <= clock + 1 && yours >= clock / 10 - 1; check(ok, String.format("timeLookups with 1,200,000 words: your time (%.1f ms) agrees with the tester's clock (%.1f ms)", yours, clock)); if (!ok) { hint("return the time in MILLISECONDS, as buildMap does: (System.nanoTime() - start) / 1e6." + "\n Record the start just before the loop, and the end just after it."); } }); } private static void removeAll() { section("Task 2: timeRemoveAll", "Builds the map of tiny.txt, then calls your timeRemoveAll."); runSection(() -> { if (tiny == null) { fail("tiny.txt could not be read: see the Setup section"); return; } for (String structure : new String[] {"BST", "HashMap"}) { WordCounter counter = new WordCounter(structure); SpyMap spy = built(counter, tiny); ArrayList keys = spy.real.keySet(); // the order timeRemoveAll should follow double time = counter.timeRemoveAll(); String m = name(structure) + ": "; checkEquals(1, spy.keySets, m + "timeRemoveAll calls keySet once, to get the keys to remove"); if (!checkEquals(20, spy.removes, m + "timeRemoveAll calls remove once for each of the 20 different words")) { if (spy.removes == 60) { hint("remove each KEY once: the keys come from keySet, not from the text's words."); } } checkEquals(keys, spy.removed, m + "the keys are removed in the order of keySet"); checkEquals(0, spy.puts, m + "timeRemoveAll never calls put"); checkEquals(0, counter.uniqueWordCount(), m + "after timeRemoveAll, the map is empty: 0 different words"); if (!checkEquals(0, counter.totalWordCount(), m + "after timeRemoveAll, the total word count is 0")) { hint("TODO 5: set totalWords to 0, as clearMap does."); } check(time >= 0 && !Double.isNaN(time), m + "timeRemoveAll returns a time of 0 ms or more (yours: " + time + ")"); // The map can be used again after removing everything. counter.buildMap(tiny); checkEquals(20, counter.uniqueWordCount(), m + "building tiny.txt again afterwards gives 20 different words again"); } if (structureCapacityShrinks()) { check(true, "HashMap: removing every key shrinks the table back to its starting 16 bins"); } else { fail("HashMap: removing every key should shrink the table back to its starting 16 bins"); hint("this is your HashMap's remove (Lab 07, Task 7): Lab07Tester's Task 7 section checks it."); } }); } /** Builds a HashMap of 1,000 words through WordCounter, removes them all, and checks the capacity. */ private static boolean structureCapacityShrinks() { WordCounter counter = new WordCounter("HashMap"); SpyMap spy = spyOn(counter); ArrayList words = new ArrayList(); for (int i = 0; i < 1000; i++) { words.add("word" + i); } Collections.shuffle(words); counter.buildMap(words); counter.timeRemoveAll(); return ((HashMap) spy.real).capacity() == 16; } public static void main(String[] args) { System.out.println("Project 07 Tester"); provided(); lookups(); removeAll(); System.out.println(); System.out.println("Summary: " + passed + " passed, " + failed + " failed, " + skipped + " skipped."); if (failed == 0 && skipped == 0) { System.out.println("All checks passed."); } else if (failed == 0) { System.out.println("No failures so far. SKIP means a method is not written yet."); } System.exit(0); } }