我基于@black_dragon 的思想编写了这个类,并支持深度验证。以下是如何使用它(从测试用例复制):
def test_index_with_sample_case_for_depth_2(self):
idx = HierarchicalIndex(2)
# A
idx.insert(1, 'A', 'X')
idx.insert(2, 'A', 'X')
idx.insert(3, 'A', 'X')
idx.insert(4, 'A', 'Y')
idx.insert(5, 'A', 'Y')
idx.insert(10, 'A', 'Z')
idx.insert(11, 'A', 'Z')
#B
idx.insert(6, 'B', 'X')
idx.insert(7, 'B', 'X')
idx.insert(8, 'B', 'Y')
assert_that(idx.get('A'), equal_to([1, 2, 3, 4, 5, 10, 11]))
assert_that(idx.get('A', 'Y'), equal_to([4, 5]))
assert_that(idx.get('B'), equal_to([6, 7, 8]))
assert_that(idx.get('B', 'X'), equal_to([6, 7]))
def test_index_with_sample_case_for_depth_3(self):
idx = HierarchicalIndex(3)
# A
idx.insert(1, 'A', 'X', 'i')
idx.insert(2, 'A', 'X', 'ii')
idx.insert(3, 'A', 'X', 'ii')
idx.insert(4, 'A', 'Y', 'i')
idx.insert(5, 'A', 'Y', 'ii')
idx.insert(10, 'A', 'Z', 'ii')
idx.insert(11, 'A', 'Z', 'iii')
#B
idx.insert(6, 'B', 'X', 'ii')
idx.insert(7, 'B', 'X', 'iii')
idx.insert(8, 'B', 'Y', 'i')
#same queries with case for depth 2
assert_that(idx.get('A'), equal_to([1, 2, 3, 4, 5, 10, 11]))
assert_that(idx.get('A', 'Y'), equal_to([4, 5]))
assert_that(idx.get('B'), equal_to([6, 7, 8]))
assert_that(idx.get('B', 'X'), equal_to([6, 7]))
#new queries
assert_that(idx.get('B', 'X', 'ii'), equal_to([6]))
assert_that(idx.get('A', 'X', 'ii'), equal_to([2, 3]))
并验证深度:
def test_index_should_validate_depth_in_operations(self):
# ....
# depth=3
idx = HierarchicalIndex(3)
assert_that(idx.get('A'), has_length(0))
assert_that(idx.get('A', 'X'), has_length(0))
assert_that(idx.get('A', 'X', 'i'), has_length(0))
self.assertRaises(AssertionError, lambda: idx.get('A', 'X', 'i', '1'))
self.assertRaises(AssertionError, lambda: idx.insert(1))
self.assertRaises(AssertionError, lambda: idx.insert(1, 'A'))
self.assertRaises(AssertionError, lambda: idx.insert(1, 'A', 'X'))
idx.insert(1, 'A', 'X', 'i') # should not raise anything
self.assertRaises(AssertionError, lambda: idx.insert(1, 'A', 'X', 'i', 'a'))
assert_that(idx.get('A', 'X', 'i'), equal_to([1]))