def test_id_generator(): min_id = 10 max_id = 20 id_gen = IdGenerator(min_id, max_id) test_id = 5 assert not id_gen.reserve_id(test_id) test_id = 25 assert not id_gen.reserve_id(test_id) test_id = 15 assert not id_gen.is_id_used(test_id) assert id_gen.reserve_id(test_id) assert id_gen.is_id_used(test_id) assert id_gen.release_id(test_id) assert not id_gen.release_id(test_id) assert not id_gen.is_id_used(test_id) for idx in range(min_id, max_id + 1): new_id = id_gen.get_new_id() assert idx == new_id print 'ID generator where all IDs were assigned:' print str(id_gen) assert id_gen.get_new_id() is None assert not id_gen.reserve_id(test_id) for idx in range(min_id, max_id + 1): assert id_gen.release_id(idx) print 'ID generator where all IDs were released:' print str(id_gen) assert id_gen.reserve_id(min_id) assert id_gen.release_id(min_id)
def test_id_alloc_resv(): id_gen = IdGenerator() max_id = 100 alloc_id_set = set() for exp_id in range(1, max_id + 1): alloc_id = id_gen.get_new_id() assert exp_id == alloc_id assert alloc_id not in alloc_id_set assert id_gen.is_id_used(alloc_id) assert id_gen.max_resved_id == alloc_id alloc_id_set.add(alloc_id) for exp_id in range(max_id + 1, max_id * 2 + 1): assert id_gen.reserve_id(exp_id) assert id_gen.is_id_used(exp_id) # reserve used ID will fail assert not id_gen.reserve_id(exp_id) assert id_gen.max_resved_id == exp_id id_list = list(alloc_id_set) rel_id_set = set() for idx in range(max_id / 2): test_id = get_rand_list_item(id_list, True) assert id_gen.release_id(test_id) # release non-existent ID will fail assert not id_gen.release_id(test_id) assert not id_gen.is_id_used(test_id) rel_id_set.add(test_id) sorted_list = sorted(rel_id_set) for exp_id in sorted_list: alloc_id = id_gen.get_new_id() # test if ID allocation is always from the lowest available one assert exp_id == alloc_id assert id_gen.max_resved_id == max_id * 2 for test_id in range(1, max_id * 2 + 1): assert id_gen.release_id(test_id) assert len(id_gen.resved_ids) == 0 assert id_gen.avail_id == 1 assert id_gen.max_resved_id is None