import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; 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 { public static void main(String[] args) { Class clazz = Tests.class; Tests test = new Tests(); System.out.println(String.format("Tests: %s", test.getClass().getName())); 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.points.size(); try { method.invoke(test); if (test.points.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.points.get(test.points.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())); } // Aufgabe 1 - 25 Punkte @Test(name = "Aufgabe 1 - empty array - 5 points") public void testA1EmptyArray() { int[] arr = new int[0]; testCalculateMeanBelow(arr, 5, 0.0, 5); } @Test(name = "Aufgabe 1 - null array - 5 points") public void testA1NullArray() { int[] arr = null; testCalculateMeanBelow(arr, 42, 0.0, 5); } @Test(name = "Aufgabe 1 - no elements below threshold - 5 points") public void testA1NoElementsBelowThreshold() { int[] arr = { -1000000000, 0, 1000, 1000000, 1000000000 }; testCalculateMeanBelow(arr, Integer.MIN_VALUE, 0.0, 5); } @Test(name = "Aufgabe 1 - all elements below threshold - 5 points") public void testA1AllElementsBelowThreshold() { int[] arr = { 10, 20, 30 }; testCalculateMeanBelow(arr, Integer.MAX_VALUE, 20.0, 5); } @Test(name = "Aufgabe 1 - some elements below threshold - 5 points") public void testA1SomeElementsBelowThreshold() { int[] arr = { -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 }; testCalculateMeanBelow(arr, -2, -4.0, 5); } public void testCalculateMeanBelow(int[] arr, int threshold, double expected, int points) { double result = Testat1B.calculateMeanBelow(arr, threshold); if (result != expected) { TracingFramework.printError(String.format("FAIL: Expected %f for %s with threshold %d, but got %f", expected, Arrays.toString(arr), threshold, result)); } else { addPoints(points); } } // Aufgabe 2 - 25 Punkte @Test(name = "Aufgabe 2 - empty array - 2 points") public void testA2EmptyArray() { int[][] arr = new int[0][]; testCalculateColumnMean(arr, new double[0], 2); } @Test(name = "Aufgabe 2 - null array - 2 points") public void testA2NullArray() { int[][] arr = null; testCalculateColumnMean(arr, new double[0], 2); } @Test(name = "Aufgabe 2 - some columns empty - 2 points") public void testA2SomeColumnsEmpty() { int[][] arr = { {}, {}, { 1, 2, 3 }, {}, {}, { 4, 5, 6 } }; testCalculateColumnMean(arr, new double[] { 0.0, 0.0, 2.0, 0.0, 0.0, 5.0 }, 2); } @Test(name = "Aufgabe 2 - some columns null - 2 points") public void testA2SomeColumnsNull() { int[][] arr = { null, { 1, 2, 3 }, null, { 4, 5, 6 }, null, null }; testCalculateColumnMean(arr, new double[] { 0.0, 2.0, 0.0, 5.0, 0.0, 0.0 }, 2); } @Test(name = "Aufgabe 2 - unequal column lengths - 3 points") public void testA2UnequalColumnLengths() { int[][] arr = { { 1, 2, 3 }, { 4, 5 }, { 6 }, { -4, -3, -2, -1 }, { 7, 8, 9, 10 }, { -5, 0, 5 } }; testCalculateColumnMean(arr, new double[] { 2.0, 4.5, 6.0, -2.5, 8.5, 0.0 }, 3); } @Test(name = "Aufgabe 2 - rectangular array - 7 points") public void testA2RectangularArray() { int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { -30, -20, -10 } }; testCalculateColumnMean(arr, new double[] { 2.0, 5.0, 8.0, -20.0 }, 7); } @Test(name = "Aufgabe 2 - quadratic array - 7 points") public void testA2QuadraticArray() { int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; testCalculateColumnMean(arr, new double[] { 2.0, 5.0, 8.0 }, 7); } public void testCalculateColumnMean(int[][] arr, double[] expected, int points) { double[] result = Testat1B.calculateColumnMean(arr); if (Arrays.equals(result, expected)) { addPoints(points); } else { TracingFramework.printError(String.format("FAIL: Expected %s for %s, but got %s", Arrays.toString(expected), Arrays.deepToString(arr), Arrays.toString(result))); } } // Aufgabe 3 - 50 Punkte @Test(name = "Aufgabe 3a - private fields - 6 points") public void testA3PrivateFields() { int points = 6; points -= testField(MediaItem.class, "duration", int.class, 2); points -= testField(MediaItem.class, "title", String.class, 2); points -= testField(MediaItem.class, "views", int.class, 2); addPoints(points); } @Test(name = "Aufgabe 3b - MediaItem constructor - 6 points") public void testA3MediaItemConstructor() { int points = 6; int duration = 314159; String title = "Foo: Bar"; int views = 42; MediaItem item = new MediaItem(duration, title, views); points -= checkConstructorField(MediaItem.class, "duration", int.class, item, duration, 2); points -= checkConstructorField(MediaItem.class, "title", String.class, item, title, 2); points -= checkConstructorField(MediaItem.class, "views", int.class, item, views, 2); addPoints(points); } @Test(name = "Aufgabe 3c - lasting interface - 8 points") public void testA3LastingInterface() { int points = 8; Class clazz = MediaItem.class; if (!implementsInterface(clazz, Lasting.class)) { points -= 4; TracingFramework .printError(String.format("FAIL: Class '%s' does not implement interface '%s'. Deducting 4 points.", clazz.getName(), Lasting.class.getName())); } Optional method = findMethod(MediaItem.class, "getDuration", int.class); if (method.isEmpty()) { points -= 4; TracingFramework .printError(String.format("FAIL: Method 'getDuration' not found in class '%s'. Deducting 4 points.", clazz.getName())); } else { Method getDurationMethod = method.get(); int duration = 42; MediaItem item = new MediaItem(duration, "Foo", 42); try { int result = (int) getDurationMethod.invoke(item); if (result != duration) { TracingFramework.printError(String.format("FAIL: Expected getDuration() to return %d, but got %d", duration, result)); points = 0; } } catch (IllegalAccessException | InvocationTargetException e) { TracingFramework .printError(String.format("FAIL: Could not invoke getDuration() on item of class '%s'", item.getClass().getName())); points = 0; } } addPoints(points); } @Test(name = "Aufgabe 3d - MediaItem toString - 10 points") public void testA3MediaItemToString() { int points = 10; if (!overridesMethod(MediaItem.class, "toString")) { TracingFramework.printError(String.format("FAIL: Class '%s' does not override method 'toString'", MediaItem.class.getName())); points = 0; } else { MediaItem item = new MediaItem(84, "Foo", 42); String expected = "Foo (42 84 min)"; points -= testToString(item, expected, 5); MediaItem item2 = new MediaItem(1234, "Bar", 4567); String expected2 = "Bar (4567 1234 min)"; points -= testToString(item2, expected2, 5); } addPoints(points); } @Test(name = "Aufgabe 3e - Series extends MediaItem - 5 points") public void testA3SeriesExtendsMediaItem() { int points = 5; if (!extendsClass(Series.class, MediaItem.class)) { TracingFramework.printError(String.format("FAIL: Class '%s' does not extend class '%s'", Series.class.getName(), MediaItem.class.getName())); points -= 5; } else { Series series = createInstance(Series.class, 42, "Test Series", 42); if (series == null) { TracingFramework.printError(String.format("FAIL: Could not create instance of class '%s'", Series.class.getName())); points = 0; } } addPoints(points); } @Test(name = "Aufgabe 3e - Movie extends MediaItem - 5 points") public void testA3MovieExtendsMediaItem() { int points = 5; if (!extendsClass(Movie.class, MediaItem.class)) { TracingFramework.printError(String.format("FAIL: Class '%s' does not extend class '%s'", Movie.class.getName(), MediaItem.class.getName())); points -= 5; } else { Movie movie = createInstance(Movie.class, 42, "Test Movie", 42); if (movie == null) { TracingFramework.printError(String.format("FAIL: could not create instance of class '%s'", Movie.class.getName())); points = 0; } } addPoints(points); } @Test(name = "Aufgabe 3g - Series overrides toString - 5 points") public void testA3SeriesOverridesToString() { int points = 5; if (!overridesMethod(Series.class, "toString")) { TracingFramework.printError(String.format("FAIL: Class '%s' does not override method 'toString'", Series.class.getName())); points = 0; } else { Series series = createInstance(Series.class, 42, "Test Series", 42); if (series == null) { TracingFramework.printError(String.format("FAIL: Could not create instance of class '%s'", Series.class.getName())); points = 0; } else { String expected = "Series: Test Series (42 42 min)"; points -= testToString(series, expected, 5); } } addPoints(points); } @Test(name = "Aufgabe 3g - Movie overrides toString - 5 points") public void testA3MovieOverridesToString() { int points = 5; if (!overridesMethod(Movie.class, "toString")) { TracingFramework.printError(String.format("FAIL: Class '%s' does not override method 'toString'", Movie.class.getName())); points = 0; } else { Movie movie = createInstance(Movie.class, 42, "Test Movie", 42); if (movie == null) { TracingFramework.printError(String.format("FAIL: Could not create instance of class '%s'", Movie.class.getName())); points = 0; } else { String expected = "Movie: Test Movie (42 42 min)"; points -= testToString(movie, expected, 5); } } addPoints(points); } public static T createInstance(Class clazz, Object... args) { try { Class[] argTypes = Arrays.stream(args).map(Object::getClass).map(c -> { if (c.getName().equals("java.lang.Integer")) { return int.class; } else if (c.getName().equals("java.lang.Double")) { return double.class; } return c; }).toArray(Class[]::new); Constructor constructor = clazz.getDeclaredConstructor(argTypes); constructor.setAccessible(true); Object[] convertedArgs = Arrays.stream(args).map(arg -> { if (arg instanceof Integer) { return (int) arg; } else if (arg instanceof Double) { return (double) arg; } return arg; }).toArray(); return constructor.newInstance(convertedArgs); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); return null; } } public static Optional findMethod(Class clazz, String methodName, Class returnType, Class... parameterTypes) { try { Method method = clazz.getDeclaredMethod(methodName, parameterTypes); if (method.getReturnType().equals(returnType)) { return Optional.of(method); } } catch (NoSuchMethodException e) { // Method not found } return Optional.empty(); } /** * Returns true if the class clazz extends the superclass superclass. * * @param clazz The class to check. * @param superclass The superclass to check against. * @return True if clazz extends superclass, false otherwise. */ public boolean extendsClass(Class clazz, Class superclass) { return superclass.isAssignableFrom(clazz); } /** * Returns the points to deduct for a test case that checks the * toString() method. * * @param obj The object to test. * @param expected The expected string representation. * @param maxPoints The maximum points to deduct. * @return The points to deduct. maxPoints if the toString() method returns * completely different output, * maxPoints / 2 if the output is similar but has different whitespace, * otherwise 0. */ private static int testToString(Object obj, String expected, int maxPoints) { String result = obj.toString(); if (result == null) { TracingFramework.printError(String.format("FAIL: toString() returned null for object of class '%s'", obj.getClass().getName())); return maxPoints; } else if (!result.equals(expected)) { if (result.replaceAll("\\s+", " ").trim().equals(expected.replaceAll("\\s+", " ").trim())) { TracingFramework.printError(String.format( "FAIL: toString() returned '%s' for object of class '%s', but expected '%s' (ignoring whitespace)", result, obj.getClass().getName(), expected)); return maxPoints / 2; } else { TracingFramework.printError(String.format("FAIL: Expected toString() to return '%s', but got '%s'", expected, result)); return maxPoints; } } return 0; } /** * Returns whether the given class overrides the specified method. * * @param subclass The class to check. * @param methodName The name of the method to find. * @param parameterTypes The parameter types of the method to find. * @return True if the class overrides the method, false otherwise. */ public static boolean overridesMethod(Class subclass, String methodName, Class... parameterTypes) { try { Method method = subclass.getDeclaredMethod(methodName, parameterTypes); return method.getDeclaringClass().equals(subclass); } catch (NoSuchMethodException e) { return false; } } /** * Returns the points to deduct for not setting the field in the constructor. * * @param The type of the field. * @param clazz The class that should contain the field. * @param fieldName The name of the field. * @param type The type of the field. * @param instance The instance to check. * @param expected The expected value. * @param maxPoints The maximum points to deduct. * @return The points to deduct. */ private int checkConstructorField(Class clazz, String fieldName, Class type, Object instance, T expected, int maxPoints) { Field field = getField(clazz, fieldName, type); if (field == null) { TracingFramework.printError(String.format("FAIL: Field '%s' of type %s not found in class '%s'", fieldName, type.getName(), clazz.getName())); return maxPoints; } T value = readField(field, type, instance); if (!Objects.equals(value, expected)) { TracingFramework.printError(String.format("FAIL: Expected field '%s' to be %s, but got %s", fieldName, expected, value)); return maxPoints; } return 0; } /** * Returns the points to deduct for a missing or incorrect field. Based on the * type and the privacy of the field. * * @param clazz The class that should contain the field. * @param fieldName The name of the field. * @param type The type of the field. * @param maxPoints The maximum points to deduct. * @return If the field is missing maxPoints, if the field is present but not * private maxPoints / 2, otherwise 0. */ private int testField(Class clazz, String fieldName, Class type, int maxPoints) { Field field = getField(clazz, fieldName, type); if (field == null) { TracingFramework .printError(String.format("FAIL: Field '%s' of type %s not found in class '%s'", fieldName, type.getName(), clazz.getName())); return maxPoints; } else if (!isPrivateField(field)) { TracingFramework.printError( String.format("FAIL: Field '%s' in class '%s' is not private", fieldName, clazz.getName())); return maxPoints / 2; } return 0; } /** * Returns the field with the given name and type from the specified class. * * @param clazz The class to check. * @param fieldName The name of the field to find. * @param type The type of the field to find. * @return The field if found, null otherwise. */ public Field getField(Class clazz, String fieldName, Class type) { try { Field field = clazz.getDeclaredField(fieldName); if (!field.getType().equals(type)) { return null; } return field; } catch (NoSuchFieldException e) { e.printStackTrace(); return null; } } /** * Checks if the given field is private. * * @param field The field to check. * @return True if the field is private, false otherwise. */ public boolean isPrivateField(Field field) { return Modifier.isPrivate(field.getModifiers()); } /** * Reads the value of a field from an instance. * * @param The type of the field. * @param field The field to read. * @param type The type of the field. * @param instance The instance from which to read the field. * @return The value of the field, or null if an error occurs. */ @SuppressWarnings("unchecked") public T readField(Field field, Class type, Object instance) { try { field.setAccessible(true); Object obj = field.get(instance); if (obj == null) { return null; } if (type.isPrimitive()) { if ((type == double.class && obj instanceof Double) || (type == int.class && obj instanceof Integer) || (type == boolean.class && obj instanceof Boolean) || (type == long.class && obj instanceof Long) || (type == float.class && obj instanceof Float) || (type == short.class && obj instanceof Short) || (type == byte.class && obj instanceof Byte) || (type == char.class && obj instanceof Character)) { return (T) obj; } else { throw new ClassCastException("Cannot cast " + obj.getClass().getName() + " to " + type.getName()); } } return type.cast(obj); } catch (IllegalAccessException | ClassCastException e) { e.printStackTrace(); return null; } } /** * Returns true if the given class has a constructor with the specified * parameter types. * * @param clazz The class to check. * @param parameterTypes The parameter types of the constructor. * @return True if the class has a constructor with the specified parameter * types, false otherwise. */ public boolean hasConstructor(Class clazz, Class... parameterTypes) { try { clazz.getDeclaredConstructor(parameterTypes); return true; } catch (NoSuchMethodException e) { return false; } } /** * Returns true if the given class implements the specified 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) { return interfaceClass.isAssignableFrom(clazz); } /** * The points of each test case. */ private 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); } }