47 lines
1.4 KiB
Python
47 lines
1.4 KiB
Python
import unittest
|
|
from z_algorithm import z_function, search
|
|
|
|
|
|
class TestZ(unittest.TestCase):
|
|
def test_empty(self):
|
|
self.assertEqual(z_function(""), [])
|
|
|
|
def test_single(self):
|
|
self.assertEqual(z_function("a"), [1])
|
|
|
|
def test_all_same(self):
|
|
self.assertEqual(z_function("aaaa"), [4, 3, 2, 1])
|
|
|
|
def test_ababa(self):
|
|
self.assertEqual(z_function("ababa"), [5, 0, 3, 0, 1])
|
|
|
|
def test_search_basic(self):
|
|
self.assertEqual(search("ab", "abxab"), [0, 3])
|
|
|
|
def test_search_overlap(self):
|
|
self.assertEqual(search("aa", "aaaa"), [0, 1, 2])
|
|
|
|
def test_search_empty_pattern(self):
|
|
self.assertEqual(search("", "abc"), [0, 1, 2, 3])
|
|
|
|
def test_search_none(self):
|
|
self.assertEqual(search("xyz", "abc"), [])
|
|
|
|
def test_search_full_match(self):
|
|
self.assertEqual(search("abc", "abc"), [0])
|
|
|
|
def test_random_brute(self):
|
|
import random, string
|
|
for _ in range(200):
|
|
n = random.randint(0, 40)
|
|
alpha = "ab"
|
|
s = "".join(random.choice(alpha) for _ in range(n))
|
|
p = "".join(random.choice(alpha) for _ in range(random.randint(0, 6)))
|
|
# brute
|
|
brute = [i for i in range(len(s) + 1) if s.startswith(p, i)] if p else list(range(len(s) + 1))
|
|
self.assertEqual(search(p, s), brute, (s, p))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|