def test_is_child(self): """Test is child.""" db = DB() root = db.add_root('val1') child = db.add_to_parent(root, 'val2') grandson = db.add_to_parent(child, 'val3') assert db.is_child(child.db_id, root.db_id) is True assert db.is_child(grandson.db_id, root.db_id) is False
def test_get_node_params(self): """Test get node params.""" db = DB() root = db.add_root('val1') db.add_to_parent(root, 'val2', is_deleted=True) params = db.get_node_params(1) assert params.db_id == 1 assert params.value == 'val2' assert params.is_deleted is True
def test_get_parent_id(self): """Test get parent id.""" db = DB() root = db.add_root('val1') db.add_to_parent(root, 'val2', is_deleted=True) parent_id = db.get_parent_id(1) assert parent_id == 0 parent_id = db.get_parent_id(0) assert parent_id is None with pytest.raises(KeyError): parent_id = db.get_parent_id(4)
def test_to_parent_fail_unknown_parent(self): """Test add to parent fail. case: unknown parent. """ db = DB() db.add_root('val1') with pytest.raises(ValueError): db.add_to_parent(3, 'val2') unknown_node = Node('val2') unknown_node._db_id = 3 with pytest.raises(ValueError): db.add_to_parent(unknown_node, 'val2')
def test_update_node(self): """Test update node.""" db = DB() root = db.add_root('val1') child = db.add_to_parent(root, 'val2') child2 = db.add_to_parent(child, 'val3') new_value = 'val4' db.update_node( child.db_id, new_value, is_deleted=True, ) assert child.value == new_value assert child.is_deleted is True assert child2.is_deleted is True
def test_to_parent(self): """Test add to parent.""" db = DB() root = db.add_root('val1') child1 = db.add_to_parent(root, 'val2') child2 = db.add_to_parent(child1.db_id, 'val3', is_deleted=True) assert child1.is_deleted is False assert child2.is_deleted is True assert root.db_id == 0 assert child1.db_id == 1 assert child2.db_id == 2 assert len(db.nodes) == 3 assert child2.parent == child1 assert child1.children == [child2] assert child1.parent == root assert root.children == [child1]
def save(self, db: DB): """Save cache to db.""" # new created nodes appended to the end of dict # in python >= 3.6 dicts are ordered deleted = [] for _cache_id, node in self.cache_nodes.items(): db_id = node.db_id if db_id is not None: deleted_children = db.update_node( db_id, node.value, node.is_deleted, ) if deleted_children: deleted.extend(deleted_children) continue parent = node.parent if parent is None: raise RuntimeError('In cache all new nodes is subnodes') new_node = db.add_to_parent( parent.db_id, node.value, node.is_deleted, ) # now new node have db_id node.db_id = new_node.db_id self.db_nodes[new_node.db_id] = node # Case when delete root node. # But in cache we have not connection from # some subnode to this root. # This subnode should be deleted too. for db_node in deleted: cache_node = self.db_nodes.get(db_node.db_id) if cache_node: cache_node.delete()