import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework; import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework.Test; public class Tests { private static final String TESTAT_NAME = "Testat 2A"; // Aufgabe 1 - Fridge tests - 50 Punkte @Test(name = "Aufgabe 1 - Fridge - getWeight - 10 Punkte") public void testFridgeWeightful() { int points = 10; if (!implementsInterface(Fridge.class, Weightful.class)) { points -= 5; TracingFramework .printError("Fridge should implement interface Weightful, but does not. Deducting 5 points."); } Method method = findMethod(Fridge.class, "getWeight", double.class); if (method == null) { points -= 5; TracingFramework.printError( "Fridge should implement method getWeight with return type double, but does not. Deducting 5 points."); } else { Fridge fridge = new Fridge(10, 500); setItems(fridge, new FridgeItem[] { new Cheese(100, "A", "B"), new Cheese(100, "C", "D"), new Cheese(100, "E", "F") }); try { double weight = (double) method.invoke(fridge); if (weight != 300.0) { points -= 3; TracingFramework.printError( "A fridge with 3 x 100 g should have a weight of 300 g but was " + weight); } } catch (IllegalAccessException | InvocationTargetException e) { points -= 3; TracingFramework.printError("Error invoking getWeight method: " + e.getMessage()); } } addPoints(points); } @Test(name = "Aufgabe 1 - Fridge - addItem - 15 Punkte") public void testFridgeAddItem() { int points = 15; // initialize fridge and items Fridge fridge = new Fridge(10, 10); Cheese a = new Cheese(1, "A", "B"); FridgeItem[] items = new FridgeItem[] { a, new Cheese(1, "B", "C"), new Cheese(1, "C", "D") }; setItems(fridge, items); // test for duplicates // should return false and not add the item boolean duplicates = fridge.addItem(a); if (getItems(fridge).length == 3) { if (duplicates) { points -= 3; TracingFramework.printError("Note: The fridge should return false for duplicates."); } } else { points -= 6; TracingFramework.printError("The fridge does not check for duplicates."); } // test for weight exceeding // should return false and not add the item setItems(fridge, new FridgeItem[] { a, new Cheese(1, "B", "C"), new Cheese(1, "C", "D") }); boolean weight = fridge.addItem(new Cheese(8, "D", "E")); if (getItems(fridge).length == 3) { if (weight) { points -= 3; TracingFramework.printError("Note: The fridge should return false for exceeded weight."); } } else { points -= 6; TracingFramework.printError("The fridge does not check the weight."); } // max weight not actually exceeded setItems(fridge, new FridgeItem[] { a, new Cheese(1, "B", "C"), new Cheese(1, "C", "D") }); fridge.addItem(new Cheese(7, "G", "H")); if (getItems(fridge).length == 3) { points -= 3; TracingFramework .printError("Note: The fridge doesn't add an item when it hits exactly the maximum weight."); } addPoints(points); } private static TraceableFridge createTraceableFridge() { TraceableFridge fridge = new TraceableFridge(10, 10); setItems(fridge, new FridgeItem[] { new Cheese(1, "A", "B"), new Cheese(1, "B", "C"), new Cheese(1, "C", "D"), new Cheese(1, "A", "B"), new Cheese(1, "B", "C"), new Cheese(1, "C", "D"), new Cheese(1, "A", "B"), new Cheese(1, "B", "C"), new Cheese(1, "C", "D") }); return fridge; } private static long countRecursionSteps(TraceableFridge fridge) { List stackTrace = fridge.getStackTrace(); return stackTrace.stream() .filter(element -> element.getClassName().equals(Fridge.class.getName()) && element.getMethodName().equals("indexOf")) .count(); } @Test(name = "Aufgabe 1 - Fridge - indexOf - not existing item - 10 Punkte") public void testFridgeIndexOfNotExisting() { int points = 10; TraceableFridge fridge = createTraceableFridge(); // test for not existing item int index = fridge.indexOf("D", 0); long recursionSteps = countRecursionSteps(fridge); if (recursionSteps == 0) { points -= 10; TracingFramework.printError("The fridge should use recursion to find the index of an item."); } else if (index != -1) { points -= 10; TracingFramework.printError("The fridge should return -1 for not existing items."); } addPoints(points); } @Test(name = "Aufgabe 1 - Fridge - indexOf - existing item - 5 Punkte") public void testFridgeIndexOfExisting() { int points = 5; TraceableFridge fridge = createTraceableFridge(); // test for existing item int index = fridge.indexOf("C", 0); long recursionSteps = countRecursionSteps(fridge); if (recursionSteps == 0) { points -= 5; TracingFramework .printError("The fridge should use recursion to find the index of an item. Deducting 10 points."); } else if (index != 2) { points -= 5; TracingFramework.printError( "The fridge should return the index of the first occurrence of an item. Deducting 10 points."); } addPoints(points); } @Test(name = "Aufgabe 1 - Fridge - indexOf - shifted start - 10 Punkte") public void testFridgeIndexOfShiftedStart() { int points = 10; TraceableFridge fridge = createTraceableFridge(); // test for shifted start int index = fridge.indexOf("A", 1); long recursionSteps = countRecursionSteps(fridge); if (recursionSteps == 0) { points -= 10; TracingFramework .printError("The fridge should use recursion to find the index of an item. Deducting 10 points."); } else if (index != 3) { points -= 10; TracingFramework.printError( "The fridge should return the index of the first occurrence of an item after start index. Deducting 10 points."); } addPoints(points); } // Aufgabe 2 - Deque tests - 50 Punkte @Test(name = "Aufgabe 2 - Deque - addLast - valid values - 10 Punkte") public void testDequeAddLast() { int points = 10; Deque deque = new Deque(); String[] values = { "A", "B", "C", "D", "E" }; for (String value : values) { deque.addLast(value); String lastValue = peekLast(deque); if (!value.equals(lastValue)) { String lastValueFromFront = peekLastFromFront(deque); if (value.equals(lastValueFromFront)) { points -= 1; TracingFramework.printError( "The pointers inside the deque are not set correctly, but the last value is still added properly. Deducting 1 point."); } else { points -= 2; TracingFramework.printError( "The last value is not added properly. Expected: " + value + ", but got: " + lastValue); } } } addPoints(points); } @Test(name = "Aufgabe 2 - Deque - addLast - null value - 3 Punkte") public void testDequeAddLastNull() { int points = 3; Deque deque = new Deque(); deque.addLast(null); if (getFront(deque) != null || getBack(deque) != null) { points -= 3; TracingFramework.printError("The deque should not add null values. Deducting 3 points."); } addPoints(points); } @Test(name = "Aufgabe 2 - Deque - addLast - empty value - 2 Punkte") public void testDequeAddLastEmpty() { int points = 2; Deque deque = new Deque(); deque.addLast(""); if (getFront(deque) != null || getBack(deque) != null) { points -= 2; TracingFramework.printError("The deque should not add empty values. Deducting 2 points."); } addPoints(points); } @Test(name = "Aufgabe 2 - Deque - peekFirst - filled deque - 10 Punkte") public void testDequePeekFirstFilled() { int points = 10; Deque deque = buildDeque("Das", "kann", "man", "nicht", "raten"); String beforeStudentPeek = peekFirst(deque); String firstValue = deque.peekFirst(); if (!"Das".equals(firstValue)) { points -= 5; TracingFramework .printError("The first value should be 'Das', but got: " + firstValue + ". Deducting 5 points."); } String afterStudentPeek = peekFirst(deque); if (!beforeStudentPeek.equals(afterStudentPeek)) { points -= 5; TracingFramework.printError("The peekFirst method should not change the deque. Deducting 5 points."); } addPoints(points); } @Test(name = "Aufgabe 2 - Deque - peekFirst - empty deque - 5 Punkte") public void testDequePeekFirstEmpty() { int points = 5; Deque deque = buildDeque("A", "B", "C", "D", "E"); if (hasInvalidFirstPeeking()) { points -= 5; TracingFramework.printError( "The peekFirst method should not return null for a non-empty deque, assuming it always returns null. Deducting 5 points."); } else { // empty the deque pollFirst(deque); pollFirst(deque); pollFirst(deque); pollFirst(deque); pollFirst(deque); String value = deque.peekFirst(); if (value != null) { points -= 5; TracingFramework .printError("The peekFirst method should return null for an empty deque. Deducting 5 points."); } } addPoints(points); } private boolean hasInvalidFirstPeeking() { Deque deque = buildDeque("A", "B", "C", "D", "E"); String value = deque.peekFirst(); // if value is null, we assume that the return value of peekFirst is always null // without checking would always return null, and therefore granting full points return value == null; } @Test(name = "Aufgabe 2 - Deque - pollLast - filled deque - 10 Punkte") public void testDequePollLastFilled() { int points = 10; Deque deque = buildDeque("Das", "kann", "man", "nicht", "raten"); String value = deque.pollLast(); if (!"raten".equals(value)) { points -= 5; TracingFramework.printError( "The pollLast method should return 'raten', but got: " + value + ". Deducting 5 points."); } value = deque.pollLast(); if (!"nicht".equals(value)) { points -= 5; TracingFramework.printError("The pollLast method should return 'nicht', but got: " + value + ". Polling should remove the last item. Deducting 5 points."); } addPoints(points); } @Test(name = "Aufgabe 2 - Deque - pollLast - empty deque - 5 Punkte") public void testDequePollLastEmpty() { int points = 5; Deque deque = buildDeque("A", "B", "C", "D", "E"); if (hasInvalidLastPolling()) { points -= 5; TracingFramework.printError( "The pollLast method returns null for an non empty deque, assuming it always returns null. Deducting 5 points."); } else { // empty the deque pollFirst(deque); pollFirst(deque); pollFirst(deque); pollFirst(deque); pollFirst(deque); String value = deque.pollLast(); if (value != null) { points -= 5; TracingFramework .printError("The pollLast method should return null for an empty deque. Deducting 5 points."); } } addPoints(points); } public boolean hasInvalidLastPolling() { Deque deque = buildDeque("A", "B", "C", "D", "E"); String value = deque.pollLast(); // if value is null, we assume that the return value of pollLast is always null // without checking would always return null, and therefore granting full points return value == null; } @Test(name = "Aufgabe 2 - Deque - size - filled deque - 3 Punkte") public void testDequeSizeFilled() { int points = 3; if (hasIllegalDequeFields()) { points = 0; TracingFramework.printError( "Fields of Deque class were modified illegally. Cannot determine if field for size was added. Deducting all points for size tests."); } else { Deque deque = buildDeque("A", "B", "C", "D", "E"); int size = deque.size(); if (size != 5) { points -= 3; TracingFramework .printError("The size method should return 5, but got: " + size + ". Deducting 3 points."); } } addPoints(points); } @Test(name = "Aufgabe 2 - Deque - size - empty deque - 2 Punkte") public void testDequeSizeEmpty() { int points = 2; if (hasIllegalDequeFields()) { points = 0; TracingFramework.printError( "Fields of Deque class were modified illegally. Cannot determine if field for size was added. Deducting all points for size tests."); } else { Deque deque = buildDeque("A", "B", "C", "D", "E"); int size = deque.size(); if (size == 0) { points -= 2; TracingFramework .printError("The size method should not return 0 for a non-empty deque, but got: " + size + ". Assuming it always returns 0. Deducting 2 points."); } else { // empty the deque pollFirst(deque); pollFirst(deque); pollFirst(deque); pollFirst(deque); pollFirst(deque); size = deque.size(); if (size != 0) { points -= 2; TracingFramework.printError("The size method should return 0 for an empty deque, but got: " + size + ". Deducting 2 points."); } } } addPoints(points); } /** * Finds a method with the given name, return type, and parameter types in the * specified class or its superclasses. * * @param clazz The class to search in. * @param methodName The name of the method to find. * @param returnType The return type of the method. * @param parameterTypes The parameter types of the method. * @return The method if found, null otherwise. */ public static Method findMethod(Class clazz, String methodName, Class returnType, Class... parameterTypes) { try { Method method = clazz.getDeclaredMethod(methodName, parameterTypes); if (method.getReturnType().equals(returnType)) { return method; } } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } /** * Checks if a class implements a given interface. * * @param clazz The class to check. * @param interfaceClass The interface to check for. * @return True if the class implements the interface, false otherwise. */ public static boolean implementsInterface(Class clazz, Class interfaceClass) { Class[] interfaces = clazz.getInterfaces(); return Arrays.stream(interfaces).anyMatch(interfaceClass::equals); } /** * START: Fridge helper methods */ /** * Sets the fridge items. * * @param fridge The fridge. * @param items The items. */ private static void setItems(Fridge fridge, FridgeItem[] items) { try { Field f = Fridge.class.getDeclaredField("items"); f.setAccessible(true); f.set(fridge, items); } catch (Exception e) { TracingFramework.printError("Cannot set fridge items (" + e + ")."); } } /** * Returns the fridge items via reflection. * * @param fridge The fridge. * @return The fridge's items. */ private FridgeItem[] getItems(Fridge fridge) { try { Field f = Fridge.class.getDeclaredField("items"); f.setAccessible(true); return (FridgeItem[]) f.get(fridge); } catch (Exception e) { TracingFramework.printError("Cannot get fridge items (" + e + ")."); return new FridgeItem[0]; } } /** * END: Fridge helper methods */ /** * START: Deque helper methods */ /** * Checks if the Deque class has illegal fields. * The Deque class should only have two fields: 'front' and 'back', both of type * Item. * * Check to be used in tests to ensure no extra fields are added. * * Size is supposed to be determined by iterating through the items, not by a * field. Because given methods don't make use of such a field. * * @return True if illegal fields are found, false otherwise. */ public boolean hasIllegalDequeFields() { Field[] fields = Deque.class.getDeclaredFields(); if (fields.length != 2) { TracingFramework.printError("Deque class should have exactly 2 fields. But has: " + fields.length); return true; } for (Field field : fields) { String fieldName = field.getName(); if (fieldName.equals("front") || fieldName.equals("back")) { if (!field.getType().equals(Item.class)) { TracingFramework.printError("Field " + fieldName + " should be of type Item."); return true; } } else { TracingFramework.printError("Deque class has an illegal field: " + fieldName); return true; } } return false; } /** * Builds a deque from the given values. * * @param values The values to add. * @return The built deque. */ public Deque buildDeque(String... values) { Deque deque = new Deque(); for (String value : values) { try { // Create new Item Item item = new Item(value); // If deque is empty, set both front and back to this item if (peekFirst(deque) == null) { setFront(deque, item); setBack(deque, item); } else { // Add to the end (back) of the deque Item currentBack = getBack(deque); // Set the links setNext(currentBack, item); setPrev(item, currentBack); // Update back pointer setBack(deque, item); } } catch (Exception e) { return null; } } return deque; } /** * Removes and returns the first element of the deque. * * @param deque The deque to poll from. * @return The value of the first element, or null if the deque is empty. */ private String pollFirst(Deque deque) { Item first = getFront(deque); if (first == null) { return null; } String value = first.getValue(); if (first.getNext() != null) { setFront(deque, first.getNext()); first.getNext().setPrev(null); } else { setFront(deque, null); setBack(deque, null); } return value; } /** * Peeks at the first element of the deque without removing it. * * @param deque The deque to peek from. * @return The value of the first element, or null if the deque is empty. */ private String peekFirst(Deque deque) { Item first = getFront(deque); return first != null ? first.getValue() : null; } /** * Peeks at the last element of the deque without removing it. * * @param deque The deque to peek from. * @return The value of the last element, or null if the deque is empty. */ private String peekLast(Deque deque) { Item last = getBack(deque); return last != null ? last.getValue() : null; } /** * Peeks at the last element of the deque by traversing from the front. * * @param deque The deque to peek from. * @return The value of the last element, or null if the deque is empty. */ private String peekLastFromFront(Deque deque) { Item last = getLastFromFront(deque); return last != null ? last.getValue() : null; } /** * Gets the last item by traversing from the front. * * @param deque The deque to get the last item from. * @return The last item, or null if the deque is empty. */ private Item getLastFromFront(Deque deque) { Item current = getFront(deque); while (current != null && current.getNext() != null) { current = current.getNext(); } return current; } /** * Gets the front item of the deque. * * @param deque The deque to get the front item from. * @return The front item, or null if the deque is empty. */ private Item getFront(Deque deque) { try { Field field = Deque.class.getDeclaredField("front"); field.setAccessible(true); return (Item) field.get(deque); } catch (IllegalAccessException | NoSuchFieldException | SecurityException e) { throw new RuntimeException("Error accessing getFront method", e); } } /** * Gets the back item of the deque. * * @param deque The deque to get the back item from. * @return The back item, or null if the deque is empty. */ private Item getBack(Deque deque) { try { Field field = Deque.class.getDeclaredField("back"); field.setAccessible(true); return (Item) field.get(deque); } catch (IllegalAccessException | NoSuchFieldException | SecurityException e) { throw new RuntimeException("Error accessing getBack method", e); } } /** * Sets the front item of the deque. * * @param deque The deque to set the front item for. * @param front The front item to set. */ private void setFront(Deque deque, Item front) { try { Field field = Deque.class.getDeclaredField("front"); field.setAccessible(true); field.set(deque, front); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException("Error setting front item", e); } } /** * Sets the back item of the deque. * * @param deque The deque to set the back item for. * @param back The back item to set. */ private void setBack(Deque deque, Item back) { try { Field field = Deque.class.getDeclaredField("back"); field.setAccessible(true); field.set(deque, back); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException("Error setting back item", e); } } /** * Sets the next item for the given item. * * @param item The item to set the next item for. * @param next The next item to set. */ private void setNext(Item item, Item next) { try { Field field = Item.class.getDeclaredField("next"); field.setAccessible(true); field.set(item, next); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException("Error setting next item", e); } } /** * Sets the previous item for the given item. * * @param item The item to set the previous item for. * @param prev The previous item to set. */ private void setPrev(Item item, Item prev) { try { Field field = Item.class.getDeclaredField("prev"); field.setAccessible(true); field.set(item, prev); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException("Error setting previous item", e); } } /** * END: Deque helper methods */ /** * The points of each test case. */ private List testPoints = new ArrayList<>(); /** * This method will be called by jack after all test have been executed to get * the resulting points. * * @return The points resulting from the test. */ public int getResult() { int sum = 0; for (Integer p : testPoints) { sum += p; } return sum; } /** * Adds points for a test case. This class assumes that the method is called * exactly once per test case. * * @param value The points to add. */ protected void addPoints(int value) { testPoints.add(value); } /** * A utility method to execute any test driver class extending abstract test * locally without going through Jack. * * @param test The test driver to execute. * @throws Exception Thrown if something fails. */ public static void runAll() throws Exception { Class clazz = Tests.class; Tests test = new Tests(); System.out.println(String.format("Running tests for: %s", TESTAT_NAME)); System.out.println(); for (Method method : clazz.getMethods()) { if (method.isAnnotationPresent(Test.class)) { System.out.println(String.format("Currently testing: %s", method.getName())); int size = test.testPoints.size(); try { method.invoke(test); if (test.testPoints.size() != size + 1) { System.err.println("ERROR: Test yields no or multiple results. Erroneous test."); } else { System.out.println( String.format("PASS: Test passed with %d points!", test.testPoints.get(test.testPoints.size() - 1))); } } catch (Exception e) { System.err.println(String.format("ERROR: Test failed with exception: %s", e.getMessage())); e.printStackTrace(); } System.out.println(); } } System.out.println(); System.out.println(String.format("Total points: %d", test.getResult())); } public static void main(String[] args) { try { runAll(); } catch (Exception e) { e.printStackTrace(); } } }