Skip to content

Commit 1e5faa8

Browse files
authored
Refactor PatriciaTrieTest with additional test cases
1 parent 428d04b commit 1e5faa8

File tree

1 file changed

+64
-4
lines changed

1 file changed

+64
-4
lines changed
Lines changed: 64 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
1-
@Test
1+
package com.thealgorithms.datastructures.tries;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class PatriciaTrieTest {
8+
9+
@Test
210
void insert_splitCausesNewBranch_incrementsSize() {
311
var t = new PatriciaTrie<Integer>();
4-
t.put("romane", 1); // An initial key
12+
t.put("romane", 1);
513
assertEquals(1, t.size());
614

7-
// This insertion will split the "romane" edge at "roman"
8-
// and create a new branch for "us". This is where the bug occurred.
15+
// Split "romane" at "roman", create branch "us"
916
t.put("romanus", 2);
1017

1118
assertEquals(2, t.size(), "Size should increment when a split creates a new key branch");
@@ -14,3 +21,56 @@ void insert_splitCausesNewBranch_incrementsSize() {
1421
assertEquals(1, t.get("romane"));
1522
assertEquals(2, t.get("romanus"));
1623
}
24+
25+
@Test
26+
void basicPutGetContainsAndRemove() {
27+
var t = new PatriciaTrie<String>();
28+
assertTrue(t.isEmpty());
29+
30+
t.put("", "root"); // empty key
31+
t.put("a", "x");
32+
t.put("ab", "y");
33+
t.put("abc", "z");
34+
35+
assertEquals(4, t.size());
36+
assertEquals("root", t.get(""));
37+
assertEquals("x", t.get("a"));
38+
assertEquals("y", t.get("ab"));
39+
assertEquals("z", t.get("abc"));
40+
41+
assertTrue(t.contains("ab"));
42+
assertFalse(t.contains("abcd"));
43+
44+
assertTrue(t.startsWith("ab"));
45+
assertTrue(t.startsWith("abc"));
46+
assertFalse(t.startsWith("zzz"));
47+
48+
assertTrue(t.remove("ab"));
49+
assertFalse(t.contains("ab"));
50+
assertEquals(3, t.size());
51+
52+
// removing non-existent
53+
assertFalse(t.remove("ab"));
54+
assertEquals(3, t.size());
55+
}
56+
57+
@Test
58+
void updatesDoNotIncreaseSize() {
59+
var t = new PatriciaTrie<Integer>();
60+
t.put("apple", 1);
61+
t.put("apple", 2);
62+
assertEquals(1, t.size());
63+
assertEquals(2, t.get("apple"));
64+
}
65+
66+
@Test
67+
void nullContracts() {
68+
var t = new PatriciaTrie<Integer>();
69+
assertThrows(IllegalArgumentException.class, () -> t.put(null, 1));
70+
assertThrows(IllegalArgumentException.class, () -> t.put("x", null));
71+
assertThrows(IllegalArgumentException.class, () -> t.get(null));
72+
assertThrows(IllegalArgumentException.class, () -> t.contains(null));
73+
assertThrows(IllegalArgumentException.class, () -> t.remove(null));
74+
assertThrows(IllegalArgumentException.class, () -> t.startsWith(null));
75+
}
76+
}

0 commit comments

Comments
 (0)