def test_get_type_from_element_path(element_path: str, leaf_type: Type[Any], provided_type: Type[Any], raise_exception: bool): """Test to see whether an type can be retrieved from the element path.""" # parse element path my_element_path = ElementPath(element_path) apparent_type: Type[Any] if raise_exception: with pytest.raises(TrestleError): if provided_type: apparent_type = my_element_path.get_type(provided_type) else: apparent_type = my_element_path.get_type() return if provided_type: apparent_type = my_element_path.get_type(provided_type) else: apparent_type = my_element_path.get_type() assert leaf_type == apparent_type
def add(element_path: ElementPath, parent_element: Element, include_optional: bool) -> None: """For a element_path, add a child model to the parent_element of a given parent_model. Args: element_path: element path of the item to create within the model parent_element: the parent element that will host the created element include_optional: whether to create optional attributes in the created element Notes: First we find the child model at the specified element path and instantiate it with default values. Then we check if there's already existing element at that path, in which case we append the child model to the existing list of dict. Then we set up an action plan to update the model (specified by file_path) in memory, create a file at the same location and write the file. We update the parent_element to prepare for next adds in the chain """ if '*' in element_path.get_full_path_parts(): raise err.TrestleError('trestle add does not support Wildcard element path.') # Get child model try: child_model = element_path.get_type(type(parent_element.get())) # Create child element with sample values child_object = gens.generate_sample_model(child_model, include_optional=include_optional) if parent_element.get_at(element_path) is not None: # The element already exists if type(parent_element.get_at(element_path)) is list: child_object = parent_element.get_at(element_path) + child_object elif type(parent_element.get_at(element_path)) is dict: child_object = {**parent_element.get_at(element_path), **child_object} else: raise err.TrestleError('Already exists and is not a list or dictionary.') except Exception as e: raise err.TrestleError(f'Bad element path. {str(e)}') update_action = UpdateAction( sub_element=child_object, dest_element=parent_element, sub_element_path=element_path ) parent_element = parent_element.set_at(element_path, child_object) return update_action, parent_element
def test_get_type_with_parent() -> None: """Test get parent type with path chain.""" parent_path = ElementPath('catalog.controls') current_path = ElementPath('controls.control', parent_path=parent_path) assert current_path.get_type(use_parent=True) == catalog.Control