Files
Testate/WS2526/Testat 2b/Tests.java
T
2025-09-11 11:21:02 +02:00

800 lines
28 KiB
Java

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 2B";
// Aufgabe 1 - MediaLibrary tests - 50 Punkte
@Test(name = "Aufgabe 1 - MediaLibrary - getDuration - 10 Punkte")
public void testMediaLibraryLasting() {
int points = 10;
if (!implementsInterface(MediaLibrary.class, Lasting.class)) {
points -= 5;
TracingFramework
.printError("MediaLibrary should implement interface Lasting, but does not. Deducting 5 points.");
}
Method method = findMethod(MediaLibrary.class, "getDuration", int.class);
if (method == null) {
points -= 5;
TracingFramework.printError(
"MediaLibrary should implement method getDuration with return type int, but does not. Deducting 5 points.");
} else {
MediaLibrary mediaLibrary = new MediaLibrary(10, 500);
mediaLibrary.addItem(new MediaItem(100, "A", 0));
mediaLibrary.addItem(new MediaItem(100, "B", 0));
mediaLibrary.addItem(new MediaItem(100, "C", 0));
try {
int duration = (int) method.invoke(mediaLibrary);
if (duration != 300) {
points -= 3;
TracingFramework.printError(
"A media library with 3 x 100 min media items should have a duration of 300 min but was "
+ duration);
}
} catch (IllegalAccessException | InvocationTargetException e) {
points -= 3;
TracingFramework.printError("Error invoking getDuration method: " + e.getMessage());
}
}
addPoints(points);
}
@Test(name = "Aufgabe 1 - MediaLibrary - addItem - 15 Punkte")
public void testMediaLibraryAddItem() {
int points = 15;
// initialize media library and items
MediaLibrary mediaLibrary = new MediaLibrary(10, 10);
Series a = new Series(1, "A", 0);
MediaItem[] items = new MediaItem[] {
a, new Series(1, "B", 0), new Series(1, "C", 0)
};
setItems(mediaLibrary, items);
// test for duplicates
// should return false and not add the item
boolean duplicates = mediaLibrary.addItem(a);
if (getItems(mediaLibrary).length == 3) {
if (duplicates) {
points -= 3;
TracingFramework.printError("Note: The media library should return false for duplicates.");
}
} else {
points -= 6;
TracingFramework.printError("The media library does not check for duplicates.");
}
// test for duration exceeding
// should return false and not add the item
setItems(mediaLibrary, new MediaItem[] { a, new Series(1, "B", 0), new Series(1, "C", 0) });
boolean duration = mediaLibrary.addItem(new Series(8, "D", 0));
if (getItems(mediaLibrary).length == 3) {
if (duration) {
points -= 3;
TracingFramework.printError("Note: The media library should return false for exceeded duration.");
}
} else {
points -= 6;
TracingFramework.printError("The media library does not check the duration.");
}
// max duration not actually exceeded
setItems(mediaLibrary, new MediaItem[] { a, new Series(1, "B", 0), new Series(1, "C", 0) });
boolean duration2 = mediaLibrary.addItem(new Series(7, "G", 0));
if (getItems(mediaLibrary).length == 3) {
points -= 3;
TracingFramework
.printError(
"Note: The media library doesn't add an item when it hits exactly the maximum duration.");
}
addPoints(points);
}
private static TraceableMediaLibrary createTraceableMediaLibrary() {
TraceableMediaLibrary mediaLibrary = new TraceableMediaLibrary(10, 10);
setItems(mediaLibrary,
new MediaItem[] { new Series(1, "A", 0), new Series(1, "B", 0), new Series(1, "C", 0),
new Series(1, "A", 0),
new Series(1, "B", 0), new Series(1, "C", 0), new Series(1, "A", 0), new Series(1, "B", 0),
new Series(1, "C", 0) });
return mediaLibrary;
}
private static long countRecursionSteps(TraceableMediaLibrary mediaLibrary) {
List<StackTraceElement> stackTrace = mediaLibrary.getStackTrace();
return stackTrace.stream()
.filter(element -> element.getClassName().equals(MediaLibrary.class.getName())
&& element.getMethodName().equals("lastIndexOf"))
.count();
}
@Test(name = "Aufgabe 1 - MediaLibrary - lastIndexOf - not existing item - 10 Punkte")
public void testMediaLibraryLastIndexOfNotExisting() {
int points = 10;
TraceableMediaLibrary mediaLibrary = createTraceableMediaLibrary();
// test for not existing item
int index = mediaLibrary.lastIndexOf("D", 0);
long recursionSteps = countRecursionSteps(mediaLibrary);
if (recursionSteps == 0) {
points -= 10;
TracingFramework.printError("The media library should use recursion to find the index of an item.");
} else if (index != -1) {
points -= 10;
TracingFramework.printError("The media library should return -1 for not existing items.");
}
addPoints(points);
}
@Test(name = "Aufgabe 1 - MediaLibrary - lastIndexOf - existing item - 5 Punkte")
public void testMediaLibraryLastIndexOfExisting() {
int points = 5;
TraceableMediaLibrary mediaLibrary = createTraceableMediaLibrary();
// test for existing item
int index = mediaLibrary.lastIndexOf("B", 8);
long recursionSteps = countRecursionSteps(mediaLibrary);
if (recursionSteps == 0) {
points -= 5;
TracingFramework
.printError(
"The media library should use recursion to find the index of an item. Deducting 10 points.");
} else if (index != 7) {
points -= 5;
TracingFramework.printError(
"The media library should return the index of the first occurrence of an item. Deducting 10 points.");
}
addPoints(points);
}
@Test(name = "Aufgabe 1 - MediaLibrary - lastIndexOf - shifted start - 10 Punkte")
public void testMediaLibraryLastIndexOfShiftedStart() {
int points = 10;
TraceableMediaLibrary mediaLibrary = createTraceableMediaLibrary();
// test for shifted start
int index = mediaLibrary.lastIndexOf("C", 7);
long recursionSteps = countRecursionSteps(mediaLibrary);
if (recursionSteps == 0) {
points -= 10;
TracingFramework
.printError(
"The media library should use recursion to find the index of an item. Deducting 10 points.");
} else if (index != 5) {
points -= 10;
TracingFramework.printError(
"The media library should return the index of the first occurrence of an item before start index. Deducting 10 points.");
}
addPoints(points);
}
// Aufgabe 2 - Deque tests - 50 Punkte
@Test(name = "Aufgabe 2 - Deque - addFirst - valid values - 10 Punkte")
public void testDequeAddFirst() {
int points = 10;
Deque deque = new Deque();
String[] values = { "A", "B", "C", "D", "E" };
for (String value : values) {
deque.addFirst(value);
String firstValue = peekFirst(deque);
if (!value.equals(firstValue)) {
String firstValueFromFront = peekFirstFromBack(deque);
if (value.equals(firstValueFromFront)) {
points -= 1;
TracingFramework.printError(
"The pointers inside the deque are not set correctly, but the first value is still added properly. Deducting 1 point.");
} else {
points -= 2;
TracingFramework.printError(
"The first value is not added properly. Expected: " + value + ", but got: " + firstValue);
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - addFirst - null value - 3 Punkte")
public void testDequeAddFirstNull() {
int points = 3;
Deque deque = new Deque();
deque.addFirst(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 - addFirst - empty value - 2 Punkte")
public void testDequeAddFirstEmpty() {
int points = 2;
Deque deque = new Deque();
deque.addFirst("");
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 - peekLast - filled deque - 10 Punkte")
public void testDequePeekLastFilled() {
int points = 10;
Deque deque = buildDeque("Das", "kann", "man", "nicht", "raten");
String beforeStudentPeek = peekLast(deque);
String lastValue = deque.peekLast();
if (!"raten".equals(lastValue)) {
points -= 10;
TracingFramework
.printError("The last value should be 'raten', but got: " + lastValue + ". Deducting 10 points.");
} else {
String afterStudentPeek = peekLast(deque);
if (!beforeStudentPeek.equals(afterStudentPeek)) {
points -= 5;
TracingFramework.printError("The peekLast method should not alter the deque. Deducting 5 points.");
}
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - peekLast - empty deque - 5 Punkte")
public void testDequePeekLastEmpty() {
int points = 5;
Deque deque = buildDeque("A", "B", "C", "D", "E");
if (hasInvalidLastPeeking()) {
points -= 5;
TracingFramework.printError(
"The peekLast 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.peekLast();
if (value != null) {
points -= 5;
TracingFramework
.printError("The peekLast method should return null for an empty deque. Deducting 5 points.");
}
}
addPoints(points);
}
private boolean hasInvalidLastPeeking() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
String value = deque.peekLast();
// if value is null, we assume that the return value of peekLast is always null
// without checking would always return null, and therefore granting full points
return value == null;
}
@Test(name = "Aufgabe 2 - Deque - pollFirst - filled deque - 10 Punkte")
public void testDequePollFirstFilled() {
int points = 10;
Deque deque = buildDeque("Das", "kann", "man", "nicht", "raten");
String value = deque.pollFirst();
if (!"Das".equals(value)) {
points -= 5;
TracingFramework.printError(
"The pollFirst method should return 'Das', but got: " + value + ". Deducting 5 points.");
}
value = deque.pollFirst();
if (!"kann".equals(value)) {
points -= 5;
TracingFramework.printError("The pollFirst method should return 'kann', but got: " + value
+ ". Polling should remove the first item. Deducting 5 points.");
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - pollFirst - empty deque - 5 Punkte")
public void testDequePollFirstEmpty() {
int points = 5;
Deque deque = buildDeque("A", "B", "C", "D", "E");
if (hasInvalidFirstPolling()) {
points -= 5;
TracingFramework.printError(
"The pollFirst 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.pollFirst();
if (value != null) {
points -= 5;
TracingFramework
.printError("The pollFirst method should return null for an empty deque. Deducting 5 points.");
}
}
addPoints(points);
}
public boolean hasInvalidFirstPolling() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
String value = deque.pollFirst();
// if value is null, we assume that the return value of pollFirst 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;
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: MediaLibrary helper methods
*/
/**
* Sets the media library items.
*
* @param mediaLibrary The media library.
* @param items The items.
*/
private static void setItems(MediaLibrary mediaLibrary, MediaItem[] items) {
try {
Field f = MediaLibrary.class.getDeclaredField("items");
f.setAccessible(true);
f.set(mediaLibrary, items);
} catch (Exception e) {
TracingFramework.printError("Cannot set media library items (" + e + ").");
}
}
/**
* Returns the media library items via reflection.
*
* @param mediaLibrary The media library.
* @return The media library's items.
*/
private MediaItem[] getItems(MediaLibrary mediaLibrary) {
try {
Field f = MediaLibrary.class.getDeclaredField("items");
f.setAccessible(true);
return (MediaItem[]) f.get(mediaLibrary);
} catch (Exception e) {
TracingFramework.printError("Cannot get media library items (" + e + ").");
return new MediaItem[0];
}
}
/**
* END: MediaLibrary 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) {
throw new RuntimeException("Failed to build deque: " + e.getMessage(), e);
}
}
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 first element of the deque by traversing from the back.
*
* @param deque The deque to peek from.
* @return The value of the first element, or null if the deque is empty.
*/
private String peekFirstFromBack(Deque deque) {
Item first = getFrontFromBack(deque);
return first != null ? first.getValue() : null;
}
/**
* Gets the first item by traversing from the back.
*
* @param deque The deque to get the first item from.
* @return The first item, or null if the deque is empty.
*/
private Item getFrontFromBack(Deque deque) {
Item current = getBack(deque);
while (current != null && current.getPrev() != null) {
current = current.getPrev();
}
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<Integer> 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
* <b>exactly</b> 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<Tests> 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();
}
}
}