repo stringclasses 1k values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 6 values | commit_sha stringclasses 1k values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/caches/LIFOCacheTest.java | src/test/java/com/thealgorithms/datastructures/caches/LIFOCacheTest.java | package com.thealgorithms.datastructures.caches;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
class LIFOCacheTest {
private LIFOCache<String, String> cache;
private Set<String> evictedKeys;
private List<String> evictedValues;
@BeforeEach
void setUp() {
evictedKeys = new HashSet<>();
evictedValues = new ArrayList<>();
cache = new LIFOCache.Builder<String, String>(3)
.defaultTTL(1000)
.evictionListener((k, v) -> {
evictedKeys.add(k);
evictedValues.add(v);
})
.build();
}
@Test
void testPutAndGet() {
cache.put("a", "apple");
Assertions.assertEquals("apple", cache.get("a"));
}
@Test
void testOverwriteValue() {
cache.put("a", "apple");
cache.put("a", "avocado");
Assertions.assertEquals("avocado", cache.get("a"));
}
@Test
void testExpiration() throws InterruptedException {
cache.put("temp", "value", 100);
Thread.sleep(200);
Assertions.assertNull(cache.get("temp"));
Assertions.assertTrue(evictedKeys.contains("temp"));
}
@Test
void testEvictionOnCapacity() {
cache.put("a", "alpha");
cache.put("b", "bravo");
cache.put("c", "charlie");
cache.put("d", "delta");
int size = cache.size();
Assertions.assertEquals(3, size);
Assertions.assertEquals(1, evictedKeys.size());
Assertions.assertEquals(1, evictedValues.size());
Assertions.assertEquals("charlie", evictedValues.getFirst());
}
@Test
void testEvictionListener() {
cache.put("x", "one");
cache.put("y", "two");
cache.put("z", "three");
cache.put("w", "four");
Assertions.assertFalse(evictedKeys.isEmpty());
Assertions.assertFalse(evictedValues.isEmpty());
}
@Test
void testHitsAndMisses() {
cache.put("a", "apple");
Assertions.assertEquals("apple", cache.get("a"));
Assertions.assertNull(cache.get("b"));
Assertions.assertEquals(1, cache.getHits());
Assertions.assertEquals(1, cache.getMisses());
}
@Test
void testSizeExcludesExpired() throws InterruptedException {
cache.put("a", "a", 100);
cache.put("b", "b", 100);
cache.put("c", "c", 100);
Thread.sleep(150);
Assertions.assertEquals(0, cache.size());
}
@Test
void testSizeIncludesFresh() {
cache.put("a", "a", 1000);
cache.put("b", "b", 1000);
cache.put("c", "c", 1000);
Assertions.assertEquals(3, cache.size());
}
@Test
void testToStringDoesNotExposeExpired() throws InterruptedException {
cache.put("live", "alive");
cache.put("dead", "gone", 100);
Thread.sleep(150);
String result = cache.toString();
Assertions.assertTrue(result.contains("live"));
Assertions.assertFalse(result.contains("dead"));
}
@Test
void testNullKeyGetThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.get(null));
}
@Test
void testPutNullKeyThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.put(null, "v"));
}
@Test
void testPutNullValueThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.put("k", null));
}
@Test
void testPutNegativeTTLThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.put("k", "v", -1));
}
@Test
void testBuilderNegativeCapacityThrows() {
Assertions.assertThrows(IllegalArgumentException.class, () -> new LIFOCache.Builder<>(0));
}
@Test
void testBuilderNullEvictionListenerThrows() {
LIFOCache.Builder<String, String> builder = new LIFOCache.Builder<>(1);
Assertions.assertThrows(IllegalArgumentException.class, () -> builder.evictionListener(null));
}
@Test
void testEvictionListenerExceptionDoesNotCrash() {
LIFOCache<String, String> listenerCache = new LIFOCache.Builder<String, String>(1).evictionListener((k, v) -> { throw new RuntimeException("Exception"); }).build();
listenerCache.put("a", "a");
listenerCache.put("b", "b");
Assertions.assertDoesNotThrow(() -> listenerCache.get("a"));
}
@Test
void testTtlZeroThrowsIllegalArgumentException() {
Executable exec = () -> new LIFOCache.Builder<String, String>(3).defaultTTL(-1).build();
Assertions.assertThrows(IllegalArgumentException.class, exec);
}
@Test
void testPeriodicEvictionStrategyEvictsAtInterval() throws InterruptedException {
LIFOCache<String, String> periodicCache = new LIFOCache.Builder<String, String>(10).defaultTTL(50).evictionStrategy(new LIFOCache.PeriodicEvictionStrategy<>(3)).build();
periodicCache.put("x", "1");
Thread.sleep(100);
int ev1 = periodicCache.getEvictionStrategy().onAccess(periodicCache);
int ev2 = periodicCache.getEvictionStrategy().onAccess(periodicCache);
int ev3 = periodicCache.getEvictionStrategy().onAccess(periodicCache);
Assertions.assertEquals(0, ev1);
Assertions.assertEquals(0, ev2);
Assertions.assertEquals(1, ev3, "Eviction should happen on the 3rd access");
Assertions.assertEquals(0, periodicCache.size());
}
@Test
void testPeriodicEvictionStrategyThrowsExceptionIfIntervalLessThanOrEqual0() {
Executable executable = () -> new LIFOCache.Builder<String, String>(10).defaultTTL(50).evictionStrategy(new LIFOCache.PeriodicEvictionStrategy<>(0)).build();
Assertions.assertThrows(IllegalArgumentException.class, executable);
}
@Test
void testImmediateEvictionStrategyStrategyEvictsOnEachCall() throws InterruptedException {
LIFOCache<String, String> immediateEvictionStrategy = new LIFOCache.Builder<String, String>(10).defaultTTL(50).evictionStrategy(new LIFOCache.ImmediateEvictionStrategy<>()).build();
immediateEvictionStrategy.put("x", "1");
Thread.sleep(100);
int evicted = immediateEvictionStrategy.getEvictionStrategy().onAccess(immediateEvictionStrategy);
Assertions.assertEquals(1, evicted);
}
@Test
void testBuilderThrowsExceptionIfEvictionStrategyNull() {
Executable executable = () -> new LIFOCache.Builder<String, String>(10).defaultTTL(50).evictionStrategy(null).build();
Assertions.assertThrows(IllegalArgumentException.class, executable);
}
@Test
void testReturnsCorrectStrategyInstance() {
LIFOCache.EvictionStrategy<String, String> strategy = new LIFOCache.ImmediateEvictionStrategy<>();
LIFOCache<String, String> newCache = new LIFOCache.Builder<String, String>(10).defaultTTL(1000).evictionStrategy(strategy).build();
Assertions.assertSame(strategy, newCache.getEvictionStrategy(), "Returned strategy should be the same instance");
}
@Test
void testDefaultStrategyIsImmediateEvictionStrategy() {
LIFOCache<String, String> newCache = new LIFOCache.Builder<String, String>(5).defaultTTL(1000).build();
Assertions.assertInstanceOf(LIFOCache.ImmediateEvictionStrategy.class, newCache.getEvictionStrategy(), "Default strategy should be ImmediateEvictionStrategyStrategy");
}
@Test
void testGetEvictionStrategyIsNotNull() {
LIFOCache<String, String> newCache = new LIFOCache.Builder<String, String>(5).build();
Assertions.assertNotNull(newCache.getEvictionStrategy(), "Eviction strategy should never be null");
}
@Test
void testRemoveKeyRemovesExistingKey() {
cache.put("A", "Alpha");
cache.put("B", "Beta");
Assertions.assertEquals("Alpha", cache.get("A"));
Assertions.assertEquals("Beta", cache.get("B"));
String removed = cache.removeKey("A");
Assertions.assertEquals("Alpha", removed);
Assertions.assertNull(cache.get("A"));
Assertions.assertEquals(1, cache.size());
}
@Test
void testRemoveKeyReturnsNullIfKeyNotPresent() {
cache.put("X", "X-ray");
Assertions.assertNull(cache.removeKey("NonExistent"));
Assertions.assertEquals(1, cache.size());
}
@Test
void testRemoveKeyHandlesExpiredEntry() throws InterruptedException {
LIFOCache<String, String> expiringCache = new LIFOCache.Builder<String, String>(2).defaultTTL(100).evictionStrategy(new LIFOCache.ImmediateEvictionStrategy<>()).build();
expiringCache.put("T", "Temporary");
Thread.sleep(200);
String removed = expiringCache.removeKey("T");
Assertions.assertEquals("Temporary", removed);
Assertions.assertNull(expiringCache.get("T"));
}
@Test
void testRemoveKeyThrowsIfKeyIsNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> cache.removeKey(null));
}
@Test
void testRemoveKeyTriggersEvictionListener() {
AtomicInteger evictedCount = new AtomicInteger();
LIFOCache<String, String> localCache = new LIFOCache.Builder<String, String>(2).evictionListener((key, value) -> evictedCount.incrementAndGet()).build();
localCache.put("A", "Apple");
localCache.put("B", "Banana");
localCache.removeKey("A");
Assertions.assertEquals(1, evictedCount.get(), "Eviction listener should have been called once");
}
@Test
void testRemoveKeyDoestNotAffectOtherKeys() {
cache.put("A", "Alpha");
cache.put("B", "Beta");
cache.put("C", "Gamma");
cache.removeKey("B");
Assertions.assertEquals("Alpha", cache.get("A"));
Assertions.assertNull(cache.get("B"));
Assertions.assertEquals("Gamma", cache.get("C"));
}
@Test
void testEvictionListenerExceptionDoesNotPropagate() {
LIFOCache<String, String> localCache = new LIFOCache.Builder<String, String>(1).evictionListener((key, value) -> { throw new RuntimeException(); }).build();
localCache.put("A", "Apple");
Assertions.assertDoesNotThrow(() -> localCache.put("B", "Beta"));
}
@Test
void testGetKeysReturnsAllFreshKeys() {
cache.put("A", "Alpha");
cache.put("B", "Beta");
cache.put("G", "Gamma");
Set<String> expectedKeys = Set.of("A", "B", "G");
Assertions.assertEquals(expectedKeys, cache.getAllKeys());
}
@Test
void testGetKeysIgnoresExpiredKeys() throws InterruptedException {
cache.put("A", "Alpha");
cache.put("B", "Beta");
cache.put("G", "Gamma", 100);
Set<String> expectedKeys = Set.of("A", "B");
Thread.sleep(200);
Assertions.assertEquals(expectedKeys, cache.getAllKeys());
}
@Test
void testClearRemovesAllEntries() {
cache.put("A", "Alpha");
cache.put("B", "Beta");
cache.put("G", "Gamma");
cache.clear();
Assertions.assertEquals(0, cache.size());
}
@Test
void testGetExpiredKeyIncrementsMissesCount() throws InterruptedException {
LIFOCache<String, String> localCache = new LIFOCache.Builder<String, String>(3).evictionStrategy(cache -> 0).defaultTTL(10).build();
localCache.put("A", "Alpha");
Thread.sleep(100);
String value = localCache.get("A");
Assertions.assertEquals(1, localCache.getMisses());
Assertions.assertNull(value);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/bloomfilter/BloomFilterTest.java | src/test/java/com/thealgorithms/datastructures/bloomfilter/BloomFilterTest.java | package com.thealgorithms.datastructures.bloomfilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class BloomFilterTest {
private BloomFilter<String> bloomFilter;
@BeforeEach
void setUp() {
bloomFilter = new BloomFilter<>(3, 100);
}
@Test
public void testIntegerContains() {
BloomFilter<Integer> bloomFilter = new BloomFilter<>(3, 10);
bloomFilter.insert(3);
bloomFilter.insert(17);
Assertions.assertTrue(bloomFilter.contains(3));
Assertions.assertTrue(bloomFilter.contains(17));
}
@Test
public void testStringContains() {
bloomFilter.insert("omar");
bloomFilter.insert("mahamid");
Assertions.assertTrue(bloomFilter.contains("omar"));
Assertions.assertTrue(bloomFilter.contains("mahamid"));
}
@Test
void testInsertAndContains() {
bloomFilter.insert("hello");
bloomFilter.insert("world");
Assertions.assertTrue(bloomFilter.contains("hello"));
Assertions.assertTrue(bloomFilter.contains("world"));
Assertions.assertFalse(bloomFilter.contains("java"));
}
@Test
void testFalsePositive() {
bloomFilter.insert("apple");
bloomFilter.insert("banana");
Assertions.assertFalse(bloomFilter.contains("grape"));
Assertions.assertFalse(bloomFilter.contains("orange"));
}
@Test
void testMultipleInsertions() {
for (int i = 0; i < 100; i++) {
bloomFilter.insert("key" + i);
}
for (int i = 0; i < 100; i++) {
Assertions.assertTrue(bloomFilter.contains("key" + i));
}
Assertions.assertFalse(bloomFilter.contains("key" + 200));
}
@Test
void testEmptyFilterContains() {
Assertions.assertFalse(bloomFilter.contains("notInserted"), "Filter should not contain any elements when empty");
Assertions.assertFalse(bloomFilter.contains(null), "Filter should not contain null elements");
}
@Test
void testDifferentTypes() {
BloomFilter<Object> filter = new BloomFilter<>(3, 100);
filter.insert("string");
filter.insert(123);
filter.insert(45.67);
Assertions.assertTrue(filter.contains("string"), "Filter should contain the string 'string'");
Assertions.assertTrue(filter.contains(123), "Filter should contain the integer 123");
Assertions.assertTrue(filter.contains(45.67), "Filter should contain the double 45.67");
Assertions.assertFalse(filter.contains("missing"), "Filter should not contain elements that were not inserted");
}
@Test
void testFalsePositiveAfterInsertions() {
bloomFilter.insert("cat");
bloomFilter.insert("dog");
bloomFilter.insert("fish");
// Checking for an element that was not added
Assertions.assertFalse(bloomFilter.contains("bird"), "Filter should not contain 'bird' which was never inserted");
// To increase chances of false positives, we can add more items
for (int i = 0; i < 100; i++) {
bloomFilter.insert("item" + i);
}
Assertions.assertFalse(bloomFilter.contains("nonexistent"), "Filter should not contain 'nonexistent' which was never inserted");
}
@Test
void testBoundaryConditions() {
BloomFilter<String> filter = new BloomFilter<>(3, 10);
filter.insert("a");
filter.insert("b");
filter.insert("c");
filter.insert("d");
Assertions.assertTrue(filter.contains("a"), "Filter should contain 'a'");
Assertions.assertTrue(filter.contains("b"), "Filter should contain 'b'");
Assertions.assertTrue(filter.contains("c"), "Filter should contain 'c'");
Assertions.assertTrue(filter.contains("d"), "Filter should contain 'd'");
Assertions.assertFalse(filter.contains("e"), "Filter should not contain 'e' which was not inserted");
}
@Test
void testLongDataType() {
BloomFilter<Long> filter = new BloomFilter<>(5, 1000);
Long[] values = {Long.MIN_VALUE, Long.MAX_VALUE};
for (Long value : values) {
filter.insert(value);
}
for (Long value : values) {
Assertions.assertTrue(filter.contains(value), "Filter should contain " + value);
}
}
@Test
void testFloatDataType() {
BloomFilter<Float> filter = new BloomFilter<>(3, 200);
Float[] values = {1.5f, -3.7f, 0.0f, Float.MAX_VALUE, Float.MIN_VALUE};
for (Float value : values) {
filter.insert(value);
}
for (Float value : values) {
Assertions.assertTrue(filter.contains(value), "Filter should contain " + value);
}
Assertions.assertFalse(filter.contains(88.88f), "Filter should not contain uninserted value");
}
@Test
void testBooleanDataType() {
BloomFilter<Boolean> filter = new BloomFilter<>(2, 50);
filter.insert(Boolean.TRUE);
filter.insert(Boolean.FALSE);
Assertions.assertTrue(filter.contains(Boolean.TRUE), "Filter should contain true");
Assertions.assertTrue(filter.contains(Boolean.FALSE), "Filter should contain false");
}
@Test
void testListDataType() {
BloomFilter<List<String>> filter = new BloomFilter<>(4, 200);
List<String> list1 = Arrays.asList("apple", "banana");
List<String> list2 = Arrays.asList("cat", "dog");
List<String> emptyList = new ArrayList<>();
filter.insert(list1);
filter.insert(list2);
filter.insert(emptyList);
Assertions.assertTrue(filter.contains(list1), "Filter should contain list1");
Assertions.assertTrue(filter.contains(list2), "Filter should contain list2");
Assertions.assertTrue(filter.contains(emptyList), "Filter should contain empty list");
Assertions.assertFalse(filter.contains(Arrays.asList("elephant", "tiger")), "Filter should not contain uninserted list");
}
@Test
void testMapDataType() {
BloomFilter<Map<String, Integer>> filter = new BloomFilter<>(3, 150);
Map<String, Integer> map1 = new HashMap<>();
map1.put("key1", 1);
map1.put("key2", 2);
Map<String, Integer> map2 = new HashMap<>();
map2.put("key3", 3);
Map<String, Integer> emptyMap = new HashMap<>();
filter.insert(map1);
filter.insert(map2);
filter.insert(emptyMap);
Assertions.assertTrue(filter.contains(map1), "Filter should contain map1");
Assertions.assertTrue(filter.contains(map2), "Filter should contain map2");
Assertions.assertTrue(filter.contains(emptyMap), "Filter should contain empty map");
}
@Test
void testSetDataType() {
BloomFilter<Set<Integer>> filter = new BloomFilter<>(3, 100);
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3));
Set<Integer> set2 = new HashSet<>(Arrays.asList(4, 5));
Set<Integer> emptySet = new HashSet<>();
filter.insert(set1);
filter.insert(set2);
filter.insert(emptySet);
Assertions.assertTrue(filter.contains(set1), "Filter should contain set1");
Assertions.assertTrue(filter.contains(set2), "Filter should contain set2");
Assertions.assertTrue(filter.contains(emptySet), "Filter should contain empty set");
Assertions.assertFalse(filter.contains(new HashSet<>(Arrays.asList(6, 7, 8))), "Filter should not contain uninserted set");
}
@Test
void testArrayDataType() {
BloomFilter<int[]> filter = new BloomFilter<>(3, 100);
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5};
int[] emptyArray = {};
filter.insert(array1);
filter.insert(array2);
filter.insert(emptyArray);
Assertions.assertTrue(filter.contains(array1), "Filter should contain array1");
Assertions.assertTrue(filter.contains(array2), "Filter should contain array2");
Assertions.assertTrue(filter.contains(emptyArray), "Filter should contain empty array");
Assertions.assertFalse(filter.contains(new int[] {6, 7, 8}), "Filter should not contain different array");
}
@Test
void testSpecialFloatingPointValues() {
BloomFilter<Double> filter = new BloomFilter<>(3, 100);
Double[] specialValues = {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, -0.0, 0.0};
for (Double value : specialValues) {
filter.insert(value);
}
for (Double value : specialValues) {
Assertions.assertTrue(filter.contains(value), "Filter should contain " + value);
}
}
@Test
void testVerySmallBloomFilter() {
BloomFilter<String> smallFilter = new BloomFilter<>(1, 5);
smallFilter.insert("test1");
smallFilter.insert("test2");
Assertions.assertTrue(smallFilter.contains("test1"));
Assertions.assertTrue(smallFilter.contains("test2"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/QuadTreeTest.java | src/test/java/com/thealgorithms/datastructures/trees/QuadTreeTest.java | package com.thealgorithms.datastructures.trees;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class QuadTreeTest {
int quadTreeCapacity = 4;
BoundingBox boundingBox = new BoundingBox(new Point(0, 0), 500);
QuadTree quadTree = new QuadTree(boundingBox, quadTreeCapacity);
@Test
public void testNullPointInsertIntoQuadTree() {
Assertions.assertFalse(quadTree.insert(null));
}
@Test
public void testInsertIntoQuadTree() {
Assertions.assertTrue(quadTree.insert(new Point(10, -10)));
Assertions.assertTrue(quadTree.insert(new Point(-10, 10)));
Assertions.assertTrue(quadTree.insert(new Point(-10, -10)));
Assertions.assertTrue(quadTree.insert(new Point(10, 10)));
Assertions.assertFalse(quadTree.insert(new Point(1050, 1050)));
}
@Test
public void testInsertIntoQuadTreeAndSubDivide() {
Assertions.assertTrue(quadTree.insert(new Point(10, -10)));
Assertions.assertTrue(quadTree.insert(new Point(-10, 10)));
Assertions.assertTrue(quadTree.insert(new Point(-10, -10)));
Assertions.assertTrue(quadTree.insert(new Point(10, 10)));
Assertions.assertTrue(quadTree.insert(new Point(-100, 100)));
Assertions.assertTrue(quadTree.insert(new Point(100, -101)));
Assertions.assertTrue(quadTree.insert(new Point(-100, -100)));
Assertions.assertTrue(quadTree.insert(new Point(100, 100)));
}
@Test
public void testQueryInQuadTree() {
quadTree.insert(new Point(10, -10));
quadTree.insert(new Point(-10, 10));
quadTree.insert(new Point(-10, -10));
quadTree.insert(new Point(10, 10));
quadTree.insert(new Point(-100, 100));
quadTree.insert(new Point(100, -100));
quadTree.insert(new Point(-100, -100));
quadTree.insert(new Point(100, 100));
List<Point> points = quadTree.query(new BoundingBox(new Point(0, 0), 100));
Assertions.assertEquals(8, points.size());
points = quadTree.query(new BoundingBox(new Point(5, 5), 5));
Assertions.assertEquals(1, points.size());
points = quadTree.query(new BoundingBox(new Point(-200, -200), 5));
Assertions.assertEquals(0, points.size());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java | src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* @author Albina Gimaletdinova on 11/01/2023
*/
public class ZigzagTraversalTest {
@Test
public void testRootNull() {
assertEquals(Collections.emptyList(), ZigzagTraversal.traverse(null));
}
@Test
public void testSingleNodeTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {50});
assertEquals(List.of(List.of(50)), ZigzagTraversal.traverse(root));
}
/*
1
/ \
2 3
/\ /\
4 5 6 7
*/
@Test
public void testZigzagTraversalCompleteTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7});
assertEquals(List.of(List.of(1), List.of(3, 2), List.of(4, 5, 6, 7)), ZigzagTraversal.traverse(root));
}
/*
1
/ \
2 3
/\ /\
4 5 6 7
/ \
8 9
*/
@Test
public void testZigzagTraversalDifferentHeight() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9});
assertEquals(List.of(List.of(1), List.of(3, 2), List.of(4, 5, 6, 7), List.of(9, 8)), ZigzagTraversal.traverse(root));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java | src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* @author Albina Gimaletdinova on 12/01/2023
*/
public class SameTreesCheckTest {
@Test
public void testBothRootsAreNull() {
assertTrue(SameTreesCheck.check(null, null));
}
@Test
public void testOneRootIsNull() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {100});
assertFalse(SameTreesCheck.check(root, null));
}
@Test
public void testSingleNodeTreesAreSame() {
final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {100});
final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {100});
assertTrue(SameTreesCheck.check(p, q));
}
/*
1 1
/ \ / \
2 3 2 3
/\ /\ /\ /\
4 5 6 7 4 5 6 7
*/
@Test
public void testSameTreesIsSuccessful() {
final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7});
final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7});
assertTrue(SameTreesCheck.check(p, q));
}
/*
1 1
/ \ / \
2 3 2 3
/\ /\ /\ /
4 5 6 7 4 5 6
*/
@Test
public void testSameTreesFails() {
final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7});
final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6});
assertFalse(SameTreesCheck.check(p, q));
}
/*
1 1
/ \
2 2
*/
@Test
public void testTreesWithDifferentStructure() {
final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {1, 2});
final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {1, null, 2});
assertFalse(SameTreesCheck.check(p, q));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java | src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java | package com.thealgorithms.datastructures.trees;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* @author Albina Gimaletdinova on 20/04/2023
*/
public class BSTFromSortedArrayTest {
@Test
public void testNullArray() {
BinaryTree.Node actualBST = BSTFromSortedArray.createBST(null);
Assertions.assertNull(actualBST);
}
@Test
public void testEmptyArray() {
BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[] {});
Assertions.assertNull(actualBST);
}
@Test
public void testSingleElementArray() {
BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[] {Integer.MIN_VALUE});
Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(actualBST));
}
@Test
public void testCreateBSTFromSmallArray() {
BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[] {1, 2, 3});
Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(actualBST));
}
@Test
public void testCreateBSTFromLongerArray() {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
BinaryTree.Node actualBST = BSTFromSortedArray.createBST(array);
Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(actualBST));
}
@Test
public void testShouldNotCreateBSTFromNonSortedArray() {
int[] array = {10, 2, 3, 4, 5, 6, 7, 8, 9, 1};
BinaryTree.Node actualBST = BSTFromSortedArray.createBST(array);
Assertions.assertFalse(CheckBinaryTreeIsValidBST.isBST(actualBST));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java | src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* @author Albina Gimaletdinova on 17/02/2023
*/
public class PreOrderTraversalTest {
@Test
public void testNullRoot() {
assertEquals(Collections.emptyList(), PreOrderTraversal.recursivePreOrder(null));
assertEquals(Collections.emptyList(), PreOrderTraversal.iterativePreOrder(null));
}
/*
1
/ \
2 3
/\ /\
4 5 6 7
*/
@Test
public void testRecursivePreOrder() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7});
List<Integer> expected = List.of(1, 2, 4, 5, 3, 6, 7);
assertEquals(expected, PreOrderTraversal.recursivePreOrder(root));
assertEquals(expected, PreOrderTraversal.iterativePreOrder(root));
}
/*
5
\
6
\
7
\
8
*/
@Test
public void testRecursivePreOrderNonBalanced() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8});
List<Integer> expected = List.of(5, 6, 7, 8);
assertEquals(expected, PreOrderTraversal.recursivePreOrder(root));
assertEquals(expected, PreOrderTraversal.iterativePreOrder(root));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/TrieTest.java | src/test/java/com/thealgorithms/datastructures/trees/TrieTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TrieTest {
private static final List<String> WORDS = List.of("Apple", "App", "app", "APPLE");
private Trie trie;
@BeforeEach
public void setUp() {
trie = new Trie();
}
@Test
public void testInsertAndSearchBasic() {
String word = "hello";
trie.insert(word);
assertTrue(trie.search(word), "Search should return true for an inserted word.");
}
@Test
public void testSearchNonExistentWord() {
String word = "world";
assertFalse(trie.search(word), "Search should return false for a non-existent word.");
}
@Test
public void testInsertAndSearchMultipleWords() {
String word1 = "cat";
String word2 = "car";
trie.insert(word1);
trie.insert(word2);
assertTrue(trie.search(word1), "Search should return true for an inserted word.");
assertTrue(trie.search(word2), "Search should return true for another inserted word.");
assertFalse(trie.search("dog"), "Search should return false for a word not in the Trie.");
}
@Test
public void testDeleteExistingWord() {
String word = "remove";
trie.insert(word);
assertTrue(trie.delete(word), "Delete should return true for an existing word.");
assertFalse(trie.search(word), "Search should return false after deletion.");
}
@Test
public void testDeleteNonExistentWord() {
String word = "nonexistent";
assertFalse(trie.delete(word), "Delete should return false for a non-existent word.");
}
@Test
public void testInsertAndSearchPrefix() {
String prefix = "pre";
String word = "prefix";
trie.insert(prefix);
trie.insert(word);
assertTrue(trie.search(prefix), "Search should return true for an inserted prefix.");
assertTrue(trie.search(word), "Search should return true for a word with the prefix.");
assertFalse(trie.search("pref"), "Search should return false for a prefix that is not a full word.");
}
@Test
public void testCountWords() {
Trie trie = createTrie();
assertEquals(WORDS.size(), trie.countWords(), "Count words should return the correct number of words.");
}
@Test
public void testStartsWithPrefix() {
Trie trie = createTrie();
assertTrue(trie.startsWithPrefix("App"), "Starts with prefix should return true.");
}
@Test
public void testCountWordsWithPrefix() {
Trie trie = createTrie();
assertEquals(2, trie.countWordsWithPrefix("App"), "Count words with prefix should return 2.");
}
private Trie createTrie() {
Trie trie = new Trie();
WORDS.forEach(trie::insert);
return trie;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java | src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java | package com.thealgorithms.datastructures.trees;
import com.thealgorithms.datastructures.trees.BinaryTree.Node;
import java.util.LinkedList;
import java.util.Queue;
public final class TreeTestUtils {
private TreeTestUtils() {
}
/**
* Creates a binary tree with given values
*
* @param values: Level order representation of tree
* @return Root of a binary tree
*/
public static Node createTree(final Integer[] values) {
if (values == null || values.length == 0 || values[0] == null) {
throw new IllegalArgumentException("Values array should not be empty or null.");
}
final Node root = new Node(values[0]);
final Queue<Node> queue = new LinkedList<>();
queue.add(root);
int end = 1;
while (end < values.length) {
final Node node = queue.remove();
if (values[end] == null) {
node.left = null;
} else {
node.left = new Node(values[end]);
queue.add(node.left);
}
end++;
if (end < values.length) {
if (values[end] == null) {
node.right = null;
} else {
node.right = new Node(values[end]);
queue.add(node.right);
}
}
end++;
}
return root;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java | src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* @author Albina Gimaletdinova on 21/02/2023
*/
public class InorderTraversalTest {
@Test
public void testNullRoot() {
assertEquals(Collections.emptyList(), InorderTraversal.recursiveInorder(null));
assertEquals(Collections.emptyList(), InorderTraversal.iterativeInorder(null));
}
/*
1
/ \
2 3
/\ /\
4 5 6 7
*/
@Test
public void testRecursiveInorder() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7});
List<Integer> expected = List.of(4, 2, 5, 1, 6, 3, 7);
assertEquals(expected, InorderTraversal.recursiveInorder(root));
assertEquals(expected, InorderTraversal.iterativeInorder(root));
}
/*
5
\
6
\
7
\
8
*/
@Test
public void testRecursiveInorderNonBalanced() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8});
List<Integer> expected = List.of(5, 6, 7, 8);
assertEquals(expected, InorderTraversal.recursiveInorder(root));
assertEquals(expected, InorderTraversal.iterativeInorder(root));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java | src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* @author Albina Gimaletdinova on 08/02/2023
*/
public class LevelOrderTraversalTest {
@Test
public void testRootNull() {
assertEquals(Collections.emptyList(), LevelOrderTraversal.traverse(null));
}
@Test
public void testSingleNodeTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {50});
assertEquals(List.of(List.of(50)), LevelOrderTraversal.traverse(root));
}
/*
1
/ \
2 3
/\ /\
4 5 6 7
*/
@Test
public void testLevelOrderTraversalCompleteTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7});
assertEquals(List.of(List.of(1), List.of(2, 3), List.of(4, 5, 6, 7)), LevelOrderTraversal.traverse(root));
}
/*
1
/ \
2 3
/\ /\
4 5 6 7
/ \
8 9
*/
@Test
public void testLevelOrderTraversalDifferentHeight() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9});
assertEquals(List.of(List.of(1), List.of(2, 3), List.of(4, 5, 6, 7), List.of(8, 9)), LevelOrderTraversal.traverse(root));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/BSTIterativeTest.java | src/test/java/com/thealgorithms/datastructures/trees/BSTIterativeTest.java | package com.thealgorithms.datastructures.trees;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* @author Albina Gimaletdinova on 23/04/2023
*/
public class BSTIterativeTest {
@Test
public void testBSTIsCorrectlyConstructedFromOneNode() {
BSTIterative tree = new BSTIterative();
tree.add(6);
Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(tree.getRoot()));
}
@Test
public void testBSTIsCorrectlyCleanedAndEmpty() {
BSTIterative tree = new BSTIterative();
tree.add(6);
tree.remove(6);
tree.add(12);
tree.add(1);
tree.add(2);
tree.remove(1);
tree.remove(2);
tree.remove(12);
Assertions.assertNull(tree.getRoot());
}
@Test
public void testBSTIsCorrectlyCleanedAndNonEmpty() {
BSTIterative tree = new BSTIterative();
tree.add(6);
tree.remove(6);
tree.add(12);
tree.add(1);
tree.add(2);
Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(tree.getRoot()));
}
@Test
public void testBSTIsCorrectlyConstructedFromMultipleNodes() {
BSTIterative tree = new BSTIterative();
tree.add(7);
tree.add(1);
tree.add(5);
tree.add(100);
tree.add(50);
Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(tree.getRoot()));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java | src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* @author Albina Gimaletdinova on 17/02/2023
*/
public class CheckBinaryTreeIsValidBSTTest {
@Test
public void testRootNull() {
assertTrue(CheckBinaryTreeIsValidBST.isBST(null));
}
@Test
public void testOneNode() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {Integer.MIN_VALUE});
assertTrue(CheckBinaryTreeIsValidBST.isBST(root));
}
/*
9
/ \
7 13
/\ / \
3 8 10 20
*/
@Test
public void testBinaryTreeIsBST() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 20});
assertTrue(CheckBinaryTreeIsValidBST.isBST(root));
}
/*
9
/ \
7 13
/\ / \
3 8 10 13 <--- duplicated node
*/
@Test
public void testBinaryTreeWithDuplicatedNodesIsNotBST() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 13});
assertFalse(CheckBinaryTreeIsValidBST.isBST(root));
}
/*
9
/ \
7 13
/\ / \
3 8 10 12 <---- violates BST rule, needs to be more than 13 (parent node)
*/
@Test
public void testBinaryTreeIsNotBST() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 12});
assertFalse(CheckBinaryTreeIsValidBST.isBST(root));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/BoundaryTraversalTest.java | src/test/java/com/thealgorithms/datastructures/trees/BoundaryTraversalTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
*
*/
public class BoundaryTraversalTest {
@Test
public void testNullRoot() {
assertEquals(Collections.emptyList(), BoundaryTraversal.boundaryTraversal(null));
assertEquals(Collections.emptyList(), BoundaryTraversal.iterativeBoundaryTraversal(null));
}
@Test
public void testSingleNodeTree() {
final BinaryTree.Node root = new BinaryTree.Node(1);
List<Integer> expected = List.of(1);
assertEquals(expected, BoundaryTraversal.boundaryTraversal(root));
assertEquals(expected, BoundaryTraversal.iterativeBoundaryTraversal(root));
}
/*
1
/ \
2 3
/ \ / \
4 5 6 7
*/
@Test
public void testCompleteBinaryTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7});
List<Integer> expected = List.of(1, 2, 4, 5, 6, 7, 3);
assertEquals(expected, BoundaryTraversal.boundaryTraversal(root));
assertEquals(expected, BoundaryTraversal.iterativeBoundaryTraversal(root));
}
/*
1
/ \
2 7
/ \
3 8
\ /
4 9
/ \
5 6
/ \
10 11
*/
@Test
public void testBoundaryTraversal() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 7, 3, null, null, 8, null, 4, 9, null, 5, 6, 10, 11});
List<Integer> expected = List.of(1, 2, 3, 4, 5, 6, 10, 11, 9, 8, 7);
assertEquals(expected, BoundaryTraversal.boundaryTraversal(root));
assertEquals(expected, BoundaryTraversal.iterativeBoundaryTraversal(root));
}
/*
1
/
2
/
3
/
4
*/
@Test
public void testLeftSkewedTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, null, 3, null, 4, null});
List<Integer> expected = List.of(1, 2, 3, 4);
assertEquals(expected, BoundaryTraversal.boundaryTraversal(root));
assertEquals(expected, BoundaryTraversal.iterativeBoundaryTraversal(root));
}
/*
5
\
6
\
7
\
8
*/
@Test
public void testRightSkewedTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8});
List<Integer> expected = List.of(5, 6, 7, 8);
assertEquals(expected, BoundaryTraversal.boundaryTraversal(root));
assertEquals(expected, BoundaryTraversal.iterativeBoundaryTraversal(root));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java | src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class KDTreeTest {
KDTree.Point pointOf(int x, int y) {
return new KDTree.Point(new int[] {x, y});
}
@Test
void findMin() {
int[][] coordinates = {
{30, 40},
{5, 25},
{70, 70},
{10, 12},
{50, 30},
{35, 45},
};
KDTree kdTree = new KDTree(coordinates);
assertEquals(5, kdTree.findMin(0).getCoordinate(0));
assertEquals(12, kdTree.findMin(1).getCoordinate(1));
}
@Test
void delete() {
int[][] coordinates = {
{30, 40},
{5, 25},
{70, 70},
{10, 12},
{50, 30},
{35, 45},
};
KDTree kdTree = new KDTree(coordinates);
kdTree.delete(pointOf(30, 40));
assertEquals(35, kdTree.getRoot().getPoint().getCoordinate(0));
assertEquals(45, kdTree.getRoot().getPoint().getCoordinate(1));
}
@Test
void findNearest() {
int[][] coordinates = {
{2, 3},
{5, 4},
{9, 6},
{4, 7},
{8, 1},
{7, 2},
};
KDTree kdTree = new KDTree(coordinates);
assertEquals(pointOf(7, 2), kdTree.findNearest(pointOf(7, 2)));
assertEquals(pointOf(8, 1), kdTree.findNearest(pointOf(8, 1)));
assertEquals(pointOf(2, 3), kdTree.findNearest(pointOf(1, 1)));
assertEquals(pointOf(5, 4), kdTree.findNearest(pointOf(5, 5)));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveGenericTest.java | src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveGenericTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit tests for BSTRecursiveGeneric class.
* Covers insertion, deletion, search, traversal, sorting, and display.
*
* Author: Udaya Krishnan M
* GitHub: https://github.com/UdayaKrishnanM/
*/
class BSTRecursiveGenericTest {
private BSTRecursiveGeneric<Integer> intTree;
private BSTRecursiveGeneric<String> stringTree;
/**
* Initializes test trees before each test.
*/
@BeforeEach
void setUp() {
intTree = new BSTRecursiveGeneric<>();
stringTree = new BSTRecursiveGeneric<>();
}
/**
* Tests insertion and search of integer values.
*/
@Test
void testAddAndFindInteger() {
intTree.add(10);
intTree.add(5);
intTree.add(15);
assertTrue(intTree.find(10));
assertTrue(intTree.find(5));
assertTrue(intTree.find(15));
assertFalse(intTree.find(20));
}
/**
* Tests insertion and search of string values.
*/
@Test
void testAddAndFindString() {
stringTree.add("apple");
stringTree.add("banana");
stringTree.add("cherry");
assertTrue(stringTree.find("banana"));
assertFalse(stringTree.find("date"));
}
/**
* Tests deletion of existing and non-existing elements.
*/
@Test
void testRemoveElements() {
intTree.add(10);
intTree.add(5);
intTree.add(15);
assertTrue(intTree.find(5));
intTree.remove(5);
assertFalse(intTree.find(5));
intTree.remove(100); // non-existent
assertFalse(intTree.find(100));
}
/**
* Tests inorder traversal output.
*/
@Test
void testInorderTraversal() {
intTree.add(20);
intTree.add(10);
intTree.add(30);
intTree.inorder(); // visually verify output
assertTrue(true);
}
/**
* Tests preorder traversal output.
*/
@Test
void testPreorderTraversal() {
intTree.add(20);
intTree.add(10);
intTree.add(30);
intTree.preorder(); // visually verify output
assertTrue(true);
}
/**
* Tests postorder traversal output.
*/
@Test
void testPostorderTraversal() {
intTree.add(20);
intTree.add(10);
intTree.add(30);
intTree.postorder(); // visually verify output
assertTrue(true);
}
/**
* Tests inorderSort returns sorted list.
*/
@Test
void testInorderSort() {
intTree.add(30);
intTree.add(10);
intTree.add(20);
List<Integer> sorted = intTree.inorderSort();
assertEquals(List.of(10, 20, 30), sorted);
}
/**
* Tests prettyDisplay method for visual tree structure.
*/
@Test
void testPrettyDisplay() {
intTree.add(50);
intTree.add(30);
intTree.add(70);
intTree.add(20);
intTree.add(40);
intTree.add(60);
intTree.add(80);
intTree.prettyDisplay(); // visually verify output
assertTrue(true);
}
/**
* Tests edge case: empty tree.
*/
@Test
void testEmptyTree() {
assertFalse(intTree.find(1));
List<Integer> sorted = intTree.inorderSort();
assertTrue(sorted.isEmpty());
}
/**
* Tests edge case: single node tree.
*/
@Test
void testSingleNodeTree() {
intTree.add(42);
assertTrue(intTree.find(42));
intTree.remove(42);
assertFalse(intTree.find(42));
}
/**
* Tests duplicate insertions.
*/
@Test
void testDuplicateInsertions() {
intTree.add(10);
intTree.add(10);
intTree.add(10);
List<Integer> sorted = intTree.inorderSort();
assertEquals(List.of(10), sorted); // assuming duplicates are ignored
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java | src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Given tree is traversed in a 'post-order' way: LEFT -> RIGHT -> ROOT.
*
* @author Albina Gimaletdinova on 21/02/2023
*/
public class PostOrderTraversalTest {
@Test
public void testNullRoot() {
assertEquals(Collections.emptyList(), PostOrderTraversal.recursivePostOrder(null));
assertEquals(Collections.emptyList(), PostOrderTraversal.iterativePostOrder(null));
}
/*
1
/ \
2 3
/\ /\
4 5 6 7
*/
@Test
public void testPostOrder() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7});
List<Integer> expected = List.of(4, 5, 2, 6, 7, 3, 1);
assertEquals(expected, PostOrderTraversal.recursivePostOrder(root));
assertEquals(expected, PostOrderTraversal.iterativePostOrder(root));
}
/*
5
\
6
\
7
\
8
*/
@Test
public void testPostOrderNonBalanced() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8});
List<Integer> expected = List.of(8, 7, 6, 5);
assertEquals(expected, PostOrderTraversal.recursivePostOrder(root));
assertEquals(expected, PostOrderTraversal.iterativePostOrder(root));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java | src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class LazySegmentTreeTest {
@Test
void build() {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
LazySegmentTree lazySegmentTree = new LazySegmentTree(arr);
assertEquals(55, lazySegmentTree.getRoot().getValue());
assertEquals(15, lazySegmentTree.getRoot().getLeft().getValue());
assertEquals(40, lazySegmentTree.getRoot().getRight().getValue());
}
@Test
void update() {
int[] arr = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
LazySegmentTree lazySegmentTree = new LazySegmentTree(arr);
assertEquals(10, lazySegmentTree.getRoot().getValue());
lazySegmentTree.updateRange(0, 2, 1);
assertEquals(12, lazySegmentTree.getRoot().getValue());
lazySegmentTree.updateRange(1, 3, 1);
assertEquals(14, lazySegmentTree.getRoot().getValue());
lazySegmentTree.updateRange(6, 8, 1);
assertEquals(16, lazySegmentTree.getRoot().getValue());
lazySegmentTree.updateRange(3, 9, 1);
assertEquals(22, lazySegmentTree.getRoot().getValue());
}
@Test
void get() {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
LazySegmentTree lazySegmentTree = new LazySegmentTree(arr);
assertEquals(55, lazySegmentTree.getRange(0, 10));
assertEquals(3, lazySegmentTree.getRange(0, 2));
assertEquals(19, lazySegmentTree.getRange(8, 10));
assertEquals(44, lazySegmentTree.getRange(1, 9));
}
@Test
void updateAndGet() {
int[] arr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
LazySegmentTree lazySegmentTree = new LazySegmentTree(arr);
for (int i = 0; i < 10; i++) {
for (int j = i + 1; j < 10; j++) {
lazySegmentTree.updateRange(i, j, 1);
assertEquals(j - i, lazySegmentTree.getRange(i, j));
lazySegmentTree.updateRange(i, j, -1);
assertEquals(0, lazySegmentTree.getRange(i, j));
}
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/TreapTest.java | src/test/java/com/thealgorithms/datastructures/trees/TreapTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;
public class TreapTest {
@Test
public void searchAndFound() {
Treap treap = new Treap();
treap.insert(5);
treap.insert(9);
treap.insert(6);
treap.insert(2);
treap.insert(3);
treap.insert(8);
treap.insert(1);
assertEquals(5, treap.search(5).value);
}
@Test
public void searchAndNotFound() {
Treap treap = new Treap();
treap.insert(5);
treap.insert(9);
treap.insert(6);
treap.insert(2);
treap.insert(3);
treap.insert(8);
treap.insert(1);
assertEquals(null, treap.search(4));
}
@Test
public void lowerBound() {
Treap treap = new Treap();
treap.insert(5);
treap.insert(9);
treap.insert(6);
treap.insert(2);
treap.insert(3);
treap.insert(8);
treap.insert(1);
assertEquals(5, treap.lowerBound(4).value);
}
@Test
public void size() {
Treap treap = new Treap();
treap.insert(5);
treap.insert(9);
treap.insert(6);
treap.insert(2);
treap.insert(3);
treap.insert(8);
treap.insert(1);
assertEquals(7, treap.size());
assertFalse(treap.isEmpty());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/BTreeTest.java | src/test/java/com/thealgorithms/datastructures/trees/BTreeTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
public class BTreeTest {
@Test
public void testInsertSearchDelete() {
BTree bTree = new BTree(3); // Minimum degree t = 3
int[] values = {10, 20, 5, 6, 12, 30, 7, 17};
for (int val : values) {
bTree.insert(val);
}
for (int val : values) {
assertTrue(bTree.search(val), "Should find inserted value: " + val);
}
ArrayList<Integer> traversal = new ArrayList<>();
bTree.traverse(traversal);
assertEquals(Arrays.asList(5, 6, 7, 10, 12, 17, 20, 30), traversal);
bTree.delete(6);
assertFalse(bTree.search(6));
traversal.clear();
bTree.traverse(traversal);
assertEquals(Arrays.asList(5, 7, 10, 12, 17, 20, 30), traversal);
}
@Test
public void testEmptyTreeSearch() {
BTree bTree = new BTree(3);
assertFalse(bTree.search(42), "Search in empty tree should return false.");
}
@Test
public void testDuplicateInsertions() {
BTree bTree = new BTree(3);
bTree.insert(15);
bTree.insert(15); // Attempt duplicate
bTree.insert(15); // Another duplicate
ArrayList<Integer> traversal = new ArrayList<>();
bTree.traverse(traversal);
// Should contain only one 15
long count = traversal.stream().filter(x -> x == 15).count();
assertEquals(1, count, "Duplicate keys should not be inserted.");
}
@Test
public void testDeleteNonExistentKey() {
BTree bTree = new BTree(3);
bTree.insert(10);
bTree.insert(20);
bTree.delete(99); // Doesn't exist
assertTrue(bTree.search(10));
assertTrue(bTree.search(20));
}
@Test
public void testComplexInsertDelete() {
BTree bTree = new BTree(2); // Smaller degree to trigger splits more easily
int[] values = {1, 3, 7, 10, 11, 13, 14, 15, 18, 16, 19, 24, 25, 26, 21, 4, 5, 20, 22, 2, 17, 12, 6};
for (int val : values) {
bTree.insert(val);
}
for (int val : values) {
assertTrue(bTree.search(val));
}
int[] toDelete = {6, 13, 7, 4, 2, 16};
for (int val : toDelete) {
bTree.delete(val);
assertFalse(bTree.search(val));
}
ArrayList<Integer> remaining = new ArrayList<>();
bTree.traverse(remaining);
for (int val : toDelete) {
assertFalse(remaining.contains(val));
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeToStringTest.java | src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeToStringTest.java | package com.thealgorithms.datastructures.trees;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Tests for the BinaryTreeToString class.
*/
public class BinaryTreeToStringTest {
@Test
public void testTreeToStringBasic() {
BinaryTree tree = new BinaryTree();
tree.put(1);
tree.put(2);
tree.put(3);
tree.put(4);
BinaryTreeToString converter = new BinaryTreeToString();
String result = converter.tree2str(tree.getRoot());
// Output will depend on insertion logic of BinaryTree.put()
// which is BST-style, so result = "1()(2()(3()(4)))"
Assertions.assertEquals("1()(2()(3()(4)))", result);
}
@Test
public void testSingleNodeTree() {
BinaryTree tree = new BinaryTree();
tree.put(10);
BinaryTreeToString converter = new BinaryTreeToString();
String result = converter.tree2str(tree.getRoot());
Assertions.assertEquals("10", result);
}
@Test
public void testComplexTreeStructure() {
BinaryTree.Node root = new BinaryTree.Node(10);
root.left = new BinaryTree.Node(5);
root.right = new BinaryTree.Node(20);
root.right.left = new BinaryTree.Node(15);
root.right.right = new BinaryTree.Node(25);
BinaryTreeToString converter = new BinaryTreeToString();
String result = converter.tree2str(root);
Assertions.assertEquals("10(5)(20(15)(25))", result);
}
@Test
public void testNullTree() {
BinaryTreeToString converter = new BinaryTreeToString();
Assertions.assertEquals("", converter.tree2str(null));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/CentroidDecompositionTest.java | src/test/java/com/thealgorithms/datastructures/trees/CentroidDecompositionTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Test cases for CentroidDecomposition
*
* @author lens161
*/
class CentroidDecompositionTest {
@Test
void testSingleNode() {
// Tree with just one node
int[][] edges = {};
CentroidDecomposition.CentroidTree tree = CentroidDecomposition.buildFromEdges(1, edges);
assertEquals(1, tree.size());
assertEquals(0, tree.getRoot());
assertEquals(-1, tree.getParent(0));
}
@Test
void testTwoNodes() {
// Simple tree: 0 - 1
int[][] edges = {{0, 1}};
CentroidDecomposition.CentroidTree tree = CentroidDecomposition.buildFromEdges(2, edges);
assertEquals(2, tree.size());
int root = tree.getRoot();
assertTrue(root == 0 || root == 1, "Root should be either node 0 or 1");
// One node should be root, other should have the root as parent
int nonRoot = (root == 0) ? 1 : 0;
assertEquals(-1, tree.getParent(root));
assertEquals(root, tree.getParent(nonRoot));
}
@Test
void testLinearTree() {
// Linear tree: 0 - 1 - 2 - 3 - 4
int[][] edges = {{0, 1}, {1, 2}, {2, 3}, {3, 4}};
CentroidDecomposition.CentroidTree tree = CentroidDecomposition.buildFromEdges(5, edges);
assertEquals(5, tree.size());
// For a linear tree of 5 nodes, the centroid should be the middle node (node 2)
assertEquals(2, tree.getRoot());
assertEquals(-1, tree.getParent(2));
}
@Test
void testBalancedBinaryTree() {
// Balanced binary tree:
// 0
// / \
// 1 2
// / \
// 3 4
int[][] edges = {{0, 1}, {0, 2}, {1, 3}, {1, 4}};
CentroidDecomposition.CentroidTree tree = CentroidDecomposition.buildFromEdges(5, edges);
assertEquals(5, tree.size());
// Root should be 0 or 1 (both are valid centroids)
int root = tree.getRoot();
assertTrue(root == 0 || root == 1);
assertEquals(-1, tree.getParent(root));
// All nodes should have a parent in centroid tree except root
for (int i = 0; i < 5; i++) {
if (i != root) {
assertTrue(tree.getParent(i) >= 0 && tree.getParent(i) < 5);
}
}
}
@Test
void testStarTree() {
// Star tree: center node 0 connected to 1, 2, 3, 4
int[][] edges = {{0, 1}, {0, 2}, {0, 3}, {0, 4}};
CentroidDecomposition.CentroidTree tree = CentroidDecomposition.buildFromEdges(5, edges);
assertEquals(5, tree.size());
// Center node (0) should be the root
assertEquals(0, tree.getRoot());
// All other nodes should have 0 as parent
for (int i = 1; i < 5; i++) {
assertEquals(0, tree.getParent(i));
}
}
@Test
void testCompleteTree() {
// Complete binary tree of 7 nodes:
// 0
// / \
// 1 2
// / \ / \
// 3 4 5 6
int[][] edges = {{0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6}};
CentroidDecomposition.CentroidTree tree = CentroidDecomposition.buildFromEdges(7, edges);
assertEquals(7, tree.size());
assertEquals(0, tree.getRoot()); // Root should be the center
// Verify all nodes are reachable in centroid tree
boolean[] visited = new boolean[7];
visited[0] = true;
for (int i = 1; i < 7; i++) {
int parent = tree.getParent(i);
assertTrue(parent >= 0 && parent < 7);
assertTrue(visited[parent], "Parent should be processed before child");
visited[i] = true;
}
}
@Test
void testLargerTree() {
// Tree with 10 nodes
int[][] edges = {{0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6}, {3, 7}, {4, 8}, {5, 9}};
CentroidDecomposition.CentroidTree tree = CentroidDecomposition.buildFromEdges(10, edges);
assertEquals(10, tree.size());
int root = tree.getRoot();
assertTrue(root >= 0 && root < 10);
assertEquals(-1, tree.getParent(root));
// Verify centroid tree structure is valid
for (int i = 0; i < 10; i++) {
if (i != root) {
assertTrue(tree.getParent(i) >= -1 && tree.getParent(i) < 10);
}
}
}
@Test
void testPathGraph() {
// Path graph with 8 nodes: 0-1-2-3-4-5-6-7
int[][] edges = {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}};
CentroidDecomposition.CentroidTree tree = CentroidDecomposition.buildFromEdges(8, edges);
assertEquals(8, tree.size());
// For path of 8 nodes, centroid should be around middle
int root = tree.getRoot();
assertTrue(root >= 2 && root <= 5, "Root should be near the middle of path");
}
@Test
void testInvalidEmptyTree() {
assertThrows(IllegalArgumentException.class, () -> { CentroidDecomposition.buildFromEdges(0, new int[][] {}); });
}
@Test
void testInvalidNegativeNodes() {
assertThrows(IllegalArgumentException.class, () -> { CentroidDecomposition.buildFromEdges(-1, new int[][] {}); });
}
@Test
void testInvalidNullEdges() {
assertThrows(IllegalArgumentException.class, () -> { CentroidDecomposition.buildFromEdges(5, null); });
}
@Test
void testInvalidEdgeCount() {
// Tree with n nodes must have n-1 edges
int[][] edges = {{0, 1}, {1, 2}}; // 2 edges for 5 nodes (should be 4)
assertThrows(IllegalArgumentException.class, () -> { CentroidDecomposition.buildFromEdges(5, edges); });
}
@Test
void testInvalidEdgeFormat() {
int[][] edges = {{0, 1, 2}}; // Edge with 3 elements instead of 2
assertThrows(IllegalArgumentException.class, () -> { CentroidDecomposition.buildFromEdges(3, edges); });
}
@Test
void testInvalidNodeInEdge() {
int[][] edges = {{0, 5}}; // Node 5 doesn't exist in tree of size 3
assertThrows(IllegalArgumentException.class, () -> { CentroidDecomposition.buildFromEdges(3, edges); });
}
@Test
void testInvalidNodeQuery() {
int[][] edges = {{0, 1}, {1, 2}};
CentroidDecomposition.CentroidTree tree = CentroidDecomposition.buildFromEdges(3, edges);
assertThrows(IllegalArgumentException.class, () -> { tree.getParent(-1); });
assertThrows(IllegalArgumentException.class, () -> { tree.getParent(5); });
}
@Test
void testToString() {
int[][] edges = {{0, 1}, {1, 2}};
CentroidDecomposition.CentroidTree tree = CentroidDecomposition.buildFromEdges(3, edges);
String result = tree.toString();
assertNotNull(result);
assertTrue(result.contains("Centroid Tree"));
assertTrue(result.contains("Node"));
assertTrue(result.contains("ROOT"));
}
@Test
void testAdjacencyListConstructor() {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < 3; i++) {
adj.add(new ArrayList<>());
}
adj.get(0).add(1);
adj.get(1).add(0);
adj.get(1).add(2);
adj.get(2).add(1);
CentroidDecomposition.CentroidTree tree = new CentroidDecomposition.CentroidTree(adj);
assertEquals(3, tree.size());
assertEquals(1, tree.getRoot());
}
@Test
void testNullAdjacencyList() {
assertThrows(IllegalArgumentException.class, () -> { new CentroidDecomposition.CentroidTree(null); });
}
@Test
void testEmptyAdjacencyList() {
assertThrows(IllegalArgumentException.class, () -> { new CentroidDecomposition.CentroidTree(new ArrayList<>()); });
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java | src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* @author kumanoit on 10/10/22 IST 1:02 AM
*/
public class CheckTreeIsSymmetricTest {
@Test
public void testRootNull() {
assertTrue(CheckTreeIsSymmetric.isSymmetric(null));
}
@Test
public void testSingleNodeTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {100});
assertTrue(CheckTreeIsSymmetric.isSymmetric(root));
}
@Test
public void testSymmetricTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 2, 3, 4, 4, 3});
assertTrue(CheckTreeIsSymmetric.isSymmetric(root));
}
@Test
public void testNonSymmetricTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 2, 3, 5, 4, 3});
assertFalse(CheckTreeIsSymmetric.isSymmetric(root));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java | src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import com.thealgorithms.datastructures.trees.BinaryTree.Node;
import org.junit.jupiter.api.Test;
public class CeilInBinarySearchTreeTest {
@Test
public void testRootNull() {
assertNull(CeilInBinarySearchTree.getCeil(null, 9));
}
@Test
public void testKeyPresentRootIsCeil() {
final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200});
assertEquals(100, CeilInBinarySearchTree.getCeil(root, 100).data);
}
@Test
public void testKeyPresentLeafIsCeil() {
final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200});
assertEquals(10, CeilInBinarySearchTree.getCeil(root, 10).data);
}
@Test
public void testKeyAbsentRootIsCeil() {
final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300});
assertEquals(100, CeilInBinarySearchTree.getCeil(root, 75).data);
}
@Test
public void testKeyAbsentLeafIsCeil() {
final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300});
assertEquals(50, CeilInBinarySearchTree.getCeil(root, 40).data);
}
@Test
public void testKeyAbsentLeftMostNodeIsCeil() {
final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300});
assertEquals(5, CeilInBinarySearchTree.getCeil(root, 1).data);
}
@Test
public void testKeyAbsentCeilIsNull() {
final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300});
assertNull(CeilInBinarySearchTree.getCeil(root, 400));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java | src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java | package com.thealgorithms.datastructures.trees;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the BinaryTree class.
*/
public class BinaryTreeTest {
@Test
public void testInsertAndFind() {
BinaryTree tree = new BinaryTree();
tree.put(3);
tree.put(5);
tree.put(7);
tree.put(9);
tree.put(12);
Assertions.assertNotNull(tree.find(5), "Node with value 5 should exist");
Assertions.assertEquals(5, tree.find(5).data, "Value of the found node should be 5");
Assertions.assertEquals(7, tree.find(7).data, "Value of the found node should be 7");
}
@Test
public void testRemove() {
BinaryTree tree = new BinaryTree();
tree.put(3);
tree.put(5);
tree.put(7);
tree.put(9);
tree.put(12);
tree.remove(3);
tree.remove(5);
tree.remove(7);
Assertions.assertNotNull(tree.getRoot(), "Root should not be null after removals");
if (tree.getRoot() != null) {
Assertions.assertEquals(9, tree.getRoot().data, "Root value should be 9 after removals");
} else {
Assertions.fail("Root should not be null after removals, but it is.");
}
}
@Test
public void testRemoveReturnValue() {
BinaryTree tree = new BinaryTree();
tree.put(3);
tree.put(5);
tree.put(7);
tree.put(9);
tree.put(12);
Assertions.assertTrue(tree.remove(9), "Removing existing node 9 should return true");
Assertions.assertFalse(tree.remove(398745987), "Removing non-existing node should return false");
}
@Test
public void testTraversalMethods() {
BinaryTree tree = new BinaryTree();
tree.put(3);
tree.put(5);
tree.put(7);
tree.put(9);
tree.put(12);
// Testing traversal methods
tree.bfs(tree.getRoot());
tree.inOrder(tree.getRoot());
tree.preOrder(tree.getRoot());
tree.postOrder(tree.getRoot());
Assertions.assertTrue(tree.remove(9), "Removing existing node 9 should return true");
Assertions.assertFalse(tree.remove(398745987), "Removing non-existing node should return false");
Assertions.assertNotNull(tree.getRoot(), "Root should not be null after operations");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java | src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* @author Albina Gimaletdinova on 13/01/2023
*/
public class VerticalOrderTraversalTest {
@Test
public void testRootNull() {
assertEquals(Collections.emptyList(), VerticalOrderTraversal.verticalTraversal(null));
}
@Test
public void testSingleNodeTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {50});
assertEquals(List.of(50), VerticalOrderTraversal.verticalTraversal(root));
}
/*
1
/ \
2 3
/\ /\
4 5 6 7
*/
@Test
public void testVerticalTraversalCompleteTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7});
assertEquals(List.of(4, 2, 1, 5, 6, 3, 7), VerticalOrderTraversal.verticalTraversal(root));
}
/*
1
/ \
2 3
/\ /\
4 5 6 7
/ \
8 9
*/
@Test
public void testVerticalTraversalDifferentHeight() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9});
assertEquals(List.of(4, 2, 8, 1, 5, 6, 3, 9, 7), VerticalOrderTraversal.verticalTraversal(root));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveTest.java | src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveTest.java | package com.thealgorithms.datastructures.trees;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* @author Albina Gimaletdinova on 06/05/2023
*/
public class BSTRecursiveTest {
@Test
public void testBSTIsCorrectlyConstructedFromOneNode() {
BSTRecursive tree = new BSTRecursive();
tree.add(6);
Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(tree.getRoot()));
}
@Test
public void testBSTIsCorrectlyCleanedAndEmpty() {
BSTRecursive tree = new BSTRecursive();
tree.add(6);
tree.remove(6);
tree.add(12);
tree.add(1);
tree.add(2);
tree.remove(1);
tree.remove(2);
tree.remove(12);
Assertions.assertNull(tree.getRoot());
}
@Test
public void testBSTIsCorrectlyCleanedAndNonEmpty() {
BSTRecursive tree = new BSTRecursive();
tree.add(6);
tree.remove(6);
tree.add(12);
tree.add(1);
tree.add(2);
Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(tree.getRoot()));
}
@Test
public void testBSTIsCorrectlyConstructedFromMultipleNodes() {
BSTRecursive tree = new BSTRecursive();
tree.add(7);
tree.add(1);
tree.add(5);
tree.add(100);
tree.add(50);
Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(tree.getRoot()));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/AVLTreeTest.java | src/test/java/com/thealgorithms/datastructures/trees/AVLTreeTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class AVLTreeTest {
private AVLTree avlTree;
@BeforeEach
public void setUp() {
avlTree = new AVLTree();
}
@Test
public void testInsert() {
assertTrue(avlTree.insert(10));
assertTrue(avlTree.insert(20));
assertTrue(avlTree.insert(5));
assertFalse(avlTree.insert(10)); // Duplicate
}
@Test
public void testSearch() {
avlTree.insert(15);
avlTree.insert(25);
assertTrue(avlTree.search(15));
assertFalse(avlTree.search(30)); // Not in the tree
}
@Test
public void testDeleteLeafNode() {
avlTree.insert(10);
avlTree.insert(20);
avlTree.insert(30);
avlTree.delete(30);
assertFalse(avlTree.search(30));
}
@Test
public void testDeleteNodeWithOneChild() {
avlTree.insert(20);
avlTree.insert(10);
avlTree.insert(30);
avlTree.delete(10);
assertFalse(avlTree.search(10));
}
@Test
public void testDeleteNodeWithTwoChildren() {
avlTree.insert(20);
avlTree.insert(10);
avlTree.insert(30);
avlTree.insert(25);
avlTree.delete(20);
assertFalse(avlTree.search(20));
assertTrue(avlTree.search(30));
assertTrue(avlTree.search(25));
}
@Test
public void testReturnBalance() {
avlTree.insert(10);
avlTree.insert(20);
avlTree.insert(5);
List<Integer> balances = avlTree.returnBalance();
assertEquals(3, balances.size()); // There should be 3 nodes
assertEquals(0, balances.get(0)); // Balance for node 5
assertEquals(0, balances.get(1)); // Balance for node 10
assertEquals(0, balances.get(2)); // Balance for node 20
}
@Test
public void testInsertAndRebalance() {
avlTree.insert(30);
avlTree.insert(20);
avlTree.insert(10); // This should cause a right rotation
assertTrue(avlTree.search(20));
assertTrue(avlTree.search(10));
assertTrue(avlTree.search(30));
}
@Test
public void testComplexInsertionAndDeletion() {
avlTree.insert(30);
avlTree.insert(20);
avlTree.insert(10);
avlTree.insert(25);
avlTree.insert(5);
avlTree.insert(15);
avlTree.delete(20); // Test deletion
assertFalse(avlTree.search(20));
assertTrue(avlTree.search(30));
assertTrue(avlTree.search(25));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/SplayTreeTest.java | src/test/java/com/thealgorithms/datastructures/trees/SplayTreeTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class SplayTreeTest {
@ParameterizedTest
@MethodSource("traversalStrategies")
public void testTraversal(SplayTree.TreeTraversal traversal, List<Integer> expected) {
SplayTree tree = createComplexTree();
List<Integer> result = tree.traverse(traversal);
assertEquals(expected, result);
}
@ParameterizedTest
@MethodSource("valuesToTest")
public void testSearch(int value) {
SplayTree tree = createComplexTree();
assertTrue(tree.search(value));
}
@ParameterizedTest
@MethodSource("valuesToTest")
public void testDelete(int value) {
SplayTree tree = createComplexTree();
assertTrue(tree.search(value));
tree.delete(value);
assertFalse(tree.search(value));
}
@ParameterizedTest
@MethodSource("nonExistentValues")
public void testSearchNonExistent(int value) {
SplayTree tree = createComplexTree();
assertFalse(tree.search(value));
}
@ParameterizedTest
@MethodSource("nonExistentValues")
public void testDeleteNonExistent(int value) {
SplayTree tree = createComplexTree();
tree.delete(value);
assertFalse(tree.search(value));
}
@ParameterizedTest
@MethodSource("valuesToTest")
public void testDeleteThrowsExceptionForEmptyTree(int value) {
SplayTree tree = new SplayTree();
assertThrows(SplayTree.EmptyTreeException.class, () -> tree.delete(value));
}
@ParameterizedTest
@MethodSource("valuesToTest")
public void testInsertThrowsExceptionForDuplicateKeys(int value) {
SplayTree tree = createComplexTree();
assertThrows(SplayTree.DuplicateKeyException.class, () -> tree.insert(value));
}
@ParameterizedTest
@MethodSource("valuesToTest")
public void testSearchInEmptyTree(int value) {
SplayTree tree = new SplayTree();
assertFalse(tree.search(value));
}
private static Stream<Object[]> traversalStrategies() {
return Stream.of(new Object[] {SplayTree.IN_ORDER, Arrays.asList(5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90)}, new Object[] {SplayTree.PRE_ORDER, Arrays.asList(15, 5, 10, 80, 70, 45, 25, 20, 35, 30, 40, 55, 50, 65, 60, 75, 90, 85)},
new Object[] {SplayTree.POST_ORDER, Arrays.asList(10, 5, 20, 30, 40, 35, 25, 50, 60, 65, 55, 45, 75, 70, 85, 90, 80, 15)});
}
private static Stream<Integer> valuesToTest() {
return Stream.of(5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90);
}
private static Stream<Integer> nonExistentValues() {
return Stream.of(0, 100, 42, 58);
}
private SplayTree createComplexTree() {
SplayTree tree = new SplayTree();
tree.insert(50);
tree.insert(30);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(20);
tree.insert(80);
tree.insert(10);
tree.insert(25);
tree.insert(35);
tree.insert(45);
tree.insert(55);
tree.insert(65);
tree.insert(75);
tree.insert(85);
tree.insert(5);
tree.insert(90);
tree.insert(15);
return tree;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalancedTest.java | src/test/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalancedTest.java | package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* Test check both implemented ways, iterative and recursive algorithms.
*
* @author Albina Gimaletdinova on 26/06/2023
*/
public class CheckIfBinaryTreeBalancedTest {
@Test
public void testRootNull() {
assertTrue(CheckIfBinaryTreeBalanced.isBalancedRecursive(null));
assertTrue(CheckIfBinaryTreeBalanced.isBalancedIterative(null));
}
@Test
public void testOneNode() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {Integer.MIN_VALUE});
assertTrue(CheckIfBinaryTreeBalanced.isBalancedRecursive(root));
assertTrue(CheckIfBinaryTreeBalanced.isBalancedIterative(root));
}
/*
9 <-- Math.abs(height(left) - height(right)) == 0
/ \
7 13
/\ / \
3 8 10 20
*/
@Test
public void testBinaryTreeIsBalancedEqualSubtreeHeights() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 20});
assertTrue(CheckIfBinaryTreeBalanced.isBalancedRecursive(root));
assertTrue(CheckIfBinaryTreeBalanced.isBalancedIterative(root));
}
/*
9 <-- Math.abs(height(left) - height(right)) == 1
/ \
7 13
/\
3 8
*/
@Test
public void testBinaryTreeIsBalancedWithDifferentHeights() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8});
assertTrue(CheckIfBinaryTreeBalanced.isBalancedRecursive(root));
assertTrue(CheckIfBinaryTreeBalanced.isBalancedIterative(root));
}
/*
9 <-- only left tree exists, Math.abs(height(left) - height(right)) > 1
/
7
/\
3 8
*/
@Test
public void testBinaryTreeNotBalanced() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, null, 3, 8});
assertFalse(CheckIfBinaryTreeBalanced.isBalancedRecursive(root));
assertFalse(CheckIfBinaryTreeBalanced.isBalancedIterative(root));
}
/*
9 <-- Math.abs(height(left) - height(right)) > 1
/ \
7 13
/\
3 8
/
11
*/
@Test
public void testBinaryTreeNotBalancedBecauseLeftTreeNotBalanced() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, null, null, 11});
assertFalse(CheckIfBinaryTreeBalanced.isBalancedRecursive(root));
assertFalse(CheckIfBinaryTreeBalanced.isBalancedIterative(root));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/ThreadedBinaryTreeTest.java | src/test/java/com/thealgorithms/datastructures/trees/ThreadedBinaryTreeTest.java | /*
* TheAlgorithms (https://github.com/TheAlgorithms/Java)
* Author: Shewale41
* This file is licensed under the MIT License.
*/
package com.thealgorithms.datastructures.trees;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Basic tests for ThreadedBinaryTree inorder traversal.
*/
public class ThreadedBinaryTreeTest {
@Test
public void testInorderTraversalSimple() {
ThreadedBinaryTree tree = new ThreadedBinaryTree();
tree.insert(50);
tree.insert(30);
tree.insert(70);
tree.insert(20);
tree.insert(40);
tree.insert(60);
tree.insert(80);
List<Integer> expected = List.of(20, 30, 40, 50, 60, 70, 80);
List<Integer> actual = tree.inorderTraversal();
assertEquals(expected, actual);
}
@Test
public void testInorderWithDuplicates() {
ThreadedBinaryTree tree = new ThreadedBinaryTree();
tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(7); // duplicate
tree.insert(2);
List<Integer> expected = List.of(2, 3, 5, 7, 7);
List<Integer> actual = tree.inorderTraversal();
assertEquals(expected, actual);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java | src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java | package com.thealgorithms.datastructures.trees;
import java.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* @author Albina Gimaletdinova on 14/05/2023
*/
public class CreateBinaryTreeFromInorderPreorderTest {
@Test
public void testOnNullArraysShouldReturnNullTree() {
// when
BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(null, null);
BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(null, null);
// then
Assertions.assertNull(root);
Assertions.assertNull(rootOpt);
}
@Test
public void testOnEmptyArraysShouldCreateNullTree() {
// given
Integer[] preorder = {};
Integer[] inorder = {};
// when
BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder);
BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder);
// then
Assertions.assertNull(root);
Assertions.assertNull(rootOpt);
}
@Test
public void testOnSingleNodeTreeShouldCreateCorrectTree() {
// given
Integer[] preorder = {1};
Integer[] inorder = {1};
// when
BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder);
BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder);
// then
checkTree(preorder, inorder, root);
checkTree(preorder, inorder, rootOpt);
}
@Test
public void testOnRightSkewedTreeShouldCreateCorrectTree() {
// given
Integer[] preorder = {1, 2, 3, 4};
Integer[] inorder = {1, 2, 3, 4};
// when
BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder);
BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder);
// then
checkTree(preorder, inorder, root);
checkTree(preorder, inorder, rootOpt);
}
@Test
public void testOnLeftSkewedTreeShouldCreateCorrectTree() {
// given
Integer[] preorder = {1, 2, 3, 4};
Integer[] inorder = {4, 3, 2, 1};
// when
BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder);
BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder);
// then
checkTree(preorder, inorder, root);
checkTree(preorder, inorder, rootOpt);
}
@Test
public void testOnNormalTreeShouldCreateCorrectTree() {
// given
Integer[] preorder = {3, 9, 20, 15, 7};
Integer[] inorder = {9, 3, 15, 20, 7};
// when
BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder);
BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder);
// then
checkTree(preorder, inorder, root);
checkTree(preorder, inorder, rootOpt);
}
private static void checkTree(Integer[] preorder, Integer[] inorder, BinaryTree.Node root) {
Assertions.assertNotNull(root);
Assertions.assertEquals(PreOrderTraversal.iterativePreOrder(root), Arrays.asList(preorder));
Assertions.assertEquals(InorderTraversal.iterativeInorder(root), Arrays.asList(inorder));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/dynamicarray/DynamicArrayTest.java | src/test/java/com/thealgorithms/datastructures/dynamicarray/DynamicArrayTest.java | package com.thealgorithms.datastructures.dynamicarray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class DynamicArrayTest {
private DynamicArray<String> array;
@BeforeEach
public void setUp() {
array = new DynamicArray<>();
}
@Test
public void testGetElement() {
array.add("Alice");
array.add("Bob");
array.add("Charlie");
array.add("David");
assertEquals("Bob", array.get(1));
}
@Test
public void testGetInvalidIndex() {
assertThrows(IndexOutOfBoundsException.class, () -> array.get(-1));
assertThrows(IndexOutOfBoundsException.class, () -> array.get(10));
assertThrows(IndexOutOfBoundsException.class, () -> array.get(100));
}
@Test
public void testAddElement() {
array.add("Alice");
array.add("Bob");
assertEquals(2, array.getSize());
assertEquals("Alice", array.get(0));
assertEquals("Bob", array.get(1));
}
@Test
public void testAddAndGet() {
array.add("Alice");
array.add("Bob");
assertEquals("Alice", array.get(0));
assertEquals("Bob", array.get(1));
assertThrows(IndexOutOfBoundsException.class, () -> array.get(2));
}
@Test
public void testAddBeyondCapacity() {
for (int i = 0; i < 20; i++) {
array.add("Element " + i);
}
assertEquals(20, array.getSize());
assertEquals("Element 19", array.get(19));
}
@Test
public void testPutElement() {
array.put(5, "Placeholder");
assertEquals(6, array.getSize());
assertEquals("Placeholder", array.get(5));
}
@Test
public void testPutElementBeyondCapacity() {
array.put(20, "FarAway");
assertEquals(21, array.getSize());
assertEquals("FarAway", array.get(20));
}
@Test
public void testPutAndDynamicCapacity() {
array.put(0, "Alice");
array.put(2, "Bob"); // Tests capacity expansion
assertEquals("Alice", array.get(0));
assertEquals("Bob", array.get(2));
assertEquals(3, array.getSize()); // Size should be 3 due to index 2
}
@Test
public void testRemoveElement() {
array.add("Alice");
array.add("Bob");
String removed = array.remove(0);
assertEquals("Alice", removed);
assertEquals(1, array.getSize());
assertEquals("Bob", array.get(0));
}
@Test
public void testRemoveInvalidIndex() {
assertThrows(IndexOutOfBoundsException.class, () -> array.remove(-1));
assertThrows(IndexOutOfBoundsException.class, () -> array.remove(10));
}
@Test
public void testRemoveComplex() {
array.add("Alice");
array.add("Bob");
array.add("Charlie");
assertEquals("Bob", array.remove(1));
assertEquals("Alice", array.get(0));
assertEquals("Charlie", array.get(1));
assertThrows(IndexOutOfBoundsException.class, () -> array.remove(2));
}
@Test
public void testRemoveEdgeCases() {
array.add("Alice");
array.add("Bob");
assertEquals("Alice", array.remove(0));
assertEquals(1, array.getSize());
assertEquals("Bob", array.get(0));
assertEquals("Bob", array.remove(0));
assertTrue(array.isEmpty());
assertThrows(IndexOutOfBoundsException.class, () -> array.get(0));
}
@Test
public void testIsEmpty() {
assertTrue(array.isEmpty());
array.add("Alice");
assertFalse(array.isEmpty());
array.remove(0);
assertTrue(array.isEmpty());
}
@Test
public void testSize() {
DynamicArray<String> array = new DynamicArray<>();
assertEquals(0, array.getSize());
array.add("Alice");
array.add("Bob");
assertEquals(2, array.getSize());
array.remove(0);
assertEquals(1, array.getSize());
}
@Test
public void testToString() {
array.add("Alice");
array.add("Bob");
assertEquals("[Alice, Bob]", array.toString());
}
@Test
public void testIterator() {
array.add("Alice");
array.add("Bob");
String result = array.stream().collect(Collectors.joining(", "));
assertEquals("Alice, Bob", result);
}
@Test
public void testStreamAsString() {
array.add("Alice");
array.add("Bob");
String result = array.stream().collect(Collectors.joining(", "));
assertEquals("Alice, Bob", result);
}
@Test
public void testStream() {
array.add("Alice");
array.add("Bob");
long count = array.stream().count();
assertEquals(2, count);
}
@Test
public void testAddToFullCapacity() {
DynamicArray<String> array = new DynamicArray<>(2);
array.add("Alice");
array.add("Bob");
array.add("Charlie"); // Triggers capacity expansion
assertEquals(3, array.getSize());
assertEquals("Charlie", array.get(2));
}
@Test
public void testPutWithNegativeIndex() {
assertThrows(IndexOutOfBoundsException.class, () -> array.put(-1, "Alice"));
}
@Test
public void testGetWithNegativeIndex() {
assertThrows(IndexOutOfBoundsException.class, () -> array.get(-1));
}
@Test
public void testIteratorConcurrentModification() {
array.add("Alice");
array.add("Bob");
Iterator<String> iterator = array.iterator();
array.add("Charlie"); // Modify during iteration
assertThrows(ConcurrentModificationException.class, iterator::next);
}
@Test
public void testIteratorRemove() {
array.add("Alice");
array.add("Bob");
Iterator<String> iterator = array.iterator();
assertEquals("Alice", iterator.next());
iterator.remove();
assertEquals(1, array.getSize());
assertEquals("Bob", array.get(0));
}
@Test
public void testRemoveBeyondCapacity() {
DynamicArray<String> array = new DynamicArray<>(2);
array.add("Alice");
array.add("Bob");
array.add("Charlie");
array.remove(1);
assertEquals(2, array.getSize());
assertEquals("Alice", array.get(0));
assertEquals("Charlie", array.get(1));
}
@Test
public void testCapacityDoubling() {
DynamicArray<String> array = new DynamicArray<>(1);
array.add("Alice");
array.add("Bob");
array.add("Charlie"); // Ensure capacity expansion is working
assertEquals(3, array.getSize());
assertEquals("Charlie", array.get(2));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/datastructures/bag/BagTest.java | src/test/java/com/thealgorithms/datastructures/bag/BagTest.java | package com.thealgorithms.datastructures.bag;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.thealgorithms.datastructures.bags.Bag;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.Test;
class BagTest {
@Test
void testBagOperations() {
Bag<String> bag = new Bag<>();
assertTrue(bag.isEmpty(), "Bag should be empty initially");
assertEquals(0, bag.size(), "Bag size should be 0 initially");
bag.add("item1");
bag.add("item2");
bag.add("item1"); // adding duplicate item
assertFalse(bag.isEmpty(), "Bag should not be empty after adding elements");
assertEquals(3, bag.size(), "Bag size should be 3 after adding 3 elements");
assertTrue(bag.contains("item1"), "Bag should contain 'item1'");
assertTrue(bag.contains("item2"), "Bag should contain 'item2'");
assertFalse(bag.contains("item3"), "Bag should not contain 'item3'");
assertFalse(bag.contains(null), "Bag should not contain null");
// Test iteration
int count = 0;
for (String item : bag) {
assertTrue(item.equals("item1") || item.equals("item2"), "Item should be either 'item1' or 'item2'");
count++;
}
assertEquals(3, count, "Iterator should traverse all 3 items");
}
@Test
void testBagInitialization() {
Bag<String> bag = new Bag<>();
assertTrue(bag.isEmpty(), "Bag should be empty initially");
assertEquals(0, bag.size(), "Bag size should be 0 initially");
}
@Test
void testAddElements() {
Bag<String> bag = new Bag<>();
bag.add("item1");
bag.add("item2");
bag.add("item1"); // Adding duplicate item
assertFalse(bag.isEmpty(), "Bag should not be empty after adding elements");
assertEquals(3, bag.size(), "Bag size should be 3 after adding 3 elements");
}
@Test
void testContainsMethod() {
Bag<String> bag = new Bag<>();
bag.add("item1");
bag.add("item2");
assertTrue(bag.contains("item1"), "Bag should contain 'item1'");
assertTrue(bag.contains("item2"), "Bag should contain 'item2'");
assertFalse(bag.contains("item3"), "Bag should not contain 'item3'");
assertFalse(bag.contains(null), "Bag should not contain null");
}
@Test
void testContainsAfterAdditions() {
Bag<String> bag = new Bag<>();
bag.add("item1");
bag.add("item2");
assertTrue(bag.contains("item1"), "Bag should contain 'item1' after addition");
assertTrue(bag.contains("item2"), "Bag should contain 'item2' after addition");
}
@Test
void testIterator() {
Bag<String> bag = new Bag<>();
bag.add("item1");
bag.add("item2");
bag.add("item3");
int count = 0;
for (String item : bag) {
assertTrue(item.equals("item1") || item.equals("item2") || item.equals("item3"), "Item should be one of 'item1', 'item2', or 'item3'");
count++;
}
assertEquals(3, count, "Iterator should traverse all 3 items");
}
@Test
void testIteratorEmptyBag() {
Bag<String> bag = new Bag<>();
int count = 0;
for (String ignored : bag) {
org.junit.jupiter.api.Assertions.fail("Iterator should not return any items for an empty bag");
}
assertEquals(0, count, "Iterator should not traverse any items in an empty bag");
}
@Test
void testRemoveMethodThrowsException() {
Bag<String> bag = new Bag<>();
bag.add("item1");
Iterator<String> iterator = bag.iterator();
assertThrows(UnsupportedOperationException.class, iterator::remove, "Remove operation should throw UnsupportedOperationException");
}
@Test
void testMultipleDuplicates() {
Bag<String> bag = new Bag<>();
bag.add("item1");
bag.add("item1");
bag.add("item1"); // Add three duplicates
assertEquals(3, bag.size(), "Bag size should be 3 after adding three duplicates");
assertTrue(bag.contains("item1"), "Bag should contain 'item1'");
}
@Test
void testLargeNumberOfElements() {
Bag<Integer> bag = new Bag<>();
for (int i = 0; i < 1000; i++) {
bag.add(i);
}
assertEquals(1000, bag.size(), "Bag should contain 1000 elements");
}
@Test
void testMixedTypeElements() {
Bag<Object> bag = new Bag<>();
bag.add("string");
bag.add(1);
bag.add(2.0);
assertTrue(bag.contains("string"), "Bag should contain a string");
assertTrue(bag.contains(1), "Bag should contain an integer");
assertTrue(bag.contains(2.0), "Bag should contain a double");
}
@Test
void testIteratorWithDuplicates() {
Bag<String> bag = new Bag<>();
bag.add("item1");
bag.add("item1");
bag.add("item2");
int count = 0;
for (String item : bag) {
assertTrue(item.equals("item1") || item.equals("item2"), "Item should be either 'item1' or 'item2'");
count++;
}
assertEquals(3, count, "Iterator should traverse all 3 items including duplicates");
}
@Test
void testCollectionElements() {
Bag<List<String>> bag = new Bag<>();
List<String> list1 = new ArrayList<>();
list1.add("a");
list1.add("b");
List<String> list2 = new ArrayList<>();
list2.add("c");
List<String> emptyList = new ArrayList<>();
bag.add(list1);
bag.add(list2);
bag.add(emptyList);
bag.add(list1); // Duplicate
assertEquals(4, bag.size(), "Bag should contain 4 list elements");
assertTrue(bag.contains(list1), "Bag should contain list1");
assertTrue(bag.contains(list2), "Bag should contain list2");
assertTrue(bag.contains(emptyList), "Bag should contain empty list");
}
@Test
void testIteratorConsistency() {
Bag<String> bag = new Bag<>();
bag.add("first");
bag.add("second");
bag.add("third");
// Multiple iterations should return same elements
List<String> firstIteration = new ArrayList<>();
for (String item : bag) {
firstIteration.add(item);
}
List<String> secondIteration = new ArrayList<>();
for (String item : bag) {
secondIteration.add(item);
}
assertEquals(firstIteration.size(), secondIteration.size(), "Both iterations should have same size");
assertEquals(3, firstIteration.size(), "First iteration should have 3 elements");
assertEquals(3, secondIteration.size(), "Second iteration should have 3 elements");
}
@Test
void testMultipleIterators() {
Bag<String> bag = new Bag<>();
bag.add("item1");
bag.add("item2");
Iterator<String> iter1 = bag.iterator();
Iterator<String> iter2 = bag.iterator();
assertTrue(iter1.hasNext(), "First iterator should have next element");
assertTrue(iter2.hasNext(), "Second iterator should have next element");
String first1 = iter1.next();
String first2 = iter2.next();
org.junit.jupiter.api.Assertions.assertNotNull(first1, "First iterator should return non-null element");
org.junit.jupiter.api.Assertions.assertNotNull(first2, "Second iterator should return non-null element");
}
@Test
void testIteratorHasNextConsistency() {
Bag<String> bag = new Bag<>();
bag.add("single");
Iterator<String> iter = bag.iterator();
assertTrue(iter.hasNext(), "hasNext should return true");
assertTrue(iter.hasNext(), "hasNext should still return true after multiple calls");
String item = iter.next();
assertEquals("single", item, "Next should return the single item");
assertFalse(iter.hasNext(), "hasNext should return false after consuming element");
assertFalse(iter.hasNext(), "hasNext should still return false");
}
@Test
void testIteratorNextOnEmptyBag() {
Bag<String> bag = new Bag<>();
Iterator<String> iter = bag.iterator();
assertFalse(iter.hasNext(), "hasNext should return false for empty bag");
assertThrows(NoSuchElementException.class, iter::next, "next() should throw NoSuchElementException on empty bag");
}
@Test
void testBagOrderIndependence() {
Bag<String> bag1 = new Bag<>();
Bag<String> bag2 = new Bag<>();
// Add same elements in different order
bag1.add("first");
bag1.add("second");
bag1.add("third");
bag2.add("third");
bag2.add("first");
bag2.add("second");
assertEquals(bag1.size(), bag2.size(), "Bags should have same size");
// Both bags should contain all elements
assertTrue(bag1.contains("first") && bag2.contains("first"));
assertTrue(bag1.contains("second") && bag2.contains("second"));
assertTrue(bag1.contains("third") && bag2.contains("third"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/CountCharTest.java | src/test/java/com/thealgorithms/strings/CountCharTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class CountCharTest {
@ParameterizedTest(name = "\"{0}\" should have {1} non-whitespace characters")
@CsvSource({"'', 0", "' ', 0", "'a', 1", "'abc', 3", "'a b c', 3", "' a b c ', 3", "'\tabc\n', 3", "' a b\tc ', 3", "' 12345 ', 5", "'Hello, World!', 12"})
@DisplayName("Test countCharacters with various inputs")
void testCountCharacters(String input, int expected) {
assertEquals(expected, CountChar.countCharacters(input));
}
@Test
@DisplayName("Test countCharacters with null input")
void testCountCharactersNullInput() {
assertEquals(0, CountChar.countCharacters(null));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/ReverseWordsInStringTest.java | src/test/java/com/thealgorithms/strings/ReverseWordsInStringTest.java | package com.thealgorithms.strings;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class ReverseWordsInStringTest {
@ParameterizedTest
@MethodSource("inputStream")
void numberTests(String expected, String input) {
Assertions.assertEquals(expected, ReverseWordsInString.reverseWordsInString(input));
}
private static Stream<Arguments> inputStream() {
return Stream.of(Arguments.of("blue is Sky", "Sky is blue"), Arguments.of("blue is Sky", "Sky \n is \t \n blue "), Arguments.of("", ""), Arguments.of("", " "), Arguments.of("", "\t"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/WordLadderTest.java | src/test/java/com/thealgorithms/strings/WordLadderTest.java | package com.thealgorithms.strings;
import static java.util.Collections.emptyList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class WordLadderTest {
/**
* Test 1:
* Input: beginWord = "hit", endWord = "cog", wordList =
* ["hot","dot","dog","lot","log","cog"]
* Output: 5
* Explanation: One shortest transformation sequence is
* "hit" -> "hot" -> "dot" -> "dog" -> cog"
* which is 5 words long.
*/
@Test
public void testWordLadder() {
List<String> wordList1 = Arrays.asList("hot", "dot", "dog", "lot", "log", "cog");
assertEquals(WordLadder.ladderLength("hit", "cog", wordList1), 5);
}
/**
* Test 2:
* Input: beginWord = "hit", endWord = "cog", wordList =
* ["hot","dot","dog","lot","log"]
* Output: 0
* Explanation: The endWord "cog" is not in wordList,
* therefore there is no valid transformation sequence.
*/
@Test
public void testWordLadder2() {
List<String> wordList2 = Arrays.asList("hot", "dot", "dog", "lot", "log");
assertEquals(WordLadder.ladderLength("hit", "cog", wordList2), 0);
}
/**
* Test 3:
* Input: beginWord = "hit", endWord = "cog", wordList =
* []
* Output: 0
* Explanation: The wordList is empty (corner case),
* therefore there is no valid transformation sequence.
*/
@Test
public void testWordLadder3() {
List<String> wordList3 = emptyList();
assertEquals(WordLadder.ladderLength("hit", "cog", wordList3), 0);
}
@ParameterizedTest
@CsvSource({"'a', 'c', 'b,c', 2", "'a', 'c', 'a', 0", "'a', 'a', 'a', 0", "'ab', 'cd', 'ad,bd,cd', 3", "'a', 'd', 'b,c,d', 2", "'a', 'd', 'b,c,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,d', 2"})
void testLadderLength(String beginWord, String endWord, String wordListStr, int expectedLength) {
List<String> wordList = List.of(wordListStr.split(","));
int result = WordLadder.ladderLength(beginWord, endWord, wordList);
assertEquals(expectedLength, result);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/MyAtoiTest.java | src/test/java/com/thealgorithms/strings/MyAtoiTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class MyAtoiTest {
@ParameterizedTest
@CsvSource({"'42', 42", "' -42', -42", "'4193 with words', 4193", "'words and 987', 0", "'-91283472332', -2147483648", "'21474836460', 2147483647", "' +123', 123", "'', 0", "' ', 0", "'-2147483648', -2147483648", "'+2147483647', 2147483647", "' -0012a42', -12",
"'9223372036854775808', 2147483647", "'-9223372036854775809', -2147483648", "'3.14159', 3", "' -0012', -12", "' 0000000000012345678', 12345678", "' -0000000000012345678', -12345678", "' +0000000000012345678', 12345678", "'0', 0", "'+0', 0", "'-0', 0"})
void
testMyAtoi(String input, int expected) {
assertEquals(expected, MyAtoi.myAtoi(input));
}
@Test
void testNullInput() {
assertEquals(0, MyAtoi.myAtoi(null));
}
@Test
void testSinglePlus() {
assertEquals(0, MyAtoi.myAtoi("+"));
}
@Test
void testSingleMinus() {
assertEquals(0, MyAtoi.myAtoi("-"));
}
@Test
void testIntegerMinBoundary() {
assertEquals(Integer.MIN_VALUE, MyAtoi.myAtoi("-2147483648"));
}
@Test
void testIntegerMaxBoundary() {
assertEquals(Integer.MAX_VALUE, MyAtoi.myAtoi("2147483647"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/UpperTest.java | src/test/java/com/thealgorithms/strings/UpperTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class UpperTest {
@Test
public void toUpperCase() {
String input1 = "hello world";
String input2 = "hElLo WoRlD";
String input3 = "HELLO WORLD";
assertEquals("HELLO WORLD", Upper.toUpperCase(input1));
assertEquals("HELLO WORLD", Upper.toUpperCase(input2));
assertEquals("HELLO WORLD", Upper.toUpperCase(input3));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/LowerTest.java | src/test/java/com/thealgorithms/strings/LowerTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class LowerTest {
@Test
public void toLowerCase() {
String input1 = "hello world";
String input2 = "HelLO WoRld";
String input3 = "HELLO WORLD";
assertEquals("hello world", Lower.toLowerCase(input1));
assertEquals("hello world", Lower.toLowerCase(input2));
assertEquals("hello world", Lower.toLowerCase(input3));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/CountWordsTest.java | src/test/java/com/thealgorithms/strings/CountWordsTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class CountWordsTest {
@ParameterizedTest
@MethodSource("wordCountTestCases")
void testWordCount(String input, int expectedCount) {
assertEquals(expectedCount, CountWords.wordCount(input));
}
@ParameterizedTest
@MethodSource("secondaryWordCountTestCases")
void testSecondaryWordCount(String input, int expectedCount) {
assertEquals(expectedCount, CountWords.secondaryWordCount(input));
}
private static Stream<Arguments> wordCountTestCases() {
return Stream.of(Arguments.of("", 0), Arguments.of(null, 0), Arguments.of("aaaa bbb cccc", 3), Arguments.of("note extra spaces here", 4), Arguments.of(" a b c d e ", 5));
}
private static Stream<Arguments> secondaryWordCountTestCases() {
return Stream.of(Arguments.of("", 0), Arguments.of(null, 0), Arguments.of("aaaa bbb cccc", 3), Arguments.of("this-is-one-word!", 1), Arguments.of("What, about, this? Hmmm----strange", 4), Arguments.of("word1 word-2 word-3- w?o,r.d.@!@#$&*()<>4", 4));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/PangramTest.java | src/test/java/com/thealgorithms/strings/PangramTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class PangramTest {
@Test
public void testPangram() {
assertTrue(Pangram.isPangram("The quick brown fox jumps over the lazy dog"));
assertFalse(Pangram.isPangram("The quick brown fox jumps over the azy dog")); // L is missing
assertFalse(Pangram.isPangram("+-1234 This string is not alphabetical"));
assertFalse(Pangram.isPangram("\u0000/\\ Invalid characters are alright too"));
assertTrue(Pangram.isPangram2("The quick brown fox jumps over the lazy dog"));
assertFalse(Pangram.isPangram2("The quick brown fox jumps over the azy dog")); // L is missing
assertFalse(Pangram.isPangram2("+-1234 This string is not alphabetical"));
assertFalse(Pangram.isPangram2("\u0000/\\ Invalid characters are alright too"));
assertTrue(Pangram.isPangramUsingSet("The quick brown fox jumps over the lazy dog"));
assertFalse(Pangram.isPangramUsingSet("The quick brown fox jumps over the azy dog")); // L is missing
assertFalse(Pangram.isPangramUsingSet("+-1234 This string is not alphabetical"));
assertFalse(Pangram.isPangramUsingSet("\u0000/\\ Invalid characters are alright too"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/LongestNonRepetitiveSubstringTest.java | src/test/java/com/thealgorithms/strings/LongestNonRepetitiveSubstringTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class LongestNonRepetitiveSubstringTest {
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of("", 0), Arguments.of("a", 1), Arguments.of("abcde", 5), Arguments.of("aaaaa", 1), Arguments.of("abca", 3), Arguments.of("abcdeabc", 5), Arguments.of("a1b2c3", 6), Arguments.of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 62),
Arguments.of("aabb", 2), Arguments.of("abcdefghijabc", 10));
}
@ParameterizedTest
@MethodSource("provideTestCases")
void testLengthOfLongestSubstring(String input, int expectedLength) {
assertEquals(expectedLength, LongestNonRepetitiveSubstring.lengthOfLongestSubstring(input));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/PalindromeTest.java | src/test/java/com/thealgorithms/strings/PalindromeTest.java | package com.thealgorithms.strings;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class PalindromeTest {
private static Stream<TestData> provideTestCases() {
return Stream.of(new TestData(null, true), new TestData("", true), new TestData("aba", true), new TestData("123321", true), new TestData("kayak", true), new TestData("abb", false), new TestData("abc", false), new TestData("abc123", false), new TestData("kayaks", false));
}
@ParameterizedTest
@MethodSource("provideTestCases")
void testPalindrome(TestData testData) {
Assertions.assertEquals(testData.expected, Palindrome.isPalindrome(testData.input) && Palindrome.isPalindromeRecursion(testData.input) && Palindrome.isPalindromeTwoPointer(testData.input));
}
private record TestData(String input, boolean expected) {
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java | src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class HorspoolSearchTest {
@Test
void testFindFirstMatch() {
int index = HorspoolSearch.findFirst("World", "Hello World");
assertEquals(6, index);
}
@Test
void testFindFirstNotMatch() {
int index = HorspoolSearch.findFirst("hell", "Hello World");
assertEquals(-1, index);
}
@Test
void testFindFirstPatternLongerText() {
int index = HorspoolSearch.findFirst("Hello World!!!", "Hello World");
assertEquals(-1, index);
}
@Test
void testFindFirstPatternEmpty() {
int index = HorspoolSearch.findFirst("", "Hello World");
assertEquals(-1, index);
}
@Test
void testFindFirstTextEmpty() {
int index = HorspoolSearch.findFirst("Hello", "");
assertEquals(-1, index);
}
@Test
void testFindFirstPatternAndTextEmpty() {
int index = HorspoolSearch.findFirst("", "");
assertEquals(-1, index);
}
@Test
void testFindFirstSpecialCharacter() {
int index = HorspoolSearch.findFirst("$3**", "Hello $3**$ World");
assertEquals(6, index);
}
@Test
void testFindFirstInsensitiveMatch() {
int index = HorspoolSearch.findFirstInsensitive("hello", "Hello World");
assertEquals(0, index);
}
@Test
void testFindFirstInsensitiveNotMatch() {
int index = HorspoolSearch.findFirstInsensitive("helo", "Hello World");
assertEquals(-1, index);
}
@Test
void testGetLastComparisons() {
HorspoolSearch.findFirst("World", "Hello World");
int lastSearchNumber = HorspoolSearch.getLastComparisons();
assertEquals(7, lastSearchNumber);
}
@Test
void testGetLastComparisonsNotMatch() {
HorspoolSearch.findFirst("Word", "Hello World");
int lastSearchNumber = HorspoolSearch.getLastComparisons();
assertEquals(3, lastSearchNumber);
}
@Test
void testFindFirstPatternNull() {
assertThrows(NullPointerException.class, () -> HorspoolSearch.findFirst(null, "Hello World"));
}
@Test
void testFindFirstTextNull() {
assertThrows(NullPointerException.class, () -> HorspoolSearch.findFirst("Hello", null));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/LongestCommonPrefixTest.java | src/test/java/com/thealgorithms/strings/LongestCommonPrefixTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class LongestCommonPrefixTest {
@ParameterizedTest(name = "{index} => input={0}, expected=\"{1}\"")
@MethodSource("provideTestCases")
@DisplayName("Test Longest Common Prefix")
void testLongestCommonPrefix(String[] input, String expected) {
assertEquals(expected, LongestCommonPrefix.longestCommonPrefix(input));
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of(new String[] {"flower", "flow", "flight"}, "fl"), Arguments.of(new String[] {"dog", "racecar", "car"}, ""), Arguments.of(new String[] {}, ""), Arguments.of(null, ""), Arguments.of(new String[] {"single"}, "single"), Arguments.of(new String[] {"ab", "a"}, "a"),
Arguments.of(new String[] {"test", "test", "test"}, "test"), Arguments.of(new String[] {"abcde", "abcfgh", "abcmnop"}, "abc"), Arguments.of(new String[] {"Flower", "flow", "flight"}, ""));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/AlphabeticalTest.java | src/test/java/com/thealgorithms/strings/AlphabeticalTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class AlphabeticalTest {
@ParameterizedTest(name = "\"{0}\" → Expected: {1}")
@CsvSource({"'abcdefghijklmno', true", "'abcdxxxyzzzz', true", "'123a', false", "'abcABC', false", "'abcdefghikjlmno', false", "'aBC', true", "'abc', true", "'xyzabc', false", "'abcxyz', true", "'', false", "'1', false"})
void testIsAlphabetical(String input, boolean expected) {
assertEquals(expected, Alphabetical.isAlphabetical(input));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/PermuteStringTest.java | src/test/java/com/thealgorithms/strings/PermuteStringTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class PermuteStringTest {
private static Stream<TestData> provideTestCases() {
return Stream.of(new TestData("ABC", Set.of("ABC", "ACB", "BAC", "BCA", "CAB", "CBA")), new TestData("AB", Set.of("AB", "BA")), new TestData("A", Set.of("A")), new TestData("AA", Set.of("AA")), new TestData("123", Set.of("123", "132", "213", "231", "312", "321")),
new TestData("aA", Set.of("aA", "Aa")), new TestData("AaB", Set.of("AaB", "ABa", "aAB", "aBA", "BAa", "BaA")), new TestData("!@", Set.of("!@", "@!")), new TestData("!a@", Set.of("!a@", "!@a", "a!@", "a@!", "@!a", "@a!")),
new TestData("ABCD", Set.of("ABCD", "ABDC", "ACBD", "ACDB", "ADBC", "ADCB", "BACD", "BADC", "BCAD", "BCDA", "BDAC", "BDCA", "CABD", "CADB", "CBAD", "CBDA", "CDAB", "CDBA", "DABC", "DACB", "DBAC", "DBCA", "DCAB", "DCBA")),
new TestData("A B", Set.of("A B", "AB ", " AB", " BA", "BA ", "B A")),
new TestData("abcd", Set.of("abcd", "abdc", "acbd", "acdb", "adbc", "adcb", "bacd", "badc", "bcad", "bcda", "bdac", "bdca", "cabd", "cadb", "cbad", "cbda", "cdab", "cdba", "dabc", "dacb", "dbac", "dbca", "dcab", "dcba")));
}
@ParameterizedTest
@MethodSource("provideTestCases")
void testPermutations(TestData testData) {
Set<String> actualPermutations = PermuteString.getPermutations(testData.input);
assertEquals(testData.expected, actualPermutations, "The permutations of '" + testData.input + "' are not correct.");
}
record TestData(String input, Set<String> expected) {
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/CharactersSameTest.java | src/test/java/com/thealgorithms/strings/CharactersSameTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class CharactersSameTest {
@ParameterizedTest
@CsvSource({"aaa, true", "abc, false", "'1 1 1 1', false", "111, true", "'', true", "' ', true", "'. ', false", "'a', true", "' ', true", "'ab', false", "'11111', true", "'ababab', false", "' ', true", "'+++', true"})
void testIsAllCharactersSame(String input, boolean expected) {
assertEquals(CharactersSame.isAllCharactersSame(input), expected);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/ReturnSubsequenceTest.java | src/test/java/com/thealgorithms/strings/ReturnSubsequenceTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class ReturnSubsequenceTest {
@ParameterizedTest
@MethodSource("provideTestCases")
void testSubsequences(String input, String[] expected) {
String[] actual = ReturnSubsequence.getSubsequences(input);
assertArrayEquals(expected, actual);
}
static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of("", new String[] {""}), Arguments.of("a", new String[] {"", "a"}), Arguments.of("ab", new String[] {"", "b", "a", "ab"}), Arguments.of("abc", new String[] {"", "c", "b", "bc", "a", "ac", "ab", "abc"}),
Arguments.of("aab", new String[] {"", "b", "a", "ab", "a", "ab", "aa", "aab"}));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/AnagramsTest.java | src/test/java/com/thealgorithms/strings/AnagramsTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class AnagramsTest {
record AnagramTestCase(String input1, String input2, boolean expected) {
}
private static Stream<AnagramTestCase> anagramTestData() {
return Stream.of(new AnagramTestCase("late", "tale", true), new AnagramTestCase("late", "teal", true), new AnagramTestCase("listen", "silent", true), new AnagramTestCase("hello", "olelh", true), new AnagramTestCase("hello", "world", false), new AnagramTestCase("deal", "lead", true),
new AnagramTestCase("binary", "brainy", true), new AnagramTestCase("adobe", "abode", true), new AnagramTestCase("cat", "act", true), new AnagramTestCase("cat", "cut", false), new AnagramTestCase("Listen", "Silent", true), new AnagramTestCase("Dormitory", "DirtyRoom", true),
new AnagramTestCase("Schoolmaster", "TheClassroom", true), new AnagramTestCase("Astronomer", "MoonStarer", true), new AnagramTestCase("Conversation", "VoicesRantOn", true));
}
@ParameterizedTest
@MethodSource("anagramTestData")
void testApproach1(AnagramTestCase testCase) {
assertEquals(testCase.expected(), Anagrams.areAnagramsBySorting(testCase.input1(), testCase.input2()));
}
@ParameterizedTest
@MethodSource("anagramTestData")
void testApproach2(AnagramTestCase testCase) {
assertEquals(testCase.expected(), Anagrams.areAnagramsByCountingChars(testCase.input1(), testCase.input2()));
}
@ParameterizedTest
@MethodSource("anagramTestData")
void testApproach3(AnagramTestCase testCase) {
assertEquals(testCase.expected(), Anagrams.areAnagramsByCountingCharsSingleArray(testCase.input1(), testCase.input2()));
}
@ParameterizedTest
@MethodSource("anagramTestData")
void testApproach4(AnagramTestCase testCase) {
assertEquals(testCase.expected(), Anagrams.areAnagramsUsingHashMap(testCase.input1(), testCase.input2()));
}
@ParameterizedTest
@MethodSource("anagramTestData")
void testApproach5(AnagramTestCase testCase) {
assertEquals(testCase.expected(), Anagrams.areAnagramsBySingleFreqArray(testCase.input1(), testCase.input2()));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/IsogramTest.java | src/test/java/com/thealgorithms/strings/IsogramTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class IsogramTest {
record IsogramTestCase(String input, boolean expected) {
}
private static Stream<IsogramTestCase> isAlphabeticIsogram() {
return Stream.of(
// Valid isograms (only checks letters)
new IsogramTestCase("uncopyrightable", true), new IsogramTestCase("dermatoglyphics", true), new IsogramTestCase("background", true), new IsogramTestCase("python", true), new IsogramTestCase("keyboard", true), new IsogramTestCase("clipboard", true), new IsogramTestCase("flowchart", true),
new IsogramTestCase("bankruptcy", true), new IsogramTestCase("computer", true), new IsogramTestCase("algorithms", true),
// Not isograms - letters repeat
new IsogramTestCase("hello", false), new IsogramTestCase("programming", false), new IsogramTestCase("java", false), new IsogramTestCase("coffee", false), new IsogramTestCase("book", false), new IsogramTestCase("letter", false), new IsogramTestCase("mississippi", false),
new IsogramTestCase("google", false),
// Edge cases
new IsogramTestCase("", true), new IsogramTestCase("a", true), new IsogramTestCase("ab", true), new IsogramTestCase("abc", true), new IsogramTestCase("aa", false), new IsogramTestCase("abcdefghijklmnopqrstuvwxyz", true),
// Case insensitive
new IsogramTestCase("Python", true), new IsogramTestCase("BACKGROUND", true), new IsogramTestCase("Hello", false), new IsogramTestCase("PROGRAMMING", false));
}
private static Stream<IsogramTestCase> isFullIsogram() {
return Stream.of(
// Valid isograms (checks all characters)
new IsogramTestCase("uncopyrightable", true), new IsogramTestCase("dermatoglyphics", true), new IsogramTestCase("background", true), new IsogramTestCase("python", true), new IsogramTestCase("keyboard", true), new IsogramTestCase("clipboard", true), new IsogramTestCase("flowchart", true),
new IsogramTestCase("bankruptcy", true), new IsogramTestCase("computer", true), new IsogramTestCase("algorithms", true),
// Not isograms - characters repeat
new IsogramTestCase("hello", false), new IsogramTestCase("programming", false), new IsogramTestCase("java", false), new IsogramTestCase("coffee", false), new IsogramTestCase("book", false), new IsogramTestCase("letter", false), new IsogramTestCase("mississippi", false),
new IsogramTestCase("google", false),
// Edge cases
new IsogramTestCase("", true), new IsogramTestCase("a", true), new IsogramTestCase("ab", true), new IsogramTestCase("abc", true), new IsogramTestCase("aa", false), new IsogramTestCase("abcdefghijklmnopqrstuvwxyz", true),
// Case insensitive
new IsogramTestCase("Python", true), new IsogramTestCase("BACKGROUND", true), new IsogramTestCase("Hello", false), new IsogramTestCase("PROGRAMMING", false),
// Strings with symbols and numbers
new IsogramTestCase("abc@def", true), // all characters unique
new IsogramTestCase("test-case", false), // 't', 's', 'e' repeat
new IsogramTestCase("python123", true), // all characters unique
new IsogramTestCase("hello@123", false), // 'l' repeats
new IsogramTestCase("abc123!@#", true), // all characters unique
new IsogramTestCase("test123test", false), // 't', 'e', 's' repeat
new IsogramTestCase("1234567890", true), // all digits unique
new IsogramTestCase("12321", false), // '1' and '2' repeat
new IsogramTestCase("!@#$%^&*()", true) // all special characters unique
);
}
@ParameterizedTest
@MethodSource("isAlphabeticIsogram")
void testIsogramByArray(IsogramTestCase testCase) {
assertEquals(testCase.expected(), Isogram.isAlphabeticIsogram(testCase.input()));
}
@ParameterizedTest
@MethodSource("isFullIsogram")
void testIsogramByLength(IsogramTestCase testCase) {
assertEquals(testCase.expected(), Isogram.isFullIsogram(testCase.input()));
}
@Test
void testNullInputByArray() {
assertTrue(Isogram.isAlphabeticIsogram(null));
}
@Test
void testNullInputByLength() {
assertTrue(Isogram.isFullIsogram(null));
}
@Test
void testEmptyStringByArray() {
assertTrue(Isogram.isAlphabeticIsogram(""));
}
@Test
void testEmptyStringByLength() {
assertTrue(Isogram.isFullIsogram(""));
}
@Test
void testAlphabeticIsogramThrowsException() {
// Test that IllegalArgumentException is thrown for non-alphabetic characters
assertThrows(IllegalArgumentException.class, () -> Isogram.isAlphabeticIsogram("1"));
assertThrows(IllegalArgumentException.class, () -> Isogram.isAlphabeticIsogram("@"));
assertThrows(IllegalArgumentException.class, () -> Isogram.isAlphabeticIsogram("python!"));
assertThrows(IllegalArgumentException.class, () -> Isogram.isAlphabeticIsogram("123algorithm"));
assertThrows(IllegalArgumentException.class, () -> Isogram.isAlphabeticIsogram("hello123"));
assertThrows(IllegalArgumentException.class, () -> Isogram.isAlphabeticIsogram("!@@#$%^&*()"));
}
@Test
void testFullIsogramWithMixedCharacters() {
// Test that full isogram method handles all character types without exceptions
assertTrue(Isogram.isFullIsogram("abc123"));
assertFalse(Isogram.isFullIsogram("test@email")); // 'e' repeats
assertFalse(Isogram.isFullIsogram("hello123")); // 'l' repeats
assertTrue(Isogram.isFullIsogram("1234567890"));
assertFalse(Isogram.isFullIsogram("12321")); // '1' and '2' repeat
assertTrue(Isogram.isFullIsogram("!@#$%^&*()"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/LengthOfLastWordTest.java | src/test/java/com/thealgorithms/strings/LengthOfLastWordTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class LengthOfLastWordTest {
@Test
public void testLengthOfLastWord() {
assertEquals(5, new LengthOfLastWord().lengthOfLastWord("Hello World"));
assertEquals(4, new LengthOfLastWord().lengthOfLastWord(" fly me to the moon "));
assertEquals(6, new LengthOfLastWord().lengthOfLastWord("luffy is still joyboy"));
assertEquals(5, new LengthOfLastWord().lengthOfLastWord("Hello"));
assertEquals(0, new LengthOfLastWord().lengthOfLastWord(" "));
assertEquals(0, new LengthOfLastWord().lengthOfLastWord(""));
assertEquals(3, new LengthOfLastWord().lengthOfLastWord("JUST LIE "));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/StringCompressionTest.java | src/test/java/com/thealgorithms/strings/StringCompressionTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class StringCompressionTest {
@ParameterizedTest
@CsvSource({"'a', 'a'", "'aabbb', 'a2b3'", "'abbbc', 'ab3c'", "'aabccd', 'a2bc2d'", "'aaaabbbcccc', 'a4b3c4'", "'abcd', 'abcd'", "'aabbccdd', 'a2b2c2d2'", "'aaabbaa', 'a3b2a2'", "'', ''", "'a', 'a'", "'aaaaa', 'a5'", "'aabb', 'a2b2'", "'aabbbaaa', 'a2b3a3'", "'qwerty', 'qwerty'"})
void stringCompressionTest(String input, String expectedOutput) {
String output = StringCompression.compress(input);
assertEquals(expectedOutput, output);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/RotationTest.java | src/test/java/com/thealgorithms/strings/RotationTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class RotationTest {
@Test
public void testRotation() {
assertEquals("eksge", Rotation.rotation("geeks", 2));
assertEquals("anasban", Rotation.rotation("bananas", 3));
assertEquals("abracadabra", Rotation.rotation("abracadabra", 0));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/ReverseStringTest.java | src/test/java/com/thealgorithms/strings/ReverseStringTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
public class ReverseStringTest {
private static Stream<Arguments> testCases() {
return Stream.of(Arguments.of("Hello World", "dlroW olleH"), Arguments.of("helloworld", "dlrowolleh"), Arguments.of("123456789", "987654321"), Arguments.of("", ""), Arguments.of("A", "A"), Arguments.of("ab", "ba"),
Arguments.of(" leading and trailing spaces ", " secaps gniliart dna gnidael "), Arguments.of("!@#$%^&*()", ")(*&^%$#@!"), Arguments.of("MixOf123AndText!", "!txeTdnA321fOxiM"));
}
@ParameterizedTest
@MethodSource("testCases")
public void testReverseString(String input, String expectedOutput) {
assertEquals(expectedOutput, ReverseString.reverse(input));
}
@ParameterizedTest
@MethodSource("testCases")
public void testReverseString2(String input, String expectedOutput) {
assertEquals(expectedOutput, ReverseString.reverse2(input));
}
@ParameterizedTest
@MethodSource("testCases")
public void testReverseString3(String input, String expectedOutput) {
assertEquals(expectedOutput, ReverseString.reverse3(input));
}
@ParameterizedTest
@MethodSource("testCases")
public void testReverseStringUsingStack(String input, String expectedOutput) {
assertEquals(expectedOutput, ReverseString.reverseStringUsingStack(input));
}
@Test
public void testReverseStringUsingStackWithNullInput() {
assertThrows(IllegalArgumentException.class, () -> ReverseString.reverseStringUsingStack(null));
}
@ParameterizedTest
@CsvSource({"'Hello World', 'dlroW olleH'", "'helloworld', 'dlrowolleh'", "'123456789', '987654321'", "'', ''", "'A', 'A'", "'!123 ABC xyz!', '!zyx CBA 321!'", "'Abc 123 Xyz', 'zyX 321 cbA'", "'12.34,56;78:90', '09:87;65,43.21'", "'abcdEFGHiJKL', 'LKJiHGFEdcba'",
"'MixOf123AndText!', '!txeTdnA321fOxiM'"})
public void
testReverseStringUsingRecursion(String input, String expectedOutput) {
assertEquals(expectedOutput, ReverseString.reverseStringUsingRecursion(input));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/StringMatchFiniteAutomataTest.java | src/test/java/com/thealgorithms/strings/StringMatchFiniteAutomataTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class StringMatchFiniteAutomataTest {
@ParameterizedTest
@MethodSource("provideTestCases")
void searchPattern(String text, String pattern, Set<Integer> expectedOutput) {
assertEquals(expectedOutput, StringMatchFiniteAutomata.searchPattern(text, pattern));
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of("abcbcabc", "abc", Set.of(0, 5)), Arguments.of("", "abc", Set.of()), Arguments.of("", "", Set.of()), Arguments.of("a", "b", Set.of()), Arguments.of("a", "a", Set.of(0)), Arguments.of("abcdabcabcabcd", "abcd", Set.of(0, 10)), Arguments.of("abc", "bcd", Set.of()),
Arguments.of("abcdefg", "xyz", Set.of()), Arguments.of("abcde", "", Set.of(1, 2, 3, 4, 5)), Arguments.of("abcabcabc", "abc", Set.of(0, 3, 6)), Arguments.of("abcabcabc", "abcabcabc", Set.of(0)), Arguments.of("aaabbbaaa", "aaa", Set.of(0, 6)), Arguments.of("abcdefg", "efg", Set.of(4)));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java | src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class ValidParenthesesTest {
@ParameterizedTest(name = "Input: \"{0}\" → Expected: {1}")
@CsvSource({"'()', true", "'()[]{}', true", "'(]', false", "'{[]}', true", "'([{}])', true", "'([)]', false", "'', true", "'(', false", "')', false", "'{{{{}}}}', true", "'[({})]', true", "'[(])', false", "'[', false", "']', false", "'()()()()', true", "'(()', false", "'())', false",
"'{[()()]()}', true"})
void
testIsValid(String input, boolean expected) {
assertEquals(expected, ValidParentheses.isValid(input));
}
@Test
void testNullInputThrows() {
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> ValidParentheses.isValid(null));
assertEquals("Input string cannot be null", ex.getMessage());
}
@ParameterizedTest(name = "Input: \"{0}\" → throws IllegalArgumentException")
@CsvSource({"'a'", "'()a'", "'[123]'", "'{hello}'", "'( )'", "'\t'", "'\n'", "'@#$%'"})
void testInvalidCharactersThrow(String input) {
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> ValidParentheses.isValid(input));
assertTrue(ex.getMessage().startsWith("Unexpected character"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/RemoveDuplicateFromStringTest.java | src/test/java/com/thealgorithms/strings/RemoveDuplicateFromStringTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
class RemoveDuplicateFromStringTest {
@Test
void testEmptyString() {
assertEquals("", RemoveDuplicateFromString.removeDuplicate(""));
}
@Test
void testNullString() {
assertNull(RemoveDuplicateFromString.removeDuplicate(null));
}
@Test
void testSingleCharacterString() {
assertEquals("a", RemoveDuplicateFromString.removeDuplicate("a"));
}
@Test
void testStringWithNoDuplicates() {
assertEquals("abc", RemoveDuplicateFromString.removeDuplicate("abc"));
}
@Test
void testStringWithDuplicates() {
assertEquals("abcd", RemoveDuplicateFromString.removeDuplicate("aabbbccccddddd"));
}
@Test
void testStringWithAllSameCharacters() {
assertEquals("a", RemoveDuplicateFromString.removeDuplicate("aaaaa"));
}
@Test
void testStringWithMixedCase() {
assertEquals("abAB", RemoveDuplicateFromString.removeDuplicate("aabABAB"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/AhoCorasickTest.java | src/test/java/com/thealgorithms/strings/AhoCorasickTest.java | /*
* Tests For Aho-Corasick String Matching Algorithm
*
* Author: Prabhat-Kumar-42
* GitHub: https://github.com/Prabhat-Kumar-42
*/
package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* This class contains test cases for the Aho-Corasick String Matching Algorithm.
* The Aho-Corasick algorithm is used to efficiently find all occurrences of multiple
* patterns in a given text.
*/
class AhoCorasickTest {
private String[] patterns; // The array of patterns to search for
private String text; // The input text to search within
/**
* This method sets up the test environment before each test case.
* It initializes the patterns and text to be used for testing.
*/
@BeforeEach
void setUp() {
patterns = new String[] {"ACC", "ATC", "CAT", "GCG", "C", "T"};
text = "GCATCG";
}
/**
* Test searching for multiple patterns in the input text.
* The expected results are defined for each pattern.
*/
@Test
void testSearch() {
// Define the expected results for each pattern
final var expected = Map.of("ACC", new ArrayList<>(List.of()), "ATC", new ArrayList<>(List.of(2)), "CAT", new ArrayList<>(List.of(1)), "GCG", new ArrayList<>(List.of()), "C", new ArrayList<>(List.of(1, 4)), "T", new ArrayList<>(List.of(3)));
assertEquals(expected, AhoCorasick.search(text, patterns));
}
/**
* Test searching with an empty pattern array.
* The result should be an empty map.
*/
@Test
void testEmptyPatterns() {
// Define an empty pattern array
final var emptyPatterns = new String[] {};
assertTrue(AhoCorasick.search(text, emptyPatterns).isEmpty());
}
/**
* Test searching for patterns that are not present in the input text.
* The result should be an empty list for each pattern.
*/
@Test
void testPatternNotFound() {
// Define patterns that are not present in the text
final var searchPatterns = new String[] {"XYZ", "123"};
final var expected = Map.of("XYZ", new ArrayList<Integer>(), "123", new ArrayList<Integer>());
assertEquals(expected, AhoCorasick.search(text, searchPatterns));
}
/**
* Test searching for patterns that start at the beginning of the input text.
* The expected position for each pattern is 0.
*/
@Test
void testPatternAtBeginning() {
// Define patterns that start at the beginning of the text
final var searchPatterns = new String[] {"GC", "GCA", "GCAT"};
final var expected = Map.of("GC", new ArrayList<>(List.of(0)), "GCA", new ArrayList<>(List.of(0)), "GCAT", new ArrayList<>(List.of(0)));
assertEquals(expected, AhoCorasick.search(text, searchPatterns));
}
/**
* Test searching for patterns that end at the end of the input text.
* The expected positions are 4, 3, and 2 for the patterns.
*/
@Test
void testPatternAtEnd() {
// Define patterns that end at the end of the text
final var searchPatterns = new String[] {"CG", "TCG", "ATCG"};
final var expected = Map.of("CG", new ArrayList<>(List.of(4)), "TCG", new ArrayList<>(List.of(3)), "ATCG", new ArrayList<>(List.of(2)));
assertEquals(expected, AhoCorasick.search(text, searchPatterns));
}
/**
* Test searching for patterns with multiple occurrences in the input text.
* The expected sizes are 1 and 1, and the expected positions are 2 and 3
* for the patterns "AT" and "T" respectively.
*/
@Test
void testMultipleOccurrencesOfPattern() {
// Define patterns with multiple occurrences in the text
final var searchPatterns = new String[] {"AT", "T"};
final var expected = Map.of("AT", new ArrayList<>(List.of(2)), "T", new ArrayList<>(List.of(3)));
assertEquals(expected, AhoCorasick.search(text, searchPatterns));
}
/**
* Test searching for patterns in a case-insensitive manner.
* The search should consider patterns regardless of their case.
*/
@Test
void testCaseInsensitiveSearch() {
// Define patterns with different cases
final var searchPatterns = new String[] {"gca", "aTc", "C"};
final var expected = Map.of("gca", new ArrayList<Integer>(), "aTc", new ArrayList<Integer>(), "C", new ArrayList<>(Arrays.asList(1, 4)));
assertEquals(expected, AhoCorasick.search(text, searchPatterns));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/CheckVowelsTest.java | src/test/java/com/thealgorithms/strings/CheckVowelsTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class CheckVowelsTest {
@ParameterizedTest
@CsvSource({"'foo', true", "'bar', true", "'why', false", "'myths', false", "'', false", "'AEIOU', true", "'bcdfghjklmnpqrstvwxyz', false", "'AeIoU', true"})
void testHasVowels(String input, boolean expected) {
assertEquals(CheckVowels.hasVowels(input), expected);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java | src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class LetterCombinationsOfPhoneNumberTest {
@ParameterizedTest
@MethodSource("provideTestCases")
public void testLetterCombinationsOfPhoneNumber(int[] numbers, List<String> expectedOutput) {
assertEquals(expectedOutput, LetterCombinationsOfPhoneNumber.getCombinations(numbers));
}
@ParameterizedTest
@MethodSource("wrongInputs")
void throwsForWrongInput(int[] numbers) {
assertThrows(IllegalArgumentException.class, () -> LetterCombinationsOfPhoneNumber.getCombinations(numbers));
}
private static Stream<Arguments> provideTestCases() {
return Stream.of(Arguments.of(null, List.of("")), Arguments.of(new int[] {}, List.of("")), Arguments.of(new int[] {2}, List.of("a", "b", "c")), Arguments.of(new int[] {2, 3}, List.of("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf")),
Arguments.of(new int[] {2, 3, 4}, List.of("adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi", "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi")),
Arguments.of(new int[] {3, 3}, List.of("dd", "de", "df", "ed", "ee", "ef", "fd", "fe", "ff")), Arguments.of(new int[] {8, 4}, List.of("tg", "th", "ti", "ug", "uh", "ui", "vg", "vh", "vi")), Arguments.of(new int[] {2, 0}, List.of("a ", "b ", "c ")),
Arguments.of(new int[] {9, 2}, List.of("wa", "wb", "wc", "xa", "xb", "xc", "ya", "yb", "yc", "za", "zb", "zc")), Arguments.of(new int[] {0}, List.of(" ")), Arguments.of(new int[] {1}, List.of("")), Arguments.of(new int[] {2}, List.of("a", "b", "c")),
Arguments.of(new int[] {1, 2, 0, 4}, List.of("a g", "a h", "a i", "b g", "b h", "b i", "c g", "c h", "c i")));
}
private static Stream<Arguments> wrongInputs() {
return Stream.of(Arguments.of(new int[] {-1}), Arguments.of(new int[] {10}), Arguments.of(new int[] {2, 2, -1, 0}), Arguments.of(new int[] {0, 0, 0, 10}));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/ManacherTest.java | src/test/java/com/thealgorithms/strings/ManacherTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class ManacherTest {
@ParameterizedTest
@MethodSource("provideTestCasesForLongestPalindrome")
public void testLongestPalindrome(String input, String expected) {
assertEquals(expected, Manacher.longestPalindrome(input));
}
private static Stream<Arguments> provideTestCasesForLongestPalindrome() {
return Stream.of(Arguments.of("abracadabraabcdefggfedcbaabracadabra", "aabcdefggfedcbaa"), Arguments.of("somelongtextwithracecarmiddletext", "racecar"), Arguments.of("bananananananana", "ananananananana"), Arguments.of("qwertydefgfedzxcvbnm", "defgfed"),
Arguments.of("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba", "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcba"));
}
@ParameterizedTest
@MethodSource("provideTestCasesForEmptyAndSingle")
public void testEmptyAndSingle(String input, String expected) {
assertEquals(expected, Manacher.longestPalindrome(input));
}
private static Stream<Arguments> provideTestCasesForEmptyAndSingle() {
return Stream.of(Arguments.of("", ""), Arguments.of("a", "a"));
}
@ParameterizedTest
@MethodSource("provideTestCasesForComplexCases")
public void testComplexCases(String input, String expected) {
assertEquals(expected, Manacher.longestPalindrome(input));
}
private static Stream<Arguments> provideTestCasesForComplexCases() {
return Stream.of(Arguments.of("abcdefghijklmnopqrstuvwxyzttattarrattatabcdefghijklmnopqrstuvwxyz", "tattarrattat"), Arguments.of("aaaaabaaaaacbaaaaa", "aaaaabaaaaa"), Arguments.of("sometextrandomabcdefgabcdefghhgfedcbahijklmnopqrstuvwxyz", "abcdefghhgfedcba"),
Arguments.of("therewasasignthatsaidmadaminedenimadamitwasthereallalong", "madaminedenimadam"));
}
@ParameterizedTest
@MethodSource("provideTestCasesForSentencePalindromes")
public void testSentencePalindromes(String input, String expected) {
assertEquals(expected, Manacher.longestPalindrome(input));
}
private static Stream<Arguments> provideTestCasesForSentencePalindromes() {
return Stream.of(Arguments.of("XThisisalongtextbuthiddeninsideisAmanaplanacanalPanamaWhichweknowisfamous", "lanacanal"), Arguments.of("AverylongstringthatcontainsNeveroddoreveninahiddenmanner", "everoddoreve"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java | src/test/java/com/thealgorithms/strings/HammingDistanceTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
class HammingDistanceTest {
@ParameterizedTest
@CsvSource({"'', '', 0", "'java', 'java', 0", "'karolin', 'kathrin', 3", "'kathrin', 'kerstin', 4", "'00000', '11111', 5", "'10101', '10100', 1"})
void testHammingDistance(String s1, String s2, int expected) {
assertEquals(expected, HammingDistance.calculateHammingDistance(s1, s2));
}
@ParameterizedTest
@MethodSource("provideNullInputs")
void testHammingDistanceWithNullInputs(String input1, String input2) {
assertThrows(IllegalArgumentException.class, () -> HammingDistance.calculateHammingDistance(input1, input2));
}
private static Stream<Arguments> provideNullInputs() {
return Stream.of(Arguments.of(null, "abc"), Arguments.of("abc", null), Arguments.of(null, null));
}
@Test
void testNotEqualStringLengths() {
Exception exception = assertThrows(IllegalArgumentException.class, () -> HammingDistance.calculateHammingDistance("ab", "abc"));
assertEquals("String lengths must be equal", exception.getMessage());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/SuffixArrayTest.java | src/test/java/com/thealgorithms/strings/SuffixArrayTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class SuffixArrayTest {
@Test
void testEmptyString() {
int[] result = SuffixArray.buildSuffixArray("");
assertArrayEquals(new int[] {}, result, "Empty string should return empty suffix array");
}
@Test
void testSingleCharacter() {
int[] result = SuffixArray.buildSuffixArray("a");
assertArrayEquals(new int[] {0}, result, "Single char string should return [0]");
}
@Test
void testDistinctCharacters() {
int[] result = SuffixArray.buildSuffixArray("abc");
assertArrayEquals(new int[] {0, 1, 2}, result, "Suffixes already in order for distinct chars");
}
@Test
void testBananaExample() {
int[] result = SuffixArray.buildSuffixArray("banana");
assertArrayEquals(new int[] {5, 3, 1, 0, 4, 2}, result, "Suffix array of 'banana' should be [5,3,1,0,4,2]");
}
@Test
void testStringWithDuplicates() {
int[] result = SuffixArray.buildSuffixArray("aaaa");
assertArrayEquals(new int[] {3, 2, 1, 0}, result, "Suffix array should be descending indices for 'aaaa'");
}
@Test
void testRandomString() {
int[] result = SuffixArray.buildSuffixArray("mississippi");
assertArrayEquals(new int[] {10, 7, 4, 1, 0, 9, 8, 6, 3, 5, 2}, result, "Suffix array for 'mississippi' should match expected");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/ZAlgorithmTest.java | src/test/java/com/thealgorithms/strings/ZAlgorithmTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class ZAlgorithmTest {
@Test
void testZFunction() {
int[] z = ZAlgorithm.zFunction("aaaaa");
assertArrayEquals(new int[] {0, 4, 3, 2, 1}, z);
}
@Test
void testSearchFound() {
assertEquals(2, ZAlgorithm.search("abcabca", "cab"));
}
@Test
void testSearchNotFound() {
assertEquals(-1, ZAlgorithm.search("abcdef", "gh"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/IsomorphicTest.java | src/test/java/com/thealgorithms/strings/IsomorphicTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public final class IsomorphicTest {
@ParameterizedTest
@MethodSource("inputs")
public void testCheckStrings(String str1, String str2, Boolean expected) {
assertEquals(expected, Isomorphic.areIsomorphic(str1, str2));
assertEquals(expected, Isomorphic.areIsomorphic(str2, str1));
}
private static Stream<Arguments> inputs() {
return Stream.of(Arguments.of("", "", Boolean.TRUE), Arguments.of("", "a", Boolean.FALSE), Arguments.of("aaa", "aa", Boolean.FALSE), Arguments.of("abbbbaac", "kffffkkd", Boolean.TRUE), Arguments.of("xyxyxy", "bnbnbn", Boolean.TRUE), Arguments.of("ghjknnmm", "wertpopo", Boolean.FALSE),
Arguments.of("aaammmnnn", "ggghhhbbj", Boolean.FALSE));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/AlternativeStringArrangeTest.java | src/test/java/com/thealgorithms/strings/AlternativeStringArrangeTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
class AlternativeStringArrangeTest {
// Method to provide test data
private static Stream<Object[]> provideTestData() {
return Stream.of(new Object[] {"abc", "12345", "a1b2c345"}, new Object[] {"abcd", "12", "a1b2cd"}, new Object[] {"", "123", "123"}, new Object[] {"abc", "", "abc"}, new Object[] {"a", "1", "a1"}, new Object[] {"ab", "12", "a1b2"}, new Object[] {"abcdef", "123", "a1b2c3def"},
new Object[] {"ab", "123456", "a1b23456"});
}
// Parameterized test using the provided test data
@ParameterizedTest(name = "{0} and {1} should return {2}")
@MethodSource("provideTestData")
void arrangeTest(String input1, String input2, String expected) {
assertEquals(expected, AlternativeStringArrange.arrange(input1, input2));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/LongestPalindromicSubstringTest.java | src/test/java/com/thealgorithms/strings/LongestPalindromicSubstringTest.java | package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class LongestPalindromicSubstringTest {
@ParameterizedTest
@MethodSource("provideTestCasesForLongestPalindrome")
void testLongestPalindrome(String input, String expected) {
assertEquals(expected, LongestPalindromicSubstring.longestPalindrome(input));
}
private static Stream<Arguments> provideTestCasesForLongestPalindrome() {
return Stream.of(Arguments.of("babad", "bab"), Arguments.of("cbbd", "bb"), Arguments.of("a", "a"), Arguments.of("", ""), Arguments.of("abc", "a"), Arguments.of(null, ""), Arguments.of("aaaaa", "aaaaa"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/strings/zigZagPattern/ZigZagPatternTest.java | src/test/java/com/thealgorithms/strings/zigZagPattern/ZigZagPatternTest.java | package com.thealgorithms.strings.zigZagPattern;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class ZigZagPatternTest {
@Test
public void testZigZagPattern() {
String input1 = "HelloWorldFromJava";
String input2 = "javaIsAProgrammingLanguage";
Assertions.assertEquals(ZigZagPattern.encode(input1, 4), "HooeWrrmalolFJvlda");
Assertions.assertEquals(ZigZagPattern.encode(input2, 4), "jAaLgasPrmgaaevIrgmnnuaoig");
// Edge cases
Assertions.assertEquals("ABC", ZigZagPattern.encode("ABC", 1)); // Single row
Assertions.assertEquals("A", ZigZagPattern.encode("A", 2)); // numRows > length of string
Assertions.assertEquals("", ZigZagPattern.encode("", 3)); // Empty string
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/audiofilters/IIRFilterTest.java | src/test/java/com/thealgorithms/audiofilters/IIRFilterTest.java | package com.thealgorithms.audiofilters;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class IIRFilterTest {
@Test
void testConstructorValidOrder() {
// Test a valid filter creation
IIRFilter filter = new IIRFilter(2);
assertNotNull(filter, "Filter should be instantiated correctly");
}
@Test
void testConstructorInvalidOrder() {
// Test an invalid filter creation (order <= 0)
assertThrows(IllegalArgumentException.class, () -> { new IIRFilter(0); }, "Order must be greater than zero");
}
@Test
void testSetCoeffsInvalidLengthA() {
IIRFilter filter = new IIRFilter(2);
// Invalid 'aCoeffs' length
double[] aCoeffs = {1.0}; // too short
double[] bCoeffs = {1.0, 0.5};
assertThrows(IllegalArgumentException.class, () -> { filter.setCoeffs(aCoeffs, bCoeffs); }, "aCoeffs must be of size 2");
}
@Test
void testSetCoeffsInvalidLengthB() {
IIRFilter filter = new IIRFilter(2);
// Invalid 'bCoeffs' length
double[] aCoeffs = {1.0, 0.5};
double[] bCoeffs = {1.0}; // too short
assertThrows(IllegalArgumentException.class, () -> { filter.setCoeffs(aCoeffs, bCoeffs); }, "bCoeffs must be of size 2");
}
@Test
void testSetCoeffsInvalidACoeffZero() {
IIRFilter filter = new IIRFilter(2);
// Invalid 'aCoeffs' where aCoeffs[0] == 0.0
double[] aCoeffs = {0.0, 0.5}; // aCoeffs[0] must not be zero
double[] bCoeffs = {1.0, 0.5};
assertThrows(IllegalArgumentException.class, () -> { filter.setCoeffs(aCoeffs, bCoeffs); }, "aCoeffs[0] must not be zero");
}
@Test
void testProcessWithNoCoeffsSet() {
// Test process method with default coefficients (sane defaults)
IIRFilter filter = new IIRFilter(2);
double inputSample = 0.5;
double result = filter.process(inputSample);
// Since default coeffsA[0] and coeffsB[0] are 1.0, expect output = input
assertEquals(inputSample, result, 1e-6, "Process should return the same value as input with default coefficients");
}
@Test
void testProcessWithCoeffsSet() {
// Test process method with set coefficients
IIRFilter filter = new IIRFilter(2);
double[] aCoeffs = {1.0, 0.5};
double[] bCoeffs = {1.0, 0.5};
filter.setCoeffs(aCoeffs, bCoeffs);
// Process a sample
double inputSample = 0.5;
double result = filter.process(inputSample);
// Expected output can be complex to calculate in advance;
// check if the method runs and returns a result within reasonable bounds
assertTrue(result >= -1.0 && result <= 1.0, "Processed result should be in the range [-1, 1]");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/audiofilters/EMAFilterTest.java | src/test/java/com/thealgorithms/audiofilters/EMAFilterTest.java | package com.thealgorithms.audiofilters;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
public class EMAFilterTest {
@Test
public void testApplyBasicSignal() {
EMAFilter emaFilter = new EMAFilter(0.2);
double[] audioSignal = {0.1, 0.5, 0.8, 0.6, 0.3, 0.9, 0.4};
double[] expectedOutput = {0.1, 0.18, 0.304, 0.3632, 0.35056, 0.460448, 0.4483584};
double[] result = emaFilter.apply(audioSignal);
assertArrayEquals(expectedOutput, result, 1e-5);
}
@Test
public void testApplyEmptySignal() {
EMAFilter emaFilter = new EMAFilter(0.2);
double[] audioSignal = {};
double[] expectedOutput = {};
double[] result = emaFilter.apply(audioSignal);
assertArrayEquals(expectedOutput, result);
}
@Test
public void testAlphaBounds() {
EMAFilter emaFilterMin = new EMAFilter(0.01);
EMAFilter emaFilterMax = new EMAFilter(1.0);
double[] audioSignal = {1.0, 1.0, 1.0, 1.0};
// Minimal smoothing (alpha close to 0)
double[] resultMin = emaFilterMin.apply(audioSignal);
assertArrayEquals(audioSignal, resultMin, 1e-5);
// Maximum smoothing (alpha = 1, output should match input)
double[] resultMax = emaFilterMax.apply(audioSignal);
assertArrayEquals(audioSignal, resultMax, 1e-5);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/DiffieHellmanTest.java | src/test/java/com/thealgorithms/ciphers/DiffieHellmanTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigInteger;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class DiffieHellmanTest {
// Test for public value calculation using instance methods
@ParameterizedTest
@MethodSource("provideTestData")
public void testCalculatePublicValue(BigInteger base, BigInteger secret, BigInteger prime, BigInteger publicExpected, BigInteger sharedExpected) {
DiffieHellman dh = new DiffieHellman(base, secret, prime); // Create an instance of DiffieHellman
assertEquals(publicExpected, dh.calculatePublicValue()); // Call instance method
}
// Test for shared secret calculation using instance methods
@ParameterizedTest
@MethodSource("provideTestData")
public void testCalculateSharedSecret(BigInteger base, BigInteger secret, BigInteger prime, BigInteger publicExpected, BigInteger sharedExpected) {
DiffieHellman dh = new DiffieHellman(base, secret, prime); // Create an instance of DiffieHellman
assertEquals(sharedExpected, dh.calculateSharedSecret(publicExpected)); // Call instance method
}
// Provide test data for both public key and shared secret calculation
private static Stream<Arguments> provideTestData() {
return Stream.of(createTestArgs(5, 6, 23, 8, 13), createTestArgs(2, 5, 13, 6, 2));
}
// Helper method for arguments
private static Arguments createTestArgs(long base, long secret, long prime, long publicExpected, long sharedExpected) {
return Arguments.of(BigInteger.valueOf(base), BigInteger.valueOf(secret), BigInteger.valueOf(prime), BigInteger.valueOf(publicExpected), BigInteger.valueOf(sharedExpected));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java | src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class SimpleSubCipherTest {
SimpleSubCipher simpleSubCipher = new SimpleSubCipher();
@Test
void simpleSubCipherEncryptTest() {
// given
String text = "defend the east wall of the castle";
String cipherSmall = "phqgiumeaylnofdxjkrcvstzwb";
// when
String cipherText = simpleSubCipher.encode(text, cipherSmall);
// then
assertEquals("giuifg cei iprc tpnn du cei qprcni", cipherText);
}
@Test
void simpleSubCipherDecryptTest() {
// given
String encryptedText = "giuifg cei iprc tpnn du cei qprcni";
String cipherSmall = "phqgiumeaylnofdxjkrcvstzwb";
// when
String decryptedText = simpleSubCipher.decode(encryptedText, cipherSmall);
// then
assertEquals("defend the east wall of the castle", decryptedText);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/RailFenceTest.java | src/test/java/com/thealgorithms/ciphers/RailFenceTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class RailFenceTest {
@Test
void testEncryption() {
RailFenceCipher cipher = new RailFenceCipher();
String input = "We are discovered! Flee at once";
int rails = 3;
String encrypted = cipher.encrypt(input, rails);
assertEquals("Wrivdlaneaedsoee!Fe toc cr e e", encrypted);
String singleChar = "A";
int singleRail = 2;
String encryptedSingleChar = cipher.encrypt(singleChar, singleRail);
assertEquals("A", encryptedSingleChar);
String shortString = "Hello";
int moreRails = 10;
String encryptedShortString = cipher.encrypt(shortString, moreRails);
assertEquals("Hello", encryptedShortString);
String inputSingleRail = "Single line";
int singleRailOnly = 1;
String encryptedSingleRail = cipher.encrypt(inputSingleRail, singleRailOnly);
assertEquals("Single line", encryptedSingleRail);
}
@Test
void testDecryption() {
RailFenceCipher cipher = new RailFenceCipher();
// Scenario 1: Basic decryption with multiple rails
String encryptedInput = "Wrivdlaneaedsoee!Fe toc cr e e";
int rails = 3;
String decrypted = cipher.decrypt(encryptedInput, rails);
assertEquals("We are discovered! Flee at once", decrypted);
// Scenario 2: Single character string decryption
String encryptedSingleChar = "A";
int singleRail = 2; // More than 1 rail
String decryptedSingleChar = cipher.decrypt(encryptedSingleChar, singleRail);
assertEquals("A", decryptedSingleChar);
// Scenario 3: String length less than the number of rails
String encryptedShortString = "Hello";
int moreRails = 10; // More rails than characters
String decryptedShortString = cipher.decrypt(encryptedShortString, moreRails);
assertEquals("Hello", decryptedShortString);
// Scenario 4: Single rail decryption (output should be the same as input)
String encryptedSingleRail = "Single line";
int singleRailOnly = 1;
String decryptedSingleRail = cipher.decrypt(encryptedSingleRail, singleRailOnly);
assertEquals("Single line", decryptedSingleRail);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/PolybiusTest.java | src/test/java/com/thealgorithms/ciphers/PolybiusTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class PolybiusTest {
@Test
void testEncrypt() {
// Given
String plaintext = "HELLOWORLD";
// When
String actual = Polybius.encrypt(plaintext);
// Then
assertEquals("12042121244124322103", actual);
}
@Test
void testDecrypt() {
// Given
String ciphertext = "12042121244124322103";
// When
String actual = Polybius.decrypt(ciphertext);
// Then
assertEquals("HELLOWORLD", actual);
}
@Test
void testIsTextTheSameAfterEncryptionAndDecryption() {
// Given
String plaintext = "HELLOWORLD";
// When
String encryptedText = Polybius.encrypt(plaintext);
String actual = Polybius.decrypt(encryptedText);
// Then
assertEquals(plaintext, actual);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/AESEncryptionTest.java | src/test/java/com/thealgorithms/ciphers/AESEncryptionTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.crypto.SecretKey;
import org.junit.jupiter.api.Test;
public class AESEncryptionTest {
@Test
public void testGetSecretEncryptionKey() throws Exception {
SecretKey key = AESEncryption.getSecretEncryptionKey();
assertNotNull(key, "Secret key should not be null");
assertEquals(128, key.getEncoded().length * 8, "Key size should be 128 bits");
}
@Test
public void testEncryptText() throws Exception {
String plainText = "Hello World";
SecretKey secKey = AESEncryption.getSecretEncryptionKey();
byte[] cipherText = AESEncryption.encryptText(plainText, secKey);
assertNotNull(cipherText, "Ciphertext should not be null");
assertTrue(cipherText.length > 0, "Ciphertext should not be empty");
}
@Test
public void testDecryptText() throws Exception {
String plainText = "Hello World";
SecretKey secKey = AESEncryption.getSecretEncryptionKey();
byte[] cipherText = AESEncryption.encryptText(plainText, secKey);
// Decrypt the ciphertext
String decryptedText = AESEncryption.decryptText(cipherText, secKey);
assertNotNull(decryptedText, "Decrypted text should not be null");
assertEquals(plainText, decryptedText, "Decrypted text should match the original plain text");
}
@Test
public void testEncryptDecrypt() throws Exception {
String plainText = "Hello AES!";
SecretKey secKey = AESEncryption.getSecretEncryptionKey();
// Encrypt the plaintext
byte[] cipherText = AESEncryption.encryptText(plainText, secKey);
// Decrypt the ciphertext
String decryptedText = AESEncryption.decryptText(cipherText, secKey);
assertEquals(plainText, decryptedText, "Decrypted text should match the original plain text");
}
@Test
public void testBytesToHex() {
byte[] bytes = new byte[] {0, 1, 15, 16, (byte) 255}; // Test with diverse byte values
String hex = AESEncryption.bytesToHex(bytes);
assertEquals("00010F10FF", hex, "Hex representation should match the expected value");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/BaconianCipherTest.java | src/test/java/com/thealgorithms/ciphers/BaconianCipherTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class BaconianCipherTest {
BaconianCipher baconianCipher = new BaconianCipher();
@Test
void baconianCipherEncryptTest() {
// given
String plaintext = "MEET AT DAWN";
// when
String cipherText = baconianCipher.encrypt(plaintext);
// then
assertEquals("ABBAAAABAAAABAABAABBAAAAABAABBAAABBAAAAABABBAABBAB", cipherText);
}
@Test
void baconianCipherDecryptTest() {
// given
String ciphertext = "ABBAAAABAAAABAABAABBAAAAABAABBAAABBAAAAABABBAABBAB";
// when
String plainText = baconianCipher.decrypt(ciphertext);
// then
assertEquals("MEETATDAWN", plainText);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/VigenereTest.java | src/test/java/com/thealgorithms/ciphers/VigenereTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class VigenereTest {
Vigenere vigenere = new Vigenere();
@Test
void testVigenereEncryptDecrypt() {
String text = "Hello World!";
String key = "suchsecret";
String encryptedText = vigenere.encrypt(text, key);
String decryptedText = vigenere.decrypt(encryptedText, key);
assertEquals("Zynsg Aqipw!", encryptedText);
assertEquals("Hello World!", decryptedText);
}
@Test
void testWithEmptyMessage() {
String text = "";
String key = "anykey";
String encryptedText = vigenere.encrypt(text, key);
String decryptedText = vigenere.decrypt(encryptedText, key);
assertEquals("", encryptedText);
assertEquals("", decryptedText);
}
@Test
void testWithEmptyKey() {
String text = "This should remain the same";
String key = "";
assertThrows(IllegalArgumentException.class, () -> vigenere.encrypt(text, key));
assertThrows(IllegalArgumentException.class, () -> vigenere.decrypt(text, key));
}
@Test
void testWithNumbersInMessage() {
String text = "Vigenere123!";
String key = "cipher";
String encryptedText = vigenere.encrypt(text, key);
String decryptedText = vigenere.decrypt(encryptedText, key);
assertEquals("Xqvlrvtm123!", encryptedText);
assertEquals(text, decryptedText);
}
@Test
void testLongerKeyThanMessage() {
String text = "Short";
String key = "VeryLongSecretKey";
String encryptedText = vigenere.encrypt(text, key);
String decryptedText = vigenere.decrypt(encryptedText, key);
assertEquals("Nlfpe", encryptedText);
assertEquals(text, decryptedText);
}
@Test
void testUppercaseMessageAndKey() {
String text = "HELLO";
String key = "SECRET";
String encryptedText = vigenere.encrypt(text, key);
String decryptedText = vigenere.decrypt(encryptedText, key);
assertEquals("ZINCS", encryptedText);
assertEquals(text, decryptedText);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/MonoAlphabeticTest.java | src/test/java/com/thealgorithms/ciphers/MonoAlphabeticTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class MonoAlphabeticTest {
// Test for both encryption and decryption with different keys
@ParameterizedTest
@MethodSource("provideTestData")
public void testEncryptDecrypt(String plainText, String key, String encryptedText) {
// Test encryption
String actualEncrypted = MonoAlphabetic.encrypt(plainText, key);
assertEquals(encryptedText, actualEncrypted, "Encryption failed for input: " + plainText + " with key: " + key);
// Test decryption
String actualDecrypted = MonoAlphabetic.decrypt(encryptedText, key);
assertEquals(plainText, actualDecrypted, "Decryption failed for input: " + encryptedText + " with key: " + key);
}
// Provide test data for both encryption and decryption
private static Stream<Arguments> provideTestData() {
return Stream.of(Arguments.of("HELLO", "MNBVCXZLKJHGFDSAPOIUYTREWQ", "LCGGS"), Arguments.of("JAVA", "MNBVCXZLKJHGFDSAPOIUYTREWQ", "JMTM"), Arguments.of("HELLO", "QWERTYUIOPLKJHGFDSAZXCVBNM", "ITKKG"), Arguments.of("JAVA", "QWERTYUIOPLKJHGFDSAZXCVBNM", "PQCQ"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java | src/test/java/com/thealgorithms/ciphers/BlowfishTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class BlowfishTest {
Blowfish blowfish = new Blowfish();
@Test
void testEncrypt() {
// given
String plainText = "123456abcd132536";
String key = "aabb09182736ccdd";
String expectedOutput = "d748ec383d3405f7";
// when
String cipherText = blowfish.encrypt(plainText, key);
// then
assertEquals(expectedOutput, cipherText);
}
@Test
void testDecrypt() {
// given
String cipherText = "d748ec383d3405f7";
String key = "aabb09182736ccdd";
String expectedOutput = "123456abcd132536";
// when
String plainText = blowfish.decrypt(cipherText, key);
// then
assertEquals(expectedOutput, plainText);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/AffineCipherTest.java | src/test/java/com/thealgorithms/ciphers/AffineCipherTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class AffineCipherTest {
@Test
public void testEncryptMessage() {
String plaintext = "AFFINE CIPHER";
char[] msg = plaintext.toCharArray();
String expectedCiphertext = "UBBAHK CAPJKX"; // Expected ciphertext after encryption
String actualCiphertext = AffineCipher.encryptMessage(msg);
assertEquals(expectedCiphertext, actualCiphertext, "The encryption result should match the expected ciphertext.");
}
@Test
public void testEncryptDecrypt() {
String plaintext = "HELLO WORLD";
char[] msg = plaintext.toCharArray();
String ciphertext = AffineCipher.encryptMessage(msg);
String decryptedText = AffineCipher.decryptCipher(ciphertext);
assertEquals(plaintext, decryptedText, "Decrypted text should match the original plaintext.");
}
@Test
public void testSpacesHandledInEncryption() {
String plaintext = "HELLO WORLD";
char[] msg = plaintext.toCharArray();
String expectedCiphertext = "JKZZY EYXZT";
String actualCiphertext = AffineCipher.encryptMessage(msg);
assertEquals(expectedCiphertext, actualCiphertext, "The encryption should handle spaces correctly.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/OneTimePadCipherTest.java | src/test/java/com/thealgorithms/ciphers/OneTimePadCipherTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
class OneTimePadCipherTest {
@Test
void encryptAndDecryptWithRandomKeyRestoresPlaintext() {
String plaintext = "The quick brown fox jumps over the lazy dog.";
byte[] plaintextBytes = plaintext.getBytes(StandardCharsets.UTF_8);
byte[] key = OneTimePadCipher.generateKey(plaintextBytes.length);
byte[] ciphertext = OneTimePadCipher.encrypt(plaintextBytes, key);
byte[] decrypted = OneTimePadCipher.decrypt(ciphertext, key);
assertArrayEquals(plaintextBytes, decrypted);
assertEquals(plaintext, new String(decrypted, StandardCharsets.UTF_8));
}
@Test
void generateKeyWithNegativeLengthThrowsException() {
assertThrows(IllegalArgumentException.class, () -> OneTimePadCipher.generateKey(-1));
}
@Test
void encryptWithMismatchedKeyLengthThrowsException() {
byte[] data = "hello".getBytes(StandardCharsets.UTF_8);
byte[] shortKey = OneTimePadCipher.generateKey(2);
assertThrows(IllegalArgumentException.class, () -> OneTimePadCipher.encrypt(data, shortKey));
}
@Test
void decryptWithMismatchedKeyLengthThrowsException() {
byte[] data = "hello".getBytes(StandardCharsets.UTF_8);
byte[] key = OneTimePadCipher.generateKey(data.length);
byte[] ciphertext = OneTimePadCipher.encrypt(data, key);
byte[] wrongSizedKey = OneTimePadCipher.generateKey(data.length + 1);
assertThrows(IllegalArgumentException.class, () -> OneTimePadCipher.decrypt(ciphertext, wrongSizedKey));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/DESTest.java | src/test/java/com/thealgorithms/ciphers/DESTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
// Test example taken from https://page.math.tu-berlin.de/~kant/teaching/hess/krypto-ws2006/des.htm
public class DESTest {
DES des;
@BeforeEach
public void setUp() {
des = new DES("0000111000110010100100100011001011101010011011010000110101110011");
}
@Test
void testEncrypt() {
// given
String plainText = "Your lips are smoother than vaseline\r\n";
// This is equal to
// c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in
// hexadecimal
String expectedOutput = "11000000100110011001111111011101111000110111100011010111111"
+ "011010111001001111101101000000000101111001010010110101000010011101110010001111111001"
+ "001101001101001001101011001000011100000011001000011011001110101010010111101111000111"
+ "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011";
// when
String cipherText = des.encrypt(plainText);
// then
assertEquals(expectedOutput, cipherText);
}
@Test
void testDecrypt() {
// given
// This is equal to
// c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in
// hexadecimal
String cipherText = "11000000100110011001111111011101111000110111100011010111111"
+ "011010111001001111101101000000000101111001010010110101000010011101110010001111111001"
+ "001101001101001001101011001000011100000011001000011011001110101010010111101111000111"
+ "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011";
String expectedOutput = "Your lips are smoother than vaseline\r\n";
// when
String plainText = des.decrypt(cipherText);
// then
assertEquals(expectedOutput, plainText);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/ECCTest.java | src/test/java/com/thealgorithms/ciphers/ECCTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.math.BigInteger;
import org.junit.jupiter.api.Test;
/**
* ECCTest - Unit tests for the ECC (Elliptic Curve Cryptography) implementation.
* This class contains various test cases to validate the encryption and decryption functionalities.
* It ensures the correctness and randomness of ECC operations.
*
* @author xuyang
*/
public class ECCTest {
ECC ecc = new ECC(256); // Generate a 256-bit ECC key pair. Calls generateKeys(bits) to create keys including privateKey and publicKey.
/**
* Test the encryption functionality: convert plaintext to ciphertext and output relevant encryption data.
*/
@Test
void testEncrypt() {
String textToEncrypt = "Elliptic Curve Cryptography";
ECC.ECPoint[] cipherText = ecc.encrypt(textToEncrypt); // Perform encryption
// Output private key information
System.out.println("Private Key: " + ecc.getPrivateKey());
// Output elliptic curve parameters
ECC.EllipticCurve curve = ecc.getCurve();
System.out.println("Elliptic Curve Parameters:");
System.out.println("a: " + curve.getA());
System.out.println("b: " + curve.getB());
System.out.println("p: " + curve.getP());
System.out.println("Base Point G: " + curve.getBasePoint());
// Verify that the ciphertext is not empty
assertEquals(cipherText.length, 2); // Check if the ciphertext contains two points (R and S)
// Output the encrypted coordinate points
System.out.println("Encrypted Points:");
for (ECC.ECPoint point : cipherText) {
System.out.println(point); // Calls ECPoint's toString() method
}
}
/**
* Test the decryption functionality: convert ciphertext back to plaintext using known private key and elliptic curve parameters.
*/
@Test
void testDecryptWithKnownValues() {
// 1. Define the known private key
BigInteger knownPrivateKey = new BigInteger("28635978664199231399690075483195602260051035216440375973817268759912070302603");
// 2. Define the known elliptic curve parameters
BigInteger a = new BigInteger("64505295837372135469230827475895976532873592609649950000895066186842236488761"); // Replace with known a value
BigInteger b = new BigInteger("89111668838830965251111555638616364203833415376750835901427122343021749874324"); // Replace with known b value
BigInteger p = new BigInteger("107276428198310591598877737561885175918069075479103276920057092968372930219921"); // Replace with known p value
ECC.ECPoint basePoint = new ECC.ECPoint(new BigInteger("4"), new BigInteger("8")); // Replace with known base point coordinates
// 3. Create the elliptic curve object
ECC.EllipticCurve curve = new ECC.EllipticCurve(a, b, p, basePoint);
// 4. Define the known ciphertext containing two ECPoints (R, S)
ECC.ECPoint rPoint = new ECC.ECPoint(new BigInteger("103077584019003058745849614420912636617007257617156724481937620119667345237687"), new BigInteger("68193862907937248121971710522760893811582068323088661566426323952783362061817"));
ECC.ECPoint sPoint = new ECC.ECPoint(new BigInteger("31932232426664380635434632300383525435115368414929679432313910646436992147798"), new BigInteger("77299754382292904069123203569944908076819220797512755280123348910207308129766"));
ECC.ECPoint[] cipherText = new ECC.ECPoint[] {rPoint, sPoint};
// 5. Create an ECC instance and set the private key and curve parameters
ecc.setPrivateKey(knownPrivateKey); // Use setter method to set the private key
ecc.setCurve(curve); // Use setter method to set the elliptic curve
// 6. Decrypt the known ciphertext
String decryptedMessage = ecc.decrypt(cipherText);
// 7. Compare the decrypted plaintext with the expected value
String expectedMessage = "Elliptic Curve Cryptography"; // Expected plaintext
assertEquals(expectedMessage, decryptedMessage);
}
/**
* Test that encrypting the same plaintext with ECC produces different ciphertexts.
*/
@Test
void testCipherTextRandomness() {
String message = "Elliptic Curve Cryptography";
ECC.ECPoint[] cipherText1 = ecc.encrypt(message);
ECC.ECPoint[] cipherText2 = ecc.encrypt(message);
assertNotEquals(cipherText1, cipherText2); // Ensure that the two ciphertexts are different
}
/**
* Test the entire ECC encryption and decryption process.
*/
@Test
void testECCEncryptionAndDecryption() {
String textToEncrypt = "Elliptic Curve Cryptography";
ECC.ECPoint[] cipherText = ecc.encrypt(textToEncrypt);
String decryptedText = ecc.decrypt(cipherText);
assertEquals(textToEncrypt, decryptedText); // Verify that the decrypted text matches the original text
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java | src/test/java/com/thealgorithms/ciphers/HillCipherTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class HillCipherTest {
HillCipher hillCipher = new HillCipher();
@Test
void hillCipherEncryptTest() {
// given
String message = "ACT"; // Plaintext message
int[][] keyMatrix = {{6, 24, 1}, {13, 16, 10}, {20, 17, 15}}; // Encryption key matrix
// when
String cipherText = hillCipher.encrypt(message, keyMatrix);
// then
assertEquals("POH", cipherText);
}
@Test
void hillCipherDecryptTest() {
// given
String cipherText = "POH"; // Ciphertext message
int[][] inverseKeyMatrix = {{8, 5, 10}, {21, 8, 21}, {21, 12, 8}}; // Decryption (inverse key) matrix
// when
String plainText = hillCipher.decrypt(cipherText, inverseKeyMatrix);
// then
assertEquals("ACT", plainText);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/AtbashTest.java | src/test/java/com/thealgorithms/ciphers/AtbashTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
public class AtbashTest {
@ParameterizedTest
@MethodSource("cipherTestProvider")
public void testAtbashCipher(String input, String expected) {
AtbashCipher cipher = new AtbashCipher(input);
assertEquals(expected, cipher.convert());
}
private static Stream<Arguments> cipherTestProvider() {
return Stream.of(
// Basic tests with lowercase and uppercase
Arguments.of("Hello", "Svool"), Arguments.of("WORLD", "DLIOW"),
// Mixed case with spaces and punctuation
Arguments.of("Hello World!", "Svool Dliow!"), Arguments.of("123 ABC xyz", "123 ZYX cba"),
// Palindromes and mixed cases
Arguments.of("madam", "nzwzn"), Arguments.of("Palindrome", "Kzormwilnv"),
// Non-alphabetic characters should remain unchanged
Arguments.of("@cipher 123!", "@xrksvi 123!"), Arguments.of("no-change", "ml-xszmtv"),
// Empty string and single characters
Arguments.of("", ""), Arguments.of("A", "Z"), Arguments.of("z", "a"),
// Numbers and symbols
Arguments.of("!@#123", "!@#123"),
// Full sentence with uppercase, lowercase, symbols, and numbers
Arguments.of("Hello World! 123, @cipher abcDEF ZYX 987 madam zzZ Palindrome!", "Svool Dliow! 123, @xrksvi zyxWVU ABC 987 nzwzn aaA Kzormwilnv!"),
Arguments.of("Svool Dliow! 123, @xrksvi zyxWVU ABC 987 nzwzn aaA Kzormwilnv!", "Hello World! 123, @cipher abcDEF ZYX 987 madam zzZ Palindrome!"));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/PermutationCipherTest.java | src/test/java/com/thealgorithms/ciphers/PermutationCipherTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class PermutationCipherTest {
private final PermutationCipher cipher = new PermutationCipher();
@Test
void testBasicEncryption() {
// given
String plaintext = "HELLO";
int[] key = {3, 1, 2}; // Move 3rd position to 1st, 1st to 2nd, 2nd to 3rd
// when
String encrypted = cipher.encrypt(plaintext, key);
// then
// "HELLO" becomes "HEL" + "LOX" (padded)
// "HEL" with key {3,1,2} becomes "LHE" (L=3rd, H=1st, E=2nd)
// "LOX" with key {3,1,2} becomes "XLO" (X=3rd, L=1st, O=2nd)
assertEquals("LHEXLO", encrypted);
}
@Test
void testBasicDecryption() {
// given
String ciphertext = "LHEXLO";
int[] key = {3, 1, 2};
// when
String decrypted = cipher.decrypt(ciphertext, key);
// then
assertEquals("HELLO", decrypted);
}
@Test
void testEncryptDecryptRoundTrip() {
// given
String plaintext = "THIS IS A TEST MESSAGE";
int[] key = {4, 2, 1, 3};
// when
String encrypted = cipher.encrypt(plaintext, key);
String decrypted = cipher.decrypt(encrypted, key);
// then
assertEquals("THISISATESTMESSAGE", decrypted); // Spaces are removed during encryption
}
@Test
void testSingleCharacterKey() {
// given
String plaintext = "ABCDEF";
int[] key = {1}; // Identity permutation
// when
String encrypted = cipher.encrypt(plaintext, key);
String decrypted = cipher.decrypt(encrypted, key);
// then
assertEquals("ABCDEF", encrypted); // Should remain unchanged
assertEquals("ABCDEF", decrypted);
}
@Test
void testLargerKey() {
// given
String plaintext = "PERMUTATION";
int[] key = {5, 3, 1, 4, 2}; // 5-character permutation
// when
String encrypted = cipher.encrypt(plaintext, key);
String decrypted = cipher.decrypt(encrypted, key);
// then
assertEquals("PERMUTATION", decrypted);
}
@Test
void testExactBlockSize() {
// given
String plaintext = "ABCDEF"; // Length 6, divisible by key length 3
int[] key = {2, 3, 1};
// when
String encrypted = cipher.encrypt(plaintext, key);
String decrypted = cipher.decrypt(encrypted, key);
// then
assertEquals("ABCDEF", decrypted);
}
@Test
void testEmptyString() {
// given
String plaintext = "";
int[] key = {2, 1, 3};
// when
String encrypted = cipher.encrypt(plaintext, key);
String decrypted = cipher.decrypt(encrypted, key);
// then
assertEquals("", encrypted);
assertEquals("", decrypted);
}
@Test
void testNullString() {
// given
String plaintext = null;
int[] key = {2, 1, 3};
// when
String encrypted = cipher.encrypt(plaintext, key);
String decrypted = cipher.decrypt(encrypted, key);
// then
assertEquals(null, encrypted);
assertEquals(null, decrypted);
}
@Test
void testStringWithSpaces() {
// given
String plaintext = "A B C D E F";
int[] key = {2, 1};
// when
String encrypted = cipher.encrypt(plaintext, key);
String decrypted = cipher.decrypt(encrypted, key);
// then
assertEquals("ABCDEF", decrypted); // Spaces should be removed
}
@Test
void testLowercaseConversion() {
// given
String plaintext = "hello world";
int[] key = {3, 1, 2};
// when
String encrypted = cipher.encrypt(plaintext, key);
String decrypted = cipher.decrypt(encrypted, key);
// then
assertEquals("HELLOWORLD", decrypted); // Should be converted to uppercase
}
@Test
void testInvalidKeyNull() {
// given
String plaintext = "HELLO";
int[] key = null;
// when & then
assertThrows(IllegalArgumentException.class, () -> cipher.encrypt(plaintext, key));
assertThrows(IllegalArgumentException.class, () -> cipher.decrypt(plaintext, key));
}
@Test
void testInvalidKeyEmpty() {
// given
String plaintext = "HELLO";
int[] key = {};
// when & then
assertThrows(IllegalArgumentException.class, () -> cipher.encrypt(plaintext, key));
assertThrows(IllegalArgumentException.class, () -> cipher.decrypt(plaintext, key));
}
@Test
void testInvalidKeyOutOfRange() {
// given
String plaintext = "HELLO";
int[] key = {1, 2, 4}; // 4 is out of range for key length 3
// when & then
assertThrows(IllegalArgumentException.class, () -> cipher.encrypt(plaintext, key));
assertThrows(IllegalArgumentException.class, () -> cipher.decrypt(plaintext, key));
}
@Test
void testInvalidKeyZero() {
// given
String plaintext = "HELLO";
int[] key = {0, 1, 2}; // 0 is invalid (should be 1-based)
// when & then
assertThrows(IllegalArgumentException.class, () -> cipher.encrypt(plaintext, key));
assertThrows(IllegalArgumentException.class, () -> cipher.decrypt(plaintext, key));
}
@Test
void testInvalidKeyDuplicate() {
// given
String plaintext = "HELLO";
int[] key = {1, 2, 2}; // Duplicate position
// when & then
assertThrows(IllegalArgumentException.class, () -> cipher.encrypt(plaintext, key));
assertThrows(IllegalArgumentException.class, () -> cipher.decrypt(plaintext, key));
}
@Test
void testInvalidKeyMissingPosition() {
// given
String plaintext = "HELLO";
int[] key = {1, 3}; // Missing position 2
// when & then
assertThrows(IllegalArgumentException.class, () -> cipher.encrypt(plaintext, key));
assertThrows(IllegalArgumentException.class, () -> cipher.decrypt(plaintext, key));
}
@Test
void testReverseKey() {
// given
String plaintext = "ABCD";
int[] key = {4, 3, 2, 1}; // Reverse order
// when
String encrypted = cipher.encrypt(plaintext, key);
String decrypted = cipher.decrypt(encrypted, key);
// then
assertEquals("DCBA", encrypted); // Should be reversed
assertEquals("ABCD", decrypted);
}
@Test
void testSpecificExampleFromDescription() {
// given
String plaintext = "HELLO";
int[] key = {3, 1, 2};
// when
String encrypted = cipher.encrypt(plaintext, key);
// then
// Block 1: "HEL" -> positions {3,1,2} -> "LHE"
// Block 2: "LOX" -> positions {3,1,2} -> "XLO"
assertEquals("LHEXLO", encrypted);
// Verify decryption
String decrypted = cipher.decrypt(encrypted, key);
assertEquals("HELLO", decrypted);
}
@Test
void testPaddingCharacterGetter() {
// when
char paddingChar = cipher.getPaddingChar();
// then
assertEquals('X', paddingChar);
}
@Test
void testLongText() {
// given
String plaintext = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
int[] key = {4, 1, 3, 2};
// when
String encrypted = cipher.encrypt(plaintext, key);
String decrypted = cipher.decrypt(encrypted, key);
// then
assertEquals("THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG", decrypted);
}
@Test
void testIdentityPermutation() {
// given
String plaintext = "IDENTITY";
int[] key = {1, 2, 3, 4}; // Identity permutation
// when
String encrypted = cipher.encrypt(plaintext, key);
String decrypted = cipher.decrypt(encrypted, key);
// then
assertEquals("IDENTITY", encrypted); // Should remain unchanged
assertEquals("IDENTITY", decrypted);
}
@Test
void testEmptyStringRemovePadding() {
// given - Test to cover line 178 (empty string case in removePadding)
String ciphertext = "";
int[] key = {2, 1, 3};
// when
String decrypted = cipher.decrypt(ciphertext, key);
// then
assertEquals("", decrypted); // Should return empty string directly
}
@Test
void testBlockShorterThanKey() {
// given - Test to cover line 139 (block length != key length case)
// This is a defensive case where permuteBlock might receive a block shorter than key
// We can test this by manually creating a scenario with malformed ciphertext
String malformedCiphertext = "AB"; // Length 2, but key length is 3
int[] key = {3, 1, 2}; // Key length is 3
// when - This should trigger the padding logic in permuteBlock during decryption
String decrypted = cipher.decrypt(malformedCiphertext, key);
// then - The method should handle the short block gracefully
// "AB" gets padded to "ABX", then permuted with inverse key {2,3,1}
// inverse key {2,3,1} means: pos 2→1st, pos 3→2nd, pos 1→3rd = "BXA"
// Padding removal only removes trailing X's, so "BXA" remains as is
assertEquals("BXA", decrypted);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/CaesarTest.java | src/test/java/com/thealgorithms/ciphers/CaesarTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class CaesarTest {
Caesar caesar = new Caesar();
@Test
void caesarEncryptTest() {
// given
String textToEncrypt = "Encrypt this text";
// when
String cipherText = caesar.encode(textToEncrypt, 5);
// then
assertEquals("Jshwduy ymnx yjcy", cipherText);
}
@Test
void caesarDecryptTest() {
// given
String encryptedText = "Jshwduy ymnx yjcy";
// when
String cipherText = caesar.decode(encryptedText, 5);
// then
assertEquals("Encrypt this text", cipherText);
}
@Test
void caesarBruteForce() {
// given
String encryptedText = "Jshwduy ymnx yjcy";
// when
String[] allPossibleAnswers = caesar.bruteforce(encryptedText);
assertEquals(27, allPossibleAnswers.length);
assertEquals("Encrypt this text", allPossibleAnswers[5]);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/ColumnarTranspositionCipherTest.java | src/test/java/com/thealgorithms/ciphers/ColumnarTranspositionCipherTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ColumnarTranspositionCipherTest {
private String keyword;
private String plaintext;
@BeforeEach
public void setUp() {
keyword = "keyword";
plaintext = "This is a test message for Columnar Transposition Cipher";
}
@Test
public void testEncryption() {
String encryptedText = ColumnarTranspositionCipher.encrypt(plaintext, keyword);
assertNotNull(encryptedText, "The encrypted text should not be null.");
assertFalse(encryptedText.isEmpty(), "The encrypted text should not be empty.");
// Check if the encrypted text is different from the plaintext
assertNotEquals(plaintext, encryptedText, "The encrypted text should be different from the plaintext.");
}
@Test
public void testDecryption() {
String encryptedText = ColumnarTranspositionCipher.encrypt(plaintext, keyword);
String decryptedText = ColumnarTranspositionCipher.decrypt();
assertEquals(plaintext.replaceAll(" ", ""), decryptedText.replaceAll(" ", ""), "The decrypted text should match the original plaintext, ignoring spaces.");
assertEquals(encryptedText, ColumnarTranspositionCipher.encrypt(plaintext, keyword), "The encrypted text should be the same when encrypted again.");
}
@Test
public void testLongPlainText() {
String longText = "This is a significantly longer piece of text to test the encryption and decryption capabilities of the Columnar Transposition Cipher. It should handle long strings gracefully.";
String encryptedText = ColumnarTranspositionCipher.encrypt(longText, keyword);
String decryptedText = ColumnarTranspositionCipher.decrypt();
assertEquals(longText.replaceAll(" ", ""), decryptedText.replaceAll(" ", ""), "The decrypted text should match the original long plaintext, ignoring spaces.");
assertEquals(encryptedText, ColumnarTranspositionCipher.encrypt(longText, keyword), "The encrypted text should be the same when encrypted again.");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/ADFGVXCipherTest.java | src/test/java/com/thealgorithms/ciphers/ADFGVXCipherTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class ADFGVXCipherTest {
private final ADFGVXCipher adfgvxCipher = new ADFGVXCipher();
@Test
void testEncrypt() {
String message = "attack at 1200am";
String key = "PRIVACY";
String encrypted = adfgvxCipher.encrypt(message, key);
assertEquals("DGDDDAGDDGAFADDFDADVDVFAADVX", encrypted);
}
@Test
void testDecrypt() {
String encrypted = "DGDDDAGDDGAFADDFDADVDVFAADVX";
String key = "PRIVACY";
String decrypted = adfgvxCipher.decrypt(encrypted, key);
assertEquals("ATTACKAT1200AM", decrypted);
}
@Test
void testEmptyInput() {
String encrypted = adfgvxCipher.encrypt("", "PRIVACY");
String decrypted = adfgvxCipher.decrypt("", "PRIVACY");
assertEquals("", encrypted);
assertEquals("", decrypted);
}
@Test
void testShortKey() {
String message = "TESTING";
String key = "A";
String encrypted = adfgvxCipher.encrypt(message, key);
String decrypted = adfgvxCipher.decrypt(encrypted, key);
assertEquals("TESTING", decrypted);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/XORCipherTest.java | src/test/java/com/thealgorithms/ciphers/XORCipherTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class XORCipherTest {
@Test
void xorEncryptDecryptTest() {
String plaintext = "My t&xt th@t will be ençrypted...";
String key = "My ç&cret key!";
String cipherText = XORCipher.encrypt(plaintext, key);
String decryptedText = XORCipher.decrypt(cipherText, key);
assertEquals("My t&xt th@t will be ençrypted...", decryptedText);
}
@Test
void testEmptyPlaintext() {
String plaintext = "";
String key = "anykey";
String cipherText = XORCipher.encrypt(plaintext, key);
String decryptedText = XORCipher.decrypt(cipherText, key);
assertEquals("", cipherText);
assertEquals("", decryptedText);
}
@Test
void testEmptyKey() {
String plaintext = "Hello World!";
String key = "";
assertThrows(IllegalArgumentException.class, () -> XORCipher.encrypt(plaintext, key));
assertThrows(IllegalArgumentException.class, () -> XORCipher.decrypt(plaintext, key));
}
@Test
void testShortKey() {
String plaintext = "Short message";
String key = "k";
String cipherText = XORCipher.encrypt(plaintext, key);
String decryptedText = XORCipher.decrypt(cipherText, key);
assertEquals(plaintext, decryptedText);
}
@Test
void testNonASCIICharacters() {
String plaintext = "こんにちは世界"; // "Hello World" in Japanese (Konichiwa Sekai)
String key = "key";
String cipherText = XORCipher.encrypt(plaintext, key);
String decryptedText = XORCipher.decrypt(cipherText, key);
assertEquals(plaintext, decryptedText);
}
@Test
void testSameKeyAndPlaintext() {
String plaintext = "samekey";
String key = "samekey";
String cipherText = XORCipher.encrypt(plaintext, key);
String decryptedText = XORCipher.decrypt(cipherText, key);
assertEquals(plaintext, decryptedText);
}
@Test
void testLongPlaintextShortKey() {
String plaintext = "This is a long plaintext message.";
String key = "key";
String cipherText = XORCipher.encrypt(plaintext, key);
String decryptedText = XORCipher.decrypt(cipherText, key);
assertEquals(plaintext, decryptedText);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java | src/test/java/com/thealgorithms/ciphers/PlayfairTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class PlayfairTest {
@Test
public void testEncryption() {
PlayfairCipher playfairCipher = new PlayfairCipher("KEYWORD");
String plaintext = "HELLO";
String encryptedText = playfairCipher.encrypt(plaintext);
assertEquals("GYIZSC", encryptedText);
}
@Test
public void testDecryption() {
PlayfairCipher playfairCipher = new PlayfairCipher("KEYWORD");
String encryptedText = "UDRIYP";
String decryptedText = playfairCipher.decrypt(encryptedText);
assertEquals("NEBFVH", decryptedText);
}
@Test
public void testEncryptionAndDecryption() {
PlayfairCipher playfairCipher = new PlayfairCipher("KEYWORD");
String plaintext = "PLAYFAIR";
String encryptedText = playfairCipher.encrypt(plaintext);
String decryptedText = playfairCipher.decrypt(encryptedText);
assertEquals(plaintext, decryptedText);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/RSATest.java | src/test/java/com/thealgorithms/ciphers/RSATest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.math.BigInteger;
import org.junit.jupiter.api.Test;
class RSATest {
private final RSA rsa = new RSA(1024);
@Test
void testEncryptDecryptString() {
String originalMessage = "Such secure";
String encryptedMessage = rsa.encrypt(originalMessage);
String decryptedMessage = rsa.decrypt(encryptedMessage);
assertEquals(originalMessage, decryptedMessage);
}
@Test
void testEncryptDecryptBigInteger() {
BigInteger originalMessage = new BigInteger("12345678901234567890");
BigInteger encryptedMessage = rsa.encrypt(originalMessage);
BigInteger decryptedMessage = rsa.decrypt(encryptedMessage);
assertEquals(originalMessage, decryptedMessage);
}
@Test
void testEmptyMessage() {
String originalMessage = "";
assertThrows(IllegalArgumentException.class, () -> rsa.encrypt(originalMessage));
assertThrows(IllegalArgumentException.class, () -> rsa.decrypt(originalMessage));
}
@Test
void testDifferentKeySizes() {
// Testing with 512-bit RSA keys
RSA smallRSA = new RSA(512);
String originalMessage = "Test with smaller key";
String encryptedMessage = smallRSA.encrypt(originalMessage);
String decryptedMessage = smallRSA.decrypt(encryptedMessage);
assertEquals(originalMessage, decryptedMessage);
// Testing with 2048-bit RSA keys
RSA largeRSA = new RSA(2048);
String largeOriginalMessage = "Test with larger key";
String largeEncryptedMessage = largeRSA.encrypt(largeOriginalMessage);
String largeDecryptedMessage = largeRSA.decrypt(largeEncryptedMessage);
assertEquals(largeOriginalMessage, largeDecryptedMessage);
}
@Test
void testSpecialCharacters() {
String originalMessage = "Hello, RSA! @2024#";
String encryptedMessage = rsa.encrypt(originalMessage);
String decryptedMessage = rsa.decrypt(encryptedMessage);
assertEquals(originalMessage, decryptedMessage);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/AutokeyTest.java | src/test/java/com/thealgorithms/ciphers/AutokeyTest.java | package com.thealgorithms.ciphers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class AutokeyCipherTest {
Autokey autokeyCipher = new Autokey();
@Test
void autokeyEncryptTest() {
// given
String plaintext = "MEET AT DAWN";
String keyword = "QUEEN";
// when
String cipherText = autokeyCipher.encrypt(plaintext, keyword);
// then
assertEquals("CYIXNFHEPN", cipherText);
}
@Test
void autokeyDecryptTest() {
// given
String ciphertext = "CYIX NF HEPN";
String keyword = "QUEEN";
// when
String plainText = autokeyCipher.decrypt(ciphertext, keyword);
// then
assertEquals("MEETATDAWN", plainText);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/a5/A5CipherTest.java | src/test/java/com/thealgorithms/ciphers/a5/A5CipherTest.java | package com.thealgorithms.ciphers.a5;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.util.BitSet;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class A5CipherTest {
private A5Cipher a5Cipher;
@BeforeEach
void setUp() {
// Initialize the session key and frame counter
final var sessionKey = BitSet.valueOf(new long[] {0b1010101010101010L});
final var frameCounter = BitSet.valueOf(new long[] {0b0000000000000001L});
a5Cipher = new A5Cipher(sessionKey, frameCounter);
}
@Test
void testEncryptWithValidInput() {
BitSet plainText = BitSet.valueOf(new long[] {0b1100110011001100L}); // Example plaintext
BitSet encrypted = a5Cipher.encrypt(plainText);
// The expected result depends on the key stream generated.
// In a real test, you would replace this with the actual expected result.
// For now, we will just assert that the encrypted result is not equal to the plaintext.
assertNotEquals(plainText, encrypted, "Encrypted output should not equal plaintext");
}
@Test
void testEncryptAllOnesInput() {
BitSet plainText = BitSet.valueOf(new long[] {0b1111111111111111L}); // All ones
BitSet encrypted = a5Cipher.encrypt(plainText);
// Similar to testEncryptWithValidInput, ensure that output isn't the same as input
assertNotEquals(plainText, encrypted, "Encrypted output should not equal plaintext of all ones");
}
@Test
void testEncryptAllZerosInput() {
BitSet plainText = new BitSet(); // All zeros
BitSet encrypted = a5Cipher.encrypt(plainText);
// Check that the encrypted output is not the same
assertNotEquals(plainText, encrypted, "Encrypted output should not equal plaintext of all zeros");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/a5/A5KeyStreamGeneratorTest.java | src/test/java/com/thealgorithms/ciphers/a5/A5KeyStreamGeneratorTest.java | package com.thealgorithms.ciphers.a5;
import static com.thealgorithms.ciphers.a5.A5KeyStreamGenerator.FRAME_COUNTER_LENGTH;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.BitSet;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class A5KeyStreamGeneratorTest {
private A5KeyStreamGenerator keyStreamGenerator;
private BitSet frameCounter;
@BeforeEach
void setUp() {
keyStreamGenerator = new A5KeyStreamGenerator();
// Initialize session key and frame counter for testing
final var sessionKey = BitSet.valueOf(new long[] {0b1010101010101010L}); // Example 16-bit key
frameCounter = BitSet.valueOf(new long[] {0b0000000000000001L}); // Example 16-bit frame counter
keyStreamGenerator.initialize(sessionKey, frameCounter);
}
@Test
void testInitialization() {
// Verify that the internal state is set up correctly
assertNotNull(keyStreamGenerator, "KeyStreamGenerator should be initialized");
}
@Test
void testIncrementFrameCounter() {
// Generate key stream to increment the frame counter
keyStreamGenerator.getNextKeyStream();
// The frame counter should have been incremented
BitSet incrementedFrameCounter = keyStreamGenerator.getFrameCounter();
// Check if the incremented frame counter is expected
BitSet expectedFrameCounter = (BitSet) frameCounter.clone();
Utils.increment(expectedFrameCounter, FRAME_COUNTER_LENGTH);
assertEquals(expectedFrameCounter, incrementedFrameCounter, "Frame counter should be incremented after generating key stream");
}
@Test
void testGetNextKeyStreamProducesDifferentOutputs() {
// Generate a key stream
BitSet firstKeyStream = keyStreamGenerator.getNextKeyStream();
// Generate another key stream
BitSet secondKeyStream = keyStreamGenerator.getNextKeyStream();
// Assert that consecutive key streams are different
assertNotEquals(firstKeyStream, secondKeyStream, "Consecutive key streams should be different");
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java | src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java | package com.thealgorithms.ciphers.a5;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.util.BitSet;
import org.junit.jupiter.api.Test;
// Basic tests for sanity check
class LFSRTest {
// Represents 0100 1110 0010 1111 0100 1101 0111 1100 0001 1110 1011 1000 1000 1011 0011 1010
// But we start reverse way because bitset starts from most right (1010)
byte[] sessionKeyBytes = {
58,
(byte) 139,
(byte) 184,
30,
124,
77,
47,
78,
};
// Represents 11 1010 1011 0011 1100 1011
byte[] frameCounterBytes = {(byte) 203, (byte) 179, 58};
@Test
void initialize() {
BitSet sessionKey = BitSet.valueOf(sessionKeyBytes);
BitSet frameCounter = BitSet.valueOf(frameCounterBytes);
BitSet expected = new BitSet(19);
expected.set(0);
expected.set(1);
expected.set(3);
expected.set(4);
expected.set(5);
expected.set(7);
expected.set(9);
expected.set(10);
expected.set(11);
expected.set(12);
expected.set(13);
expected.set(15);
expected.set(16);
expected.set(17);
LFSR lfsr0 = new LFSR(19, 8, new int[] {13, 16, 17, 18});
lfsr0.initialize(sessionKey, frameCounter);
assertEquals(expected.toString(), lfsr0.toString());
}
@Test
void clock() {
BitSet sessionKey = BitSet.valueOf(sessionKeyBytes);
BitSet frameCounter = BitSet.valueOf(frameCounterBytes);
LFSR lfsr0 = new LFSR(19, 8, new int[] {13, 16, 17, 18});
lfsr0.initialize(sessionKey, frameCounter);
BitSet expected = new BitSet(19);
expected.set(0);
expected.set(1);
expected.set(2);
expected.set(4);
expected.set(5);
expected.set(6);
expected.set(8);
expected.set(10);
expected.set(11);
expected.set(12);
expected.set(13);
expected.set(14);
expected.set(16);
expected.set(17);
expected.set(18);
lfsr0.clock();
assertEquals(expected.toString(), lfsr0.toString());
}
@Test
void getClockBit() {
BitSet sessionKey = BitSet.valueOf(sessionKeyBytes);
BitSet frameCounter = BitSet.valueOf(frameCounterBytes);
LFSR lfsr0 = new LFSR(19, 8, new int[] {13, 16, 17, 18});
assertFalse(lfsr0.getClockBit());
lfsr0.initialize(sessionKey, frameCounter);
assertFalse(lfsr0.getClockBit());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/CombSortTest.java | src/test/java/com/thealgorithms/sorts/CombSortTest.java | package com.thealgorithms.sorts;
public class CombSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new CombSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/sorts/CircleSortTest.java | src/test/java/com/thealgorithms/sorts/CircleSortTest.java | package com.thealgorithms.sorts;
class CircleSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new CircleSort();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.