import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; 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 { @Test(name = "Aufgabe 1 - Tree - traverse - 20 Punkte") public void testTreeTraverse() { Method method = findMethod(Tree.class, "traverse", TreeVisitor.class) .orElseThrow(() -> new RuntimeException( "Method Tree.traverse(TreeVisitor) not found. Class was mutated illegally.")); int points = 20; double[] values = new double[] { 3, 1, 5, 0, 2, 4, 6 }; Tree tree = new Tree(); setRoot(tree, buildTree(values)); double[] expect = new double[] { 3, 1, 0, 2, 5, 4, 6 }; TreeVisitor visitor = new TreeVisitor(); if (!safeExecuteVoidMethod(method, tree, visitor)) { throw new RuntimeException("Method Tree.traverse(TreeVisitor) did not execute successfully."); } double[] actual = visitor.toArray(); if (!Arrays.equals(actual, expect)) { double[] expectSort = expect.clone(); double[] actualSort = actual.clone(); Arrays.sort(expectSort); Arrays.sort(actualSort); if (Arrays.equals(expectSort, actualSort)) { points -= 10; TracingFramework.printError( "Traversal " + Arrays.toString(actual) + " is not pre-order but complete. Deducting 10 points."); } else { points -= 20; TracingFramework.printError("Traversal " + Arrays.toString(actual) + " is incomplete (no points)."); } } addPoints(points); } @Test(name = "Aufgabe 1 - Tree - count existing once - 10 Punkte") public void testTreeCountExisitingOnce() { Method method = findMethod(Tree.class, "count", double.class) .orElseThrow(() -> new RuntimeException( "Method Tree.count(double) not found. Class was mutated illegally.")); int points = 10; // non-sorted tree double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 }; Tree tree = new Tree(); setRoot(tree, buildTree(values)); // 3 should be found once Optional count = executeMethod(method, tree, Integer.class, 3); if (count.isEmpty()) { points -= 10; TracingFramework.printError("Execution of Tree.count(3) led to an execution. Deducting 10 points."); } else if (count.get() != 1) { points -= 10; TracingFramework.printError("Tree.count(3) should return 1 , but was " + count.get()); } addPoints(points); } @Test(name = "Aufgabe 1 - Tree - count non exisiting - 10 Punkte") public void testTreeCountNonExisiting() { Method method = findMethod(Tree.class, "count", double.class) .orElseThrow(() -> new RuntimeException( "Method Tree.count(double) not found. Class was mutated illegally.")); int points = 10; // non-sorted tree double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 }; Tree tree = new Tree(); setRoot(tree, buildTree(values)); Optional count = executeMethod(method, tree, Integer.class, 7); if (count.isEmpty()) { points -= 10; TracingFramework.printError("Execution of Tree.count(7) led to an execution. Deducting 10 points."); } else if (count.get() != 0) { points -= 10; TracingFramework.printError("Tree.count(7) should return 0 , but was " + count.get()); } addPoints(points); } @Test(name = "Aufgabe 1 - Tree - count, should find once - 10 Punkte") public void testTreeCountShouldFindOnce() { Method method = findMethod(Tree.class, "count", double.class) .orElseThrow(() -> new RuntimeException( "Method Tree.count(double) not found. Class was mutated illegally.")); int points = 10; // non-sorted tree double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 }; Tree tree = new Tree(); setRoot(tree, buildTree(values)); Optional count = executeMethod(method, tree, Integer.class, 1); if (count.isEmpty()) { points -= 10; TracingFramework.printError("Execution of Tree.count(1) led to an execution. Deducting 10 points."); } else if (count.get() == 2) { // correct, to nothing } else if (count.get() == 3) { points -= 10; TracingFramework .printError("Tree.count(1) should return 2 with efficient implementation, but was " + count); } else { points -= 10; TracingFramework.printError("Tree.count(1) should return 2 , but was " + count.get()); } addPoints(points); } @Test(name = "Aufgabe 1 - Tree - height - 10 Punkte") public void testTreeHeight() { Method method = findMethod(Tree.class, "height") .orElseThrow(() -> new RuntimeException( "Method Tree.height() not found. Class was mutated illegally.")); int points = 10; // non-sorted tree double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 }; Tree tree = new Tree(); setRoot(tree, buildTree(values)); Optional height = executeMethod(method, tree, Integer.class); if (height.isEmpty()) { points -= 10; TracingFramework.printError("Execution of Tree.height() led to an execution. Deducting 10 points."); } else if (height.get() != 3) { points -= 10; TracingFramework.printError("Tree.height() should return 3 , but was " + height.get()); } addPoints(points); } @Test(name = "Aufgabe 2 - IO - write - 10 Punkte") public void testIOWrite() { Method method = findMethod(StringListSerializer.class, "write", Path.class, List.class) .orElseThrow(() -> new RuntimeException( "Method StringListSerializer.write(Path, List) not found. Class was mutated illegally.")); StringListSerializer serializer = new StringListSerializer(); Path path = InMemoryPathFactory.createPath("/test/write.txt"); List data = Arrays.asList("Hello", "World", "This is a test"); if (!safeExecuteVoidMethod(method, serializer, path, data)) { throw new RuntimeException("Failed to execute StringListSerializer.write(Path, List) method."); } int points = 10; try { List content = Files.readAllLines(path); if (!content.equals(data)) { points -= 10; TracingFramework.printError("Written content does not match original content. Deducting 10 points."); } } catch (Exception e) { points -= 10; TracingFramework.printError("Failed to read written content: " + e.getMessage() + ". Deducting 10 points."); } addPoints(points); } @Test(name = "Aufgabe 2 - IO - read - errorless- 5 Punkte") public void testIOReadErrorless() { int points = 5; StringListSerializer serializer = new StringListSerializer(); Path path = InMemoryPathFactory.createPath("/test/read.txt"); List data = Arrays.asList("Hello", "World", "This is a test"); try { Files.write(path, data); } catch (IOException e) { points -= 5; e.printStackTrace(); TracingFramework.printError( "Failed to write test data: " + e.getMessage() + ". Erroneous test. Giving full points."); addPoints(points); return; } List readData = serializer.read(path); if (!data.equals(readData)) { points -= 5; TracingFramework.printError("Read content does not match original content. Deducting 5 points."); } addPoints(points); } @Test(name = "Aufgabe 2 - IO - read - forced IOException - 5 Punkte") public void testIOReadForcedIOException() { int points = 5; StringListSerializer serializer = new StringListSerializer(); Path path = InMemoryPathFactory.createPath("/test/forcedIOException.txt"); try { List readData = serializer.read(path); if (readData == null) { points -= 5; TracingFramework.printError( "Reading from /test/forcedIOException.txt path should return an empty list, but returned null. Deducting 5 points."); } else if (!readData.isEmpty()) { points -= 5; TracingFramework.printError( "Reading from /test/forcedIOException.txt path should return an empty list, but returned: " + readData + ". Deducting 5 points."); } } catch (Exception e) { if (e instanceof IOException) { points -= 5; TracingFramework.printError( "Reading from /test/forcedIOException.txt path should process IOException to empty list, but did not. Deducting 5 points."); } else { points -= 5; TracingFramework .printError("Reading from /test/forcedIOException.txt path throws an unexpected exception: " + e.getMessage()); } } addPoints(points); } @Test(name = "Aufgabe 3 - Deque - addFirst null - 3 Punkte") public void testDequeAddFirstNull() { Method method = findMethod(Deque.class, "addFirst", String.class) .orElseThrow(() -> new RuntimeException( "Method Deque.addFirst(String) not found. Class was mutated illegally.")); int points = 3; if (addFirstAlwaysException()) { points -= 3; TracingFramework.printError( "Deque.addFirst(\"A\"), Deque.addFirst(\"BCDEF\"), or Deque.addFirst(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 3 points."); } else { try { Deque deque = new Deque(); executeVoidMethod(method, deque, (Object) null); points -= 3; TracingFramework .printError("Deque.addFirst(null) should throw an exception, but did not. Deducting 3 points."); } catch (Exception e) { if (!(e instanceof IllegalArgumentException)) { points -= 1; TracingFramework .printError("Deque.addFirst(null) should throw an IllegalArgumentException, but threw: " + e.getClass().getName() + ". Deducting 1 point."); } if (e.getMessage() == null || !e.getMessage().equals("Value cannot be null")) { points -= 1; TracingFramework.printError( "Deque.addFirst(null) should throw an IllegalArgumentException with message 'Value cannot be null', but got: " + e.getMessage() + ". Deducting 1 point."); } } } addPoints(points); } @Test(name = "Aufgabe 3 - Deque - addFirst empty - 3 Punkte") public void testDequeAddFirstEmpty() { Method method = findMethod(Deque.class, "addFirst", String.class) .orElseThrow(() -> new RuntimeException( "Method Deque.addFirst(String) not found. Class was mutated illegally.")); int points = 3; if (addFirstAlwaysException()) { points -= 3; TracingFramework.printError( "Deque.addFirst(\"A\"), Deque.addFirst(\"BCDEF\"), or Deque.addFirst(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 3 points."); } else { try { Deque deque = new Deque(); executeVoidMethod(method, deque, ""); points -= 3; TracingFramework .printError("Deque.addFirst(\"\") should throw an exception, but did not. Deducting 3 points."); } catch (Exception e) { if (!(e instanceof IllegalArgumentException)) { points -= 1; TracingFramework .printError("Deque.addFirst(\"\") should throw an IllegalArgumentException, but threw: " + e.getClass().getName() + ". Deducting 1 point."); } if (e.getMessage() == null || !e.getMessage().equals("Value cannot be empty")) { points -= 1; TracingFramework.printError( "Deque.addFirst(\"\") should throw an IllegalArgumentException with message 'Value cannot be empty', but got: " + e.getMessage() + ". Deducting 1 point."); } } } addPoints(points); } @Test(name = "Aufgabe 3 - Deque - addFirst throws IllegalArgumentException - 2 Punkte") public void testDequeAddFirstThrowsIllegalArgumentException() { Method method = findMethod(Deque.class, "addFirst", String.class) .orElseThrow(() -> new RuntimeException( "Method Deque.addFirst(String) not found. Class was mutated illegally.")); int points = 2; Class[] exceptionTypes = method.getExceptionTypes(); if (exceptionTypes.length == 0) { points -= 2; TracingFramework.printError( "Deque.addFirst(String) should throw an exception, but did not. Deducting 2 point."); } else if (exceptionTypes.length != 1) { points -= 2; TracingFramework.printError("Deque.addFirst(String) should only throw one exception, but threw: " + Arrays.toString(exceptionTypes) + ". Deducting 2 points."); } else { if (exceptionTypes[0] != IllegalArgumentException.class) { points -= 2; TracingFramework.printError( "Deque.addFirst(String) should throw an IllegalArgumentException, but threw: " + exceptionTypes[0].getName() + ". Deducting 2 points."); } } addPoints(points); } @Test(name = "Aufgabe 3 - Deque - addLast null - 3 Punkte") public void testDequeAddLastNull() { Method method = findMethod(Deque.class, "addLast", String.class) .orElseThrow(() -> new RuntimeException( "Method Deque.addLast(String) not found. Class was mutated illegally.")); int points = 3; if (addLastAlwaysException()) { points -= 3; TracingFramework.printError( "Deque.addLast(\"A\"), Deque.addLast(\"BCDEF\"), or Deque.addLast(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 3 points."); } else { try { Deque deque = new Deque(); executeVoidMethod(method, deque, (Object) null); points -= 3; TracingFramework .printError("Deque.addLast(null) should throw an exception, but did not. Deducting 3 points."); } catch (Exception e) { if (!(e instanceof IllegalArgumentException)) { points -= 1; TracingFramework .printError("Deque.addLast(null) should throw an IllegalArgumentException, but threw: " + e.getClass().getName() + ". Deducting 1 point."); } if (e.getMessage() == null || !e.getMessage().equals("Value cannot be null")) { points -= 1; TracingFramework.printError( "Deque.addLast(null) should throw an IllegalArgumentException with message 'Value cannot be null', but got: " + e.getMessage() + ". Deducting 1 point."); } } } addPoints(points); } @Test(name = "Aufgabe 3 - Deque - addLast empty - 3 Punkte") public void testDequeAddLastEmpty() { Method method = findMethod(Deque.class, "addLast", String.class) .orElseThrow(() -> new RuntimeException( "Method Deque.addLast(String) not found. Class was mutated illegally.")); int points = 3; if (addLastAlwaysException()) { points -= 3; TracingFramework.printError( "Deque.addLast(\"A\"), Deque.addLast(\"BCDEF\"), or Deque.addLast(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 3 points."); } else { try { Deque deque = new Deque(); executeVoidMethod(method, deque, ""); points -= 3; TracingFramework .printError("Deque.addLast(\"\") should throw an exception, but did not. Deducting 3 points."); } catch (Exception e) { if (!(e instanceof IllegalArgumentException)) { points -= 1; TracingFramework .printError("Deque.addLast(\"\") should throw an IllegalArgumentException, but threw: " + e.getClass().getName() + ". Deducting 1 point."); } if (e.getMessage() == null || !e.getMessage().equals("Value cannot be empty")) { points -= 1; TracingFramework.printError( "Deque.addLast(\"\") should throw an IllegalArgumentException with message 'Value cannot be empty', but got: " + e.getMessage() + ". Deducting 1 point."); } } } addPoints(points); } @Test(name = "Aufgabe 3 - Deque - addLast throws IllegalArgumentException - 2 Punkte") public void testDequeAddLastThrowsIllegalArgumentException() { Method method = findMethod(Deque.class, "addLast", String.class) .orElseThrow(() -> new RuntimeException( "Method Deque.addLast(String) not found. Class was mutated illegally.")); int points = 2; Class[] exceptionTypes = method.getExceptionTypes(); if (exceptionTypes.length == 0) { points -= 2; TracingFramework.printError( "Deque.addLast(String) should throw an exception, but did not. Deducting 2 point."); } else if (exceptionTypes.length != 1) { points -= 2; TracingFramework.printError("Deque.addLast(String) should only throw one exception, but threw: " + Arrays.toString(exceptionTypes) + ". Deducting 2 points."); } else { if (exceptionTypes[0] != IllegalArgumentException.class) { points -= 2; TracingFramework.printError( "Deque.addLast(String) should throw an IllegalArgumentException, but threw: " + exceptionTypes[0].getName() + ". Deducting 2 points."); } } addPoints(points); } @Test(name = "Aufgabe 3 - Deque - getFirst empty exception - 2 Punkte") public void testDequeGetFirstEmptyDeque() { Method method = findMethod(Deque.class, "getFirst") .orElseThrow(() -> new RuntimeException( "Method Deque.getFirst() not found. Class was mutated illegally.")); int points = 2; if (getFirstAlwaysException()) { points -= 2; TracingFramework.printError( "Deque.getFirst() threw an exception on Deque with five elements. Assuming method always throws an exception on valid deque. Deducting 2 points."); } else { try { Deque deque = new Deque(); executeMethod(method, deque, String.class, new Object[] {}); points -= 2; TracingFramework .printError( "Deque.getFirst() should throw an exception on empty deque, but did not. Deducting 2 points."); } catch (Exception e) { if (!(e instanceof NoSuchElementException)) { points -= 1; TracingFramework.printError( "Deque.getFirst() should throw a NoSuchElementException on empty deque, but threw: " + e.getClass().getName() + ". Deducting 1 point."); } if (e.getMessage() == null || !e.getMessage().equals("Deque is empty")) { points -= 1; TracingFramework.printError( "Deque.getFirst() should throw a NoSuchElementException with message 'Deque is empty', but got: " + e.getMessage() + ". Deducting 1 point."); } } } addPoints(points); } @Test(name = "Aufgabe 3 - Deque - getFirst throws NoSuchElementException - 2 Punkte") public void testDequeGetFirstThrowsNoSuchElementException() { Method method = findMethod(Deque.class, "getFirst") .orElseThrow(() -> new RuntimeException( "Method Deque.getFirst() not found. Class was mutated illegally.")); int points = 2; Class[] exceptionTypes = method.getExceptionTypes(); if (exceptionTypes.length == 0) { points -= 2; TracingFramework.printError( "Deque.getFirst() should throw an exception, but did not. Deducting 2 point."); } else if (exceptionTypes.length != 1) { points -= 2; TracingFramework.printError("Deque.getFirst() should only throw one exception, but threw: " + Arrays.toString(exceptionTypes) + ". Deducting 2 points."); } else { if (exceptionTypes[0] != NoSuchElementException.class) { points -= 2; TracingFramework.printError( "Deque.getFirst() should throw a NoSuchElementException, but threw: " + exceptionTypes[0].getName() + ". Deducting 2 points."); } } addPoints(points); } @Test(name = "Aufgabe 3 - Deque - getLast empty exception - 2 Punkte") public void testDequeGetLastEmptyDeque() { Method method = findMethod(Deque.class, "getLast") .orElseThrow(() -> new RuntimeException( "Method Deque.getLast() not found. Class was mutated illegally.")); int points = 2; if (getLastAlwaysException()) { points -= 2; TracingFramework.printError( "Deque.getLast() threw an exception on Deque with five elements. Assuming method always throws an exception on valid deque. Deducting 2 points."); } else { try { Deque deque = new Deque(); executeMethod(method, deque, String.class, new Object[] {}); points -= 2; TracingFramework .printError( "Deque.getLast() should throw an exception on empty deque, but did not. Deducting 2 points."); } catch (Exception e) { if (!(e instanceof NoSuchElementException)) { points -= 1; TracingFramework.printError( "Deque.getLast() should throw a NoSuchElementException on empty deque, but threw: " + e.getClass().getName() + ". Deducting 1 point."); } if (e.getMessage() == null || !e.getMessage().equals("Deque is empty")) { points -= 1; TracingFramework.printError( "Deque.getLast() should throw a NoSuchElementException with message 'Deque is empty', but got: " + e.getMessage() + ". Deducting 1 point."); } } } addPoints(points); } @Test(name = "Aufgabe 3 - Deque - getLast throws NoSuchElementException - 2 Punkte") public void testDequeGetLastThrowsNoSuchElementException() { Method method = findMethod(Deque.class, "getLast") .orElseThrow(() -> new RuntimeException( "Method Deque.getLast() not found. Class was mutated illegally.")); int points = 2; Class[] exceptionTypes = method.getExceptionTypes(); if (exceptionTypes.length == 0) { points -= 2; TracingFramework.printError( "Deque.getLast() should throw an exception, but did not. Deducting 2 point."); } else if (exceptionTypes.length != 1) { points -= 2; TracingFramework.printError("Deque.getLast() should only throw one exception, but threw: " + Arrays.toString(exceptionTypes) + ". Deducting 2 points."); } else { if (exceptionTypes[0] != NoSuchElementException.class) { points -= 2; TracingFramework.printError( "Deque.getLast() should throw a NoSuchElementException, but threw: " + exceptionTypes[0].getName() + ". Deducting 2 points."); } } addPoints(points); } /** * Checks if addFirst throws any exception when called. * * We assume that if any exception is thrown on valid values, it always throws * an exception. * * @return True if addFirst throws any exception, false otherwise. */ private boolean addFirstAlwaysException() { Deque deque = new Deque(); Consumer adder = findConsumer(deque, "addFirst", String.class) .orElseThrow(() -> new RuntimeException( "Method Deque.addFirst(String) not found. Class was mutated illegally.")); return adderThrowsAnyException(adder, "A", "BCDEF", "Hallo"); } /** * Checks if addLast throws any exception when called. * * We assume that if any exception is thrown on valid values, it always throws * an exception. * * @return True if addLast throws any exception, false otherwise. */ private boolean addLastAlwaysException() { Deque deque = new Deque(); Consumer adder = findConsumer(deque, "addLast", String.class) .orElseThrow(() -> new RuntimeException( "Method Deque.addLast(String) not found. Class was mutated illegally.")); return adderThrowsAnyException(adder, "A", "BCDEF", "Hallo"); } /** * Checks if the specified adder method throws any exception when called * with the given values. * * @param adder The adder method to test. * @param values The values to add. * @return True if the adder throws any exception, false otherwise. */ private boolean adderThrowsAnyException(Consumer adder, String... values) { try { for (String value : values) { adder.accept(value); } } catch (Exception e) { return false; } return true; } /** * Checks if getFirst throws any exception when called, * while the corresponding poller method is called successfully. * * We assume that if any exception is thrown on valid values, it always throws * an exception. * * @return True if the getter throws any exception, false otherwise. */ private boolean getFirstAlwaysException() { Deque deque = buildDeque("A", "B", "C", "D", "E"); Supplier getter = findSupplier(deque, "getFirst", String.class) .orElseThrow(() -> new RuntimeException( "Method Deque.getFirst() not found. Class was mutated illegally.")); Supplier poller = findSupplier(deque, "pollFirst", String.class) .orElseThrow(() -> new RuntimeException( "Method Deque.pollFirst() not found. Class was mutated illegally.")); return getterAnyThrowsException(getter, poller, 5); } /** * Checks if getLast throws any exception when called, * while the corresponding poller method is called successfully. * * We assume that if any exception is thrown on valid values, it always throws * an exception. * * @return True if getLast throws any exception, false otherwise. */ private boolean getLastAlwaysException() { Deque deque = buildDeque("A", "B", "C", "D", "E"); // should be executable five times when deque is not empty Supplier getter = findSupplier(deque, "getLast", String.class) .orElseThrow(() -> new RuntimeException( "Method Deque.getLast() not found. Class was mutated illegally.")); Supplier poller = findSupplier(deque, "pollLast", String.class) .orElseThrow(() -> new RuntimeException( "Method Deque.pollLast() not found. Class was mutated illegally.")); return getterAnyThrowsException(getter, poller, 5); } /** * Checks if the specified getter method throws any exception when called, * while the corresponding poller method is called successfully. * * @param getter The getter method to test. * @param poller The poller method to call. * @param n The number of times to call the methods. * @return True if the getter throws any exception, false otherwise. */ private boolean getterAnyThrowsException(Supplier getter, Supplier poller, int n) { try { for (int i = 0; i < n; i++) { getter.get(); poller.get(); } } catch (Exception e) { 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 (deque.peekFirst() == 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) { throw new RuntimeException("Failed to build deque: " + e.getMessage(), e); } } return deque; } /** * Builds a binary tree from an array from top to bottom and left to right. * * @param values The values. * @return The tree node representing the root. */ private TreeNode buildTree(double[] values) { TreeNode root = new TreeNode(values[0]); java.util.List nodes = new ArrayList<>(); nodes.add(root); for (int i = 1; i < values.length; i++) { TreeNode parent = nodes.get(0); TreeNode child = new TreeNode(values[i]); nodes.add(child); if (i % 2 == 1) { parent.setLeft(child); } else { parent.setRight(child); nodes.remove(0); } } return root; } /** * Sets the root in the tree. * * @param tree The tree. * @param root The root to set in the tree. */ private void setRoot(Tree tree, TreeNode root) { try { Field field = Tree.class.getDeclaredField("root"); field.setAccessible(true); field.set(tree, root); } catch (Exception e) { throw new RuntimeException("Failed to set root."); } } /** * Sets the front item in the deque using reflection. * * @param deque The deque. * @param item The item to set as front. */ private void setFront(Deque deque, Item item) { try { Field field = Deque.class.getDeclaredField("front"); field.setAccessible(true); field.set(deque, item); } catch (Exception e) { throw new RuntimeException("Failed to set front."); } } /** * Sets the back item in the deque using reflection. * * @param deque The deque. * @param item The item to set as back. */ private void setBack(Deque deque, Item item) { try { Field field = Deque.class.getDeclaredField("back"); field.setAccessible(true); field.set(deque, item); } catch (Exception e) { throw new RuntimeException("Failed to set back."); } } /** * Gets the back item from the deque using reflection. * * @param deque The deque. * @return The back item. */ private Item getBack(Deque deque) { try { Field field = Deque.class.getDeclaredField("back"); field.setAccessible(true); return (Item) field.get(deque); } catch (Exception e) { throw new RuntimeException("Failed to get back."); } } /** * Sets the next item in an Item using reflection. * * @param item The item. * @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 (Exception e) { throw new RuntimeException("Failed to set next."); } } /** * Sets the previous item in an Item using reflection. * * @param item The item. * @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 (Exception e) { throw new RuntimeException("Failed to set prev."); } } /** * General utility methods below... */ /** * Finds a method in a class by name and parameter types. * * @param clazz The class to search in. * @param name The name of the method. * @param parameterTypes The parameter types of the method. * @return An Optional containing the found method, or empty if not found. */ public static Optional findMethod(Class clazz, String name, Class... parameterTypes) { try { return Optional.of(clazz.getDeclaredMethod(name, parameterTypes)); } catch (NoSuchMethodException e) { return Optional.empty(); } } /** * Checks if a method has a specific return type. * * @param method The method to check. * @param returnType The expected return type. * @return True if the method has the expected return type, false otherwise. */ public static boolean hasReturnType(Method method, Class returnType) { return method.getReturnType().equals(returnType); } public static Optional executeMethod(Method method, Object instance, Class returnType, Object... args) { try { Object result = method.invoke(instance, args); return Optional.of(returnType.cast(result)); } catch (Exception e) { e.printStackTrace(); return Optional.empty(); } } public static void executeVoidMethod(Method method, Object instance, Object... args) throws Exception { method.invoke(instance, args); } public static boolean safeExecuteVoidMethod(Method method, Object instance, Object... args) { try { executeVoidMethod(method, instance, args); return true; } catch (Exception e) { e.printStackTrace(); } return false; } /** * Converts a reference type to its primitive value if applicable. * If the object is a boxed primitive and the target type is a primitive, * returns the primitive value. Otherwise, returns the object as is. * * @param value The object to convert. * @param primitiveType The target primitive class (e.g., int.class, * double.class). * @return The primitive value or the original object. */ public static Object toPrimitiveIfPossible(Object value, Class primitiveType) { if (value == null) { return null; } if (primitiveType == int.class && value instanceof Integer) { return ((Integer) value).intValue(); } else if (primitiveType == double.class && value instanceof Double) { return ((Double) value).doubleValue(); } else if (primitiveType == boolean.class && value instanceof Boolean) { return ((Boolean) value).booleanValue(); } else if (primitiveType == long.class && value instanceof Long) { return ((Long) value).longValue(); } else if (primitiveType == float.class && value instanceof Float) { return ((Float) value).floatValue(); } else if (primitiveType == short.class && value instanceof Short) { return ((Short) value).shortValue(); } else if (primitiveType == byte.class && value instanceof Byte) { return ((Byte) value).byteValue(); } else if (primitiveType == char.class && value instanceof Character) { return ((Character) value).charValue(); } return value; } /** * Finds a consumer method in a class by name and parameter type. * * @param The type of the parameter for the consumer. * @param obj The object to search in. * @param methodName The name of the method. * @param parameterType The parameter type of the method. * @return An Optional containing the found consumer, or empty if not found. */ public static Optional> findConsumer(Object obj, String methodName, Class parameterType) { Optional method = findMethod(obj.getClass(), methodName, parameterType); if (method.isEmpty()) { return Optional.empty(); } return Optional.of(arg -> safeExecuteVoidMethod(method.get(), obj, toPrimitiveIfPossible(arg, parameterType))); } /** * Finds a supplier method in a class by name and return type. * * @param The type of the return value for the supplier. * @param obj The object to search in. * @param methodName The name of the method. * @param returnType The expected return type of the method. * @return An Optional containing the found supplier, or empty if not found. */ public static Optional> findSupplier(Object obj, String methodName, Class returnType) { Optional method = findMethod(obj.getClass(), methodName); if (method.isEmpty()) { return Optional.empty(); } return Optional.of(() -> { Optional result = executeMethod(method.get(), obj, returnType); return result.orElse(null); }); } /** * The points of each test case. */ private java.util.List points = 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 : points) { 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) { points.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 { Tests test = new Tests(); System.out.println(test.getClass().getName()); System.out.println(); for (Method method : test.getClass().getMethods()) { if (method.isAnnotationPresent(Test.class)) { int size = test.points.size(); try { method.invoke(test); if (test.points.size() != size + 1) { System.err.println("Der Test " + method.getAnnotation(Test.class).name() + " lieferte kein oder mehrere Ergebnisse."); } else { System.out.println("Punkte: " + test.points.get(test.points.size() - 1) + " (" + method.getAnnotation(Test.class).name() + ")"); } } catch (Exception e) { System.err.println( "Der Test " + method.getAnnotation(Test.class).name() + " lieferte ein Exception."); e.printStackTrace(); } } } System.out.println(); System.out.println("Summe: " + test.getResult()); } public static void main(String[] args) { try { runAll(); } catch (Exception e) { e.printStackTrace(); } } }