package aud.exam.prep.tree; import aud.exam.prep.ListProvider; import aud.exam.prep.Pointer; import aud.exam.prep.Tests; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; import java.util.List; import static aud.exam.prep.Tests.CMP; import static org.junit.jupiter.api.Assertions.*; public abstract class OrderedTreeProcessorTest { protected final OrderedTreeProcessor processor; protected OrderedTreeProcessorTest(OrderedTreeProcessor processor) { this.processor = processor; } @Test void testThat_newEmptyTreeWorks() { T t = processor.newEmptyTree(); assertTrue(processor.check(t, CMP)); assertEquals(-1, processor.height(t)); assertTrue(processor.isBalanced(t)); assertEquals(0, processor.numberOfNodes(t)); for (int i = 0; i < 10; i++) { assertEquals(0, processor.numberOfNodesOnLevel(t, i)); } assertIterableEquals(List.of(), processor.iterate(t)); } @ParameterizedTest @ArgumentsSource(ListProvider.class) void testThat_insertAndIterateWork(List list) { T t = asTree(list); list.sort(CMP); assertTrue(processor.check(t, CMP)); assertIterableEquals(list, processor.iterate(t)); } private T asTree(List list) { T t = processor.newEmptyTree(); for (var n : list) { t = processor.insert(t, n, CMP); } return t; } @ParameterizedTest @ArgumentsSource(ListProvider.class) void testThat_maxWorks(List list) { list.add(-1); T t = asTree(list); Integer max = Tests.getMax(list); assertEquals(max, processor.max(t)); } @ParameterizedTest @ArgumentsSource(ListProvider.class) void testThat_secondMaxWorks(List list) { list.add(-1); list.add(-2); T t = asTree(list); Integer max = Tests.getSecondMax(list); assertEquals(max, processor.secondMax(t)); } @ParameterizedTest @ArgumentsSource(ListProvider.class) void testThat_removeOfNonExistsIsFalseAndDoesNotModify(List list) { T t = asTree(list); list.sort(CMP); var p = new Pointer<>(t); assertFalse(processor.remove(p, -1, CMP)); assertFalse(processor.remove(p, 999, CMP)); t = p.deref; assertTrue(processor.check(t, CMP)); assertIterableEquals(list, processor.iterate(t)); } @ParameterizedTest @ArgumentsSource(ListProvider.class) void testThat_removeOfExistsIsTrueAndDoesModify(List list) { T t = asTree(list); list.sort(CMP); while (!list.isEmpty()) { var toRemove = list.get(list.size()/2); list.remove(toRemove); var p = new Pointer<>(t); assertTrue(processor.remove(p, toRemove, CMP)); t = p.deref; assertTrue(processor.check(t, CMP)); assertIterableEquals(list, processor.iterate(t)); } } @ParameterizedTest @ArgumentsSource(ListProvider.class) void printATree(List list) { T t = asTree(list); processor.print(t); } }