def test_parent_read_only(): """ Test that the parent field cannot be assigned after construction. """ t = Tree(None) with pytest.raises(AttributeError): t.parent = None
def test_data_read_only(): """ Test that the data on a Tree cannot be assigned after construction. """ t = Tree(None) with pytest.raises(AttributeError): t.data = 0
def _copy(self) -> None: """ Internal method to copy the constructed Tree in memory. """ new_root: Tree[T] = Tree(self.root.data) new_current = None if self.current is self.root: new_current = new_root queue = [(new_root, self.root._children)] while queue: new_parent, children = queue.pop() new_children = [] for child in children: new_child: Tree[T] = Tree(child.data) new_child._parent = new_parent new_children.append(new_child) queue.append((new_child, child._children)) if self.current is child: new_current = new_child new_parent._children = new_children self.root = new_root self.current = new_current
def test_minimal_tree_creation(): """ Test creating the minimal tree using the constructor. """ t = Tree(None) assert t.data is None assert t.parent is None assert len(t) == 0
def create_root(self, data: T) -> None: """ Creates the root of the tree. This is the first step in Tree building. This should be called when a TreeBuilder is first created. Args: data: The optional data to put on the root node. """ self.root = Tree(data) self.current = self.root
def add_child(self, data, move=False): """ Adds a child to the current cursor location's node. Children indices are directly related to the order of their creation. Args: data: The data to put on the created child. move: Flag to indicate if the cursor should move to this child. Raises: ValueError: If the TreeBuilder's root has not been initialized. """ self._assert_initialization_status() self._copy_if_necessary() child = Tree() child._data = data child._parent = self.current self.current._children.append(child) if move: l = len(self.current) self.move_to_child(l - 1)