diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5241a72 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.class \ No newline at end of file diff --git a/WS2526/Testat 1a/Aufgabenstellung.txt b/WS2526/Testat 1a/Aufgabenstellung.txt new file mode 100644 index 0000000..33120e5 --- /dev/null +++ b/WS2526/Testat 1a/Aufgabenstellung.txt @@ -0,0 +1,97 @@ +TESTAT 1A - Arrays und Vererbung + +---------------------------------------------------------------------------------- + +WICHTIGE HINWEISE + +- Verändern Sie die Signaturen der Methoden NICHT! +- Abgaben mit Syntax-Fehlern werden automatisch mit 0 Punkten bewertet. +- Vergessen Sie NICHT ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie +Sie wollen, der Beste versucht wird bewertet. +- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden +Kommentaren in den Klassen aufmerksam. Bei Unklarheiten drüfen Sie Fragen an die Aufsicht +stellen. +- In der main-Methode stellen wir Ihnen Testfälle zur Verfügung mit denen Sie +ihre Ergebnisse während der Entwicklung kontrollieren können. Diese Testfälle sind jedoch +NICHT alle Testfälle welche serverseitig ausgeführt werden für die finale Bewertung. D.h. +nur weil diese Testfälle bestehen erhalten Sie nicht automatisch die volle Punktzahl. + + +Wir wünschen viel Erfolg! + +-------------------------------------------------------------------------------- + +Aufgabe 1 +Die Methode calculateMeanAbove der Klasse Testat1A soll für alle Werte des +übergebenen Arrays arr, welche GRÖßER ALS der Grenzwert threshold sind, den +Durchschnitt berechnen. + +Für die volle Punktzahl müssen Sie berücksichtigen, dass der Array arr auch null +oder leer sein kann. In diesem Fall soll 0 zurückgegeben werden. + +--------------------------------------------------------------------------------- + +Aufgabe 2 - 25 Punkte +Die Methode calculateRowMean in der Klasse Testat1A erhält einen 2-dimensionales +Array, soll den Durchschnitt für jede Reihe berechnen und in einem neuen Array +zurückgeben. + +Die erste Dimension des 2-dimensionalen Arrays addressiert die Reihe, die zweite +Dimension die Spalte. D.h. int x = arr[0][1] weist x den Wert der Reihe 0 und der +Spalte 1 zu. + +In dem eindimensionalen Rückgabearray soll der Wert an der i-ten Stelle dem +Durchschnitt der i-ten Reihe entsprechen. + +Für die volle Punktzahl müssen Sie folgendes beachten: +- Das übergebene 2-dimensionale Array kann null oder leer sein. In diesem Fall soll +ein leeres Array übergeben werden. +- Reihen innerhalb des 2-dimensionalen Arrays können null oder leer sein. In diesem +Fall soll für diese Reihe 0 im ausgegebenen Array gesetzt werden. +- Reihen innerhalb des 2-dimensionalen Arrays haben nicht notwendigerweise dieselben +Längen. Beachten Sie dies bei ihren Berechnungen. + + +Beispiel: + +------- ----------------- +|1|2|3| |(1+2+3)/3 = 2.0| +------- ----------------- +|4|5|6| |(4+5+6)/3 = 5.0| +------- ----------------- +|7|8|9| |(7+8+9)/3 = 8.0| +------- ----------------- + +Eingabe Rückgabe + + +--------------------------------------------------------------------------------- + +Aufgabe 3 - 50 Punkte +In dieser Aufgabe sollen Sie die Klassen FridgeItem, Cheese und Yoghurt anpassen. Die +Schnittstelle Weightful ist vorgegeben und darf nicht verändert werden. + +Ergänzen Sie die Klasse FridgeItem wie folgt: +- a) Fügen Sie der Klasse 3 private Instanzvariablen hinzu: "weight" vom Typ double, "name" vom +Typ String und "color" vom Typ String. +- b) Initialisieren Sie diese Felder im vorgegebenen Konstruktor mit den Werten, die dieser als Pa- +rameter erhält. +- c) Implementieren Sie die Schnittstelle Weightful und geben Sie in der zugehörigen Methode den +Wert der Instanzvariable "weight" zurück. +- d) Überschreiben Sie die toString() Methode aus java.lang.Object, so dass diese eine Zeichen- +kette in folgendem Format zurückgibt: ( g) (also: Wert der Instanzva- +riable name, Leerzeichen, Klammer auf, Wert der Instanzvariable color, Leerzeichen, Wert der +Instanzvariable weight, Leerzeichen, kleines g, Klammer zu) + +Ergänzen Sie die Klassen Cheese und Yoghurt wie folgt: +- e) Ändern Sie die Vererbungsbeziehungen so, dass beide Klassen von FridgeItem erben. +- f) Fügen Sie den Klassen den Konstruktor Ihrer neuen Superklasse hinzu und geben Sie die +Parameter an die Superklasse weiter. +- g) Überschreiben Sie die toString() Methode, so dass vor den Wert der Implementierung aus der +Superklasse noch der Name der Klasse gefolgt von einem Doppelpunkt und einem Leerzeichen +angefügt wird. D.h. analog zu FridgeItem soll die Ausgabe wie folgt aussehen: + + Cheese: ( g) (für toString() in Cheese) + Yoghurt: ( g) (für toString() in Yoghurt) + +Nachdem Sie diese Änderungen gemacht haben, sollten alle Kompilierungsfehler beseitigt sein. \ No newline at end of file diff --git a/WS2526/Testat 1a/Cheese.java b/WS2526/Testat 1a/Cheese.java new file mode 100644 index 0000000..fe71fbf --- /dev/null +++ b/WS2526/Testat 1a/Cheese.java @@ -0,0 +1,44 @@ +/** + * Aufgabe 3e + * + * Verändern Sie die Klasse Cheese so, dass sie von FridgeItem erbt. + * + * Nicht übersehen: Machen Sie dies auch für die Klasse Yoghurt. + */ + +public class Cheese { // TODO: change + + /** + * Aufgabe 3f + * + * Fügen Sie der Klasse Cheese einen Konstruktor hinzu, der die Variablen + * weight, name und color initialisiert. Geben Sie dafür die Werte an den + * Konstruktor der Superklasse weiter. + * + * Nicht übersehen: Machen Sie dies auch für die Klasse Yoghurt. + */ + + /** + * Creates a new cheese with the weight, name and color. + * + * @param weight The weight. + * @param name The name. + * @param color The color. + */ + // TODO: constructor + + /** + * Aufgabe 3g + * + * Überschreiben Sie die toString() Methode, so dass vor den Wert der + * Implementierung aus der Superklasse noch der Name der Klasse gefolgt von + * einem Doppelpunkt und einem Leerzeichen angefügt wird. D.h. analog zu + * FridgeItem soll die Ausgabe wie folgt aussehen: + * + * Cheese: ( g) + * + * Nicht übersehen: Machen Sie dies auch für die Klasse Yoghurt. + */ + // TODO: toString + +} diff --git a/WS2526/Testat 1a/FridgeItem.java b/WS2526/Testat 1a/FridgeItem.java new file mode 100644 index 0000000..78115f6 --- /dev/null +++ b/WS2526/Testat 1a/FridgeItem.java @@ -0,0 +1,83 @@ +/** + * Aufgabe 3c + * + * Implementieren Sie die Schittstelle Weightful und geben Sie in der + * dazugehörigen Methode den Wert der Instanzvariable weight zurück. + * + * Entfernen Sie auf KEINEN Fall TraceableItem. + */ + +public abstract class FridgeItem extends TraceableItem { // TODO: change + + /** + * Aufgabe 3a + * + * Fügen Sie unterhalb, drei Private Variablen für die + * Gewicht, Name und Farbe des Items hinzu. Dabei soll weight vom Typ double, + * name vom Typ String und color vom Typ String sein. + */ + + /** + * The weight of the item. + */ + // TODO: add variable + + /** + * The name of the item. + */ + // TODO: add variable + + /** + * The color of the item. + */ + // TODO: add variable + + /** + * Aufgabe 3b + * + * Initalisieren Sie die vorher angelegten Variablen im vorgegebenen Konstruktor + * mit Werten, den dieser als Parameter erhält. + */ + + /** + * Creates a fridge item with the specified weight, name and color. + * + * @param weight The weight of the item. + * @param name The name of the item. + * @param color The color of the item. + */ + public FridgeItem(double weight, String name, String color) { + // TODO: assign member variables + + } + + /** + * Returns the name of the item. + * + * @return The name of the item. + */ + public String getName() { + return name; + } + + /** + * Returns the color of the item. + * + * @return The color of the item. + */ + public String getColor() { + return color; + } + + /** + * Aufgabe 3d + * + * Überschreiben Sie die toString() Methode aus java.lang.Object, so dass diese + * eine Zeichenkette in folgendem Format zurückgibt: ( g) + * (also: Wert der Instanzvariable name, Leerzeichen, Klammer auf, Wert der + * Instanzvariable color, Leerzeichen, Wert der Instanzvariable weight, + * Leerzeichen, kleines g, Klammer zu) + */ + // TODO: toString + +} diff --git a/WS2526/Testat 1a/Main.java b/WS2526/Testat 1a/Main.java new file mode 100644 index 0000000..b4461fd --- /dev/null +++ b/WS2526/Testat 1a/Main.java @@ -0,0 +1,77 @@ +import java.util.Arrays; + +public class Main { + /** + * Die folgende main-Methode dient Ihnen zur Hilfe, um Ihre Lösungen zutesten. + * Beachten Sie bitte, dass in dieser Methode nicht alle Tests enthalten sind, + * sondern nur einige, die Ihnen helfen sollen, Ihre Lösungen zu überprüfen. + */ + public static void main(String[] args) { + System.out.println("Aufgabe 1"); + System.out.println("-----"); + System.out.println("Eingabearray: [1, 2, 3, 4, 5]"); + System.out.println("Grenzwert: 2"); + System.out.println("Erwartete Ausgabe: 4.0"); + System.out.println("Ihre Ausgabe: " + Testat1A.calculateMeanAbove(new int[] { 1, 2, 3, 4, 5 }, 2)); + System.out.println(); + System.out.println("Eingabearray: [-10, 0, 10, 20, 4, -7, 4]"); + System.out.println("Grenzwert: 0"); + System.out.println("Erwartete Ausgabe: 9.5"); + System.out.println("Ihre Ausgabe: " + Testat1A.calculateMeanAbove(new int[] { -10, 0, 10, 20, 4, -7, 4 }, 0)); + System.out.println(); + System.out.println("Eingabearray: null"); + System.out.println("Grenzwert: 5"); + System.out.println("Erwartete Ausgabe: 0.0"); + System.out.println("Ihre Ausgabe: " + Testat1A.calculateMeanAbove(null, 5)); + System.out.println(); + + System.out.println("Aufgabe 2"); + System.out.println("-----"); + int[][] array = { { 1, 2, 3 }, { 4, 5 }, { 6 }, null }; + double[] means = Testat1A.calculateRowMean(array); + System.out.println("Eingabearray: [[1, 2, 3], [4, 5], [6], null]"); + System.out.println("Erwartete Ausgabe: [2.0, 4.5, 6.0, 0.0]"); + System.out.println("Ihre Ausgabe: " + Arrays.toString(means)); + System.out.println(); + array = new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; + means = Testat1A.calculateRowMean(array); + System.out.println("Eingabearray: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]"); + System.out.println("Erwartete Ausgabe: [2.0, 5.0, 8.0]"); + System.out.println("Ihre Ausgabe: " + Arrays.toString(means)); + System.out.println(); + array = new int[][] { { 1, 2 }, { 1, 2 }, { 1, 2 }, {} }; + means = Testat1A.calculateRowMean(array); + System.out.println("Eingabearray: [[1, 2], [1, 2], [1, 2], []]"); + System.out.println("Erwartete Ausgabe: [1.5, 1.5, 1.5, 0.0]"); + System.out.println("Ihre Ausgabe: " + Arrays.toString(means)); + System.out.println(); + + System.out.println("Aufgabe 3"); + System.out.println("-----"); + + // create items + FridgeItem gouda = new Cheese(500.5, "Gouda", "yellow"); + FridgeItem cheddar = new Cheese(1123.75, "Cheddar", "orange"); + FridgeItem cherryYoghurt = new Yoghurt(250, "Cherry", "red"); + FridgeItem vanillaYoghurt = new Yoghurt(500, "Vanilla", "light yellow"); + + // Weightful + System.out.println("Expected (Gouda.getWeight()): 500.5"); + System.out.println("Your code (Gouda.getWeight()): " + gouda.getWeight()); + System.out.println("Expected (Cheddar.getWeight()): 1123.75"); + System.out.println("Your code (Cheddar.getWeight()): " + cheddar.getWeight()); + System.out.println("Expected (CherryYoghurt.getWeight()): 250.0"); + System.out.println("Your code (CherryYoghurt.getWeight()): " + cherryYoghurt.getWeight()); + System.out.println("Expected (VanillaYoghurt.getWeight()): 500.0"); + System.out.println("Your code (VanillaYoghurt.getWeight()): " + vanillaYoghurt.getWeight()); + System.out.println(); + + // toString + System.out.println("Expected (Cheese.toString()): Cheese: Cheddar (orange 1123.75 g)"); + System.out.println("Your code (Cheese.toString()): " + cheddar.toString()); + System.out.println(); + System.out.println("Expected (Yoghurt.toString()): Yoghurt: Vanilla (light yellow 500.0 g)"); + System.out.println("Your code (Yoghurt.toString()): " + vanillaYoghurt.toString()); + System.out.println(); + } +} diff --git a/WS2526/Testat 1a/Testat1A.java b/WS2526/Testat 1a/Testat1A.java new file mode 100644 index 0000000..60759d6 --- /dev/null +++ b/WS2526/Testat 1a/Testat1A.java @@ -0,0 +1,57 @@ +import java.util.Arrays; + +public class Testat1A { + + /** + * Aufgabe 1 + * Die folgende Methode soll für alle Werte des übergebenen Arrays arr, welche + * größer als der Grenzwert threshold sind, den Durchschnitt berechnen. Sollten + * keine Werte größer als der Grenzwert vorhanden sein, soll 0 zurückgegeben + * werden. + * + * HINWEISE: + * Beachten Sie, dass die Division durch 0 zu einem Fehler führt. + * + * Beachten Sie ebenfalls, dass der Array arr auch null sein kann oder leer ist. + * In diesem Fall soll 0 zurückgegeben werden. + */ + + /** + * Returns the average of all values in the array that are above the given + * threshold. + * + * @param arr The input array of integers. + * @param threshold The threshold value. + * @return The average of all values above the threshold, or 0 if none are + * found. + */ + public static double calculateMeanAbove(int[] arr, int threshold) { + // TODO: implement Aufgabe 1 + + } + + /** + * Aufgabe 2 + * Die folgende Methode soll den Durchschnitt für jede Reihe in einem 2D-Array + * berechnen. + * + * HINWEISE: + * Beachten Sie, dass die Division durch 0 zu einem Fehler führt. + * + * Beachten Sie ebenfalls, dass das 2D-Array auch null oder leer sein kann. In + * diesem Fall soll ein leeres Array zurückgegeben werden. Außerdem kann es + * sein, dass eine Reihe null oder leer ist. In diesem Fall soll 0 für diese + * Reihe zurückgegeben werden. + */ + + /** + * Returns the average of all rows in a 2D array. + * + * @param arr The input 2D array of integers. + * @return An array containing the average of each row. + */ + public static double[] calculateRowMean(int[][] arr) { + // TODO: implement Aufgabe 2 + + } +} \ No newline at end of file diff --git a/WS2526/Testat 1a/Tests.java b/WS2526/Testat 1a/Tests.java new file mode 100644 index 0000000..9dcdb92 --- /dev/null +++ b/WS2526/Testat 1a/Tests.java @@ -0,0 +1,671 @@ +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.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]; + testCalculateMeanAbove(arr, 5, 0.0, 5); + } + + @Test(name = "Aufgabe 1 - null array - 5 points") + public void testA1NullArray() { + int[] arr = null; + testCalculateMeanAbove(arr, 42, 0.0, 5); + } + + @Test(name = "Aufgabe 1 - no elements above threshold - 5 points") + public void testA1NoElementsAboveThreshold() { + int[] arr = { -1000000000, 0, 1000, 1000000, 1000000000 }; + testCalculateMeanAbove(arr, Integer.MAX_VALUE, 0.0, 5); + } + + @Test(name = "Aufgabe 1 - all elements above threshold - 5 points") + public void testA1AllElementsAboveThreshold() { + int[] arr = { 10, 20, 30 }; + testCalculateMeanAbove(arr, Integer.MIN_VALUE, 20.0, 5); + } + + @Test(name = "Aufgabe 1 - some elements above threshold - 5 points") + public void testA1SomeElementsAboveThreshold() { + int[] arr = { -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 }; + testCalculateMeanAbove(arr, -2, 2.0, 5); + } + + public void testCalculateMeanAbove(int[] arr, int threshold, double expected, int points) { + double result = Testat1A.calculateMeanAbove(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][]; + testCalculateRowMean(arr, new double[0], 2); + } + + @Test(name = "Aufgabe 2 - null array - 2 points") + public void testA2NullArray() { + int[][] arr = null; + testCalculateRowMean(arr, new double[0], 2); + } + + @Test(name = "Aufgabe 2 - some rows empty - 2 points") + public void testA2SomeRowsEmpty() { + int[][] arr = { {}, {}, { 1, 2, 3 }, {}, {}, { 4, 5, 6 } }; + testCalculateRowMean(arr, new double[] { 0.0, 0.0, 2.0, 0.0, 0.0, 5.0 }, 2); + } + + @Test(name = "Aufgabe 2 - some rows null - 2 points") + public void testA2SomeRowsNull() { + int[][] arr = { null, { 1, 2, 3 }, null, { 4, 5, 6 }, null, null }; + testCalculateRowMean(arr, new double[] { 0.0, 2.0, 0.0, 5.0, 0.0, 0.0 }, 2); + } + + @Test(name = "Aufgabe 2 - unequal row lengths - 3 points") + public void testA2UnequalRowLengths() { + int[][] arr = { { 1, 2, 3 }, { 4, 5 }, { 6 }, { -4, -3, -2, -1 }, { 7, 8, 9, 10 }, { -5, 0, 5 } }; + testCalculateRowMean(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 } }; + testCalculateRowMean(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 } }; + testCalculateRowMean(arr, new double[] { 2.0, 5.0, 8.0 }, 7); + } + + public void testCalculateRowMean(int[][] arr, double[] expected, int points) { + double[] result = Testat1A.calculateRowMean(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 + + class TestItem extends FridgeItem { + public TestItem(double weight, String name, String color) { + super(weight, name, color); + } + } + + @Test(name = "Aufgabe 3a - private fields - 6 points") + public void testA3PrivateFields() { + int points = 9; + points -= testField(FridgeItem.class, "weight", double.class, 2); + points -= testField(FridgeItem.class, "name", String.class, 2); + points -= testField(FridgeItem.class, "color", String.class, 2); + addPoints(points); + } + + @Test(name = "Aufgabe 3b - FridgeItem constructor - 6 points") + public void testA3FridgeItemConstructor() { + int points = 6; + + double weight = 42.314159; + String name = "Foo"; + String color = "Red"; + FridgeItem item = new TestItem(weight, name, color); + + points -= checkConstructorField(FridgeItem.class, "weight", double.class, item, weight, 2); + points -= checkConstructorField(FridgeItem.class, "name", String.class, item, name, 2); + points -= checkConstructorField(FridgeItem.class, "color", String.class, item, color, 2); + + addPoints(points); + } + + @Test(name = "Aufgabe 3c - weightful interface - 8 points") + public void testA3WeightfulInterface() { + int points = 8; + Class clazz = FridgeItem.class; + if (!implementsInterface(clazz, Weightful.class)) { + TracingFramework.printError(String.format("FAIL: Class '%s' does not implement interface '%s'", + clazz.getName(), Weightful.class.getName())); + points = 0; + } else { + double weight = 42.314159; + FridgeItem item = new TestItem(weight, "Foo", "Red"); + Method method = getMethod(clazz, "getWeight"); + if (method == null || !method.getReturnType().equals(double.class)) { + TracingFramework.printError( + String.format("FAIL: Method 'getWeight' not found in class '%s' or has wrong return type", + clazz.getName())); + points = 0; + } else { + try { + double result = (double) method.invoke(item); + if (result != weight) { + TracingFramework.printError(String.format("FAIL: Expected getWeight() to return %f, but got %f", + weight, result)); + points = 0; + } + } catch (IllegalAccessException | InvocationTargetException e) { + TracingFramework + .printError(String.format("FAIL: Could not invoke getWeight() on item of class '%s'", + item.getClass().getName())); + points = 0; + } + } + } + + addPoints(points); + } + + @Test(name = "Aufgabe 3d - FridgeItem toString - 10 points") + public void testA3FridgeItemToString() { + int points = 10; + + if (!overridesMethod(FridgeItem.class, "toString")) { + TracingFramework.printError(String.format("FAIL: Class '%s' does not override method 'toString'", + FridgeItem.class.getName())); + points = 0; + } else { + FridgeItem item = new TestItem(42.314159, "Foo", "Red"); + String expected = "Foo (Red 42.314159 g)"; + points -= testToString(item, expected, 5); + + FridgeItem item2 = new TestItem(100.0, "Milk", "White"); + String expected2 = "Milk (White 100.0 g)"; + points -= testToString(item2, expected2, 5); + } + + addPoints(points); + } + + @Test(name = "Aufgabe 3e - Cheese extends FridgeItem - 5 points") + public void testA3CheeseExtendsFridgeItem() { + int points = 5; + + if (!extendsClass(Cheese.class, FridgeItem.class)) { + TracingFramework.printError(String.format("FAIL: Class '%s' does not extend class '%s'", + Cheese.class.getName(), FridgeItem.class.getName())); + points -= 5; + } else { + Cheese cheese = createInstance(Cheese.class, 42.0, "Test Cheese", "Yellow"); + if (cheese == null) { + TracingFramework.printError(String.format("FAIL: Could not create instance of class '%s'", + Cheese.class.getName())); + points = 0; + } else { + List expectedTraceExcerpt = List.of("TraceableItem", "FridgeItem", "Cheese"); + Method method = getMethod(Cheese.class, "getTrace"); + if (method == null) { + TracingFramework.printError(String.format("FAIL: Method 'getTrace' not found in class '%s'", + Cheese.class.getName())); + points -= 5; + } else { + try { + Object rawTrace = method.invoke(cheese); + List rawList = (List) rawTrace; + List classTrace = rawList.stream() + .filter(StackTraceElement.class::isInstance) + .map(StackTraceElement.class::cast) + .map(StackTraceElement::getClassName) + .collect(Collectors.toList()); + int index = Collections.indexOfSubList(classTrace, expectedTraceExcerpt); + if (index == -1) { + TracingFramework.printError( + String.format( + "FAIL: Cheese does not call super constructor. Creation class trace: %s", + classTrace)); + points -= 2; + } + } catch (IllegalAccessException | InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } + + addPoints(points); + } + + @Test(name = "Aufgabe 3e - Yoghurt extends FridgeItem - 5 points") + public void testA3YoghurtExtendsFridgeItem() { + int points = 5; + + if (!extendsClass(Yoghurt.class, FridgeItem.class)) { + TracingFramework.printError(String.format("FAIL: Class '%s' does not extend class '%s'", + Yoghurt.class.getName(), FridgeItem.class.getName())); + points -= 5; + } else { + Yoghurt yoghurt = createInstance(Yoghurt.class, 42.0, "Test Yoghurt", "White"); + if (yoghurt == null) { + TracingFramework.printError(String.format("FAIL: could not create instance of class '%s'", + Yoghurt.class.getName())); + points = 0; + } else { + List expectedTraceExcerpt = List.of("TraceableItem", "FridgeItem", "Yoghurt"); + Method method = getMethod(Yoghurt.class, "getTrace"); + if (method == null) { + TracingFramework.printError(String.format("FAIL: Method 'getTrace' not found in class '%s'", + Yoghurt.class.getName())); + points -= 5; + } else { + try { + Object rawTrace = method.invoke(yoghurt); + List rawList = (List) rawTrace; + List classTrace = rawList.stream() + .filter(StackTraceElement.class::isInstance) + .map(StackTraceElement.class::cast) + .map(StackTraceElement::getClassName) + .collect(Collectors.toList()); + int index = Collections.indexOfSubList(classTrace, expectedTraceExcerpt); + if (index == -1) { + TracingFramework.printError( + String.format( + "FAIL: Yoghurt does not call super constructor. Creation class trace: %s", + classTrace)); + points -= 2; + } + } catch (IllegalAccessException | InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } + + addPoints(points); + } + + @Test(name = "Aufgabe 3g - Cheese overrides toString - 5 points") + public void testA3CheeseOverridesToString() { + int points = 5; + if (!overridesMethod(Cheese.class, "toString")) { + TracingFramework.printError(String.format("FAIL: Class '%s' does not override method 'toString'", + Cheese.class.getName())); + points = 0; + } else { + Cheese cheese = createInstance(Cheese.class, 100.0, "Cheddar", "Yellow"); + if (cheese == null) { + TracingFramework.printError(String.format("FAIL: Could not create instance of class '%s'", + Cheese.class.getName())); + points = 0; + } else { + String expected = "Cheese: Cheddar (Yellow 100.0 g)"; + points -= testToString(cheese, expected, 5); + } + } + addPoints(points); + } + + @Test(name = "Aufgabe 3g - Yoghurt overrides toString - 5 points") + public void testA3YoghurtOverridesToString() { + int points = 5; + if (!overridesMethod(Yoghurt.class, "toString")) { + TracingFramework.printError(String.format("FAIL: Class '%s' does not override method 'toString'", + Yoghurt.class.getName())); + points = 0; + } else { + Yoghurt yoghurt = createInstance(Yoghurt.class, 200.0, "Greek Yoghurt", "White"); + if (yoghurt == null) { + TracingFramework.printError(String.format("FAIL: Could not create instance of class '%s'", + Yoghurt.class.getName())); + points = 0; + } else { + String expected = "Yoghurt: Greek Yoghurt (White 200.0 g)"; + points -= testToString(yoghurt, 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; + } + } + + /** + * 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 the method with the given name and parameter types from the + * specified class or its superclasses. + * + * @param clazz The class to check. + * @param methodName The name of the method to find. + * @param parameterTypes The parameter types of the method to find. + * @return The method if found, null otherwise. + */ + private static Method getMethod(Class clazz, String methodName, Class... parameterTypes) { + try { + return clazz.getDeclaredMethod(methodName, parameterTypes); + } catch (NoSuchMethodException e) { + return null; + } + } + + /** + * 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); + } +} diff --git a/WS2526/Testat 1a/TraceableItem.java b/WS2526/Testat 1a/TraceableItem.java new file mode 100644 index 0000000..104ad72 --- /dev/null +++ b/WS2526/Testat 1a/TraceableItem.java @@ -0,0 +1,16 @@ +import java.util.ArrayList; +import java.util.List; + +public class TraceableItem { + private List traceElements = new ArrayList<>(); + + public TraceableItem() { + for (StackTraceElement ste : Thread.currentThread().getStackTrace()) { + traceElements.add(ste); + } + } + + public List getTrace() { + return traceElements; + } +} diff --git a/WS2526/Testat 1a/Weightful.java b/WS2526/Testat 1a/Weightful.java new file mode 100644 index 0000000..56c366b --- /dev/null +++ b/WS2526/Testat 1a/Weightful.java @@ -0,0 +1,10 @@ +public interface Weightful { + + /** + * The weight of the object. + * + * @return The weight of the object. + */ + double getWeight(); + +} \ No newline at end of file diff --git a/WS2526/Testat 1a/Yoghurt.java b/WS2526/Testat 1a/Yoghurt.java new file mode 100644 index 0000000..bf79e28 --- /dev/null +++ b/WS2526/Testat 1a/Yoghurt.java @@ -0,0 +1,44 @@ +/** + * Aufgabe 3e + * + * Verändern Sie die Klasse Yoghurt so, dass sie von FridgeItem erbt. + * + * HINWEIS: Machen Sie dies auch für die Klasse Cheese. + */ + +public class Yoghurt { // TODO: change + + /** + * Aufgabe 3f + * + * Fügen Sie der Klasse Yoghurt einen Konstruktor hinzu, der die Variablen + * weight, name und color initialisiert. Geben Sie dafür die Werte an den + * Konstruktor der Superklasse weiter. + * + * Nicht übersehen: Machen Sie dies auch für die Klasse Cheese. + */ + + /** + * Creates a new yoghurt with the weight, name and color. + * + * @param weight The weight. + * @param name The name. + * @param color The color. + */ + // TODO: constructor + + /** + * Aufgabe 3g + * + * Überschreiben Sie die toString() Methode, so dass vor den Wert der + * Implementierung aus der Superklasse noch der Name der Klasse gefolgt von + * einem Doppelpunkt und einem Leerzeichen angefügt wird. D.h. analog zu + * FridgeItem soll die Ausgabe wie folgt aussehen: + * + * Yoghurt: ( g) + * + * Nicht übersehen: Machen Sie dies auch für die Klasse Cheese. + */ + // TODO: toString + +} diff --git a/WS2526/Testat 1a/de/uni_due/s3/jack2/backend/checkers/tracingchecker/framework/TracingFramework.java b/WS2526/Testat 1a/de/uni_due/s3/jack2/backend/checkers/tracingchecker/framework/TracingFramework.java new file mode 100644 index 0000000..580ac59 --- /dev/null +++ b/WS2526/Testat 1a/de/uni_due/s3/jack2/backend/checkers/tracingchecker/framework/TracingFramework.java @@ -0,0 +1,19 @@ +package de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +public class TracingFramework { + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.METHOD) + public static @interface Test { + String name(); + } + + public static void printError(String string) { + System.err.println("ERROR: " + string); + } +}