def _is_valid_optional(content_type: str) -> bool: """ Evaluate whether the format of an 'optional' content type in a protocol specification is valid. :param content_type: an 'optional' content type. :return: Boolean result """ content_type = content_type.strip() if not content_type.startswith("pt:optional"): return False if not _has_matched_brackets(content_type): return False if not _has_brackets(content_type): return False sub_types = _get_sub_types_of_compositional_types(content_type) if len(sub_types) != 1: return False sub_type = sub_types[0] return (_is_valid_ct(sub_type) or _is_valid_pt(sub_type) or _is_valid_set(sub_type) or _is_valid_list(sub_type) or _is_valid_dict(sub_type) or _is_valid_union(sub_type))
def _is_valid_dict(content_type: str) -> bool: """ Evaluate whether the format of a 'dict' content type in a protocol specification is valid. :param content_type: a 'dict' content type. :return: Boolean result """ content_type = content_type.strip() if not content_type.startswith("pt:dict"): return False if not _has_matched_brackets(content_type): return False if not _has_brackets(content_type): return False sub_types = _get_sub_types_of_compositional_types(content_type) if len(sub_types) != 2: return False sub_type_1 = sub_types[0] sub_type_2 = sub_types[1] return _is_valid_pt(sub_type_1) and _is_valid_pt(sub_type_2)
def _is_valid_union(content_type: str) -> bool: """ Evaluate whether the format of a 'union' content type in a protocol specification is valid. :param content_type: an 'union' content type. :return: Boolean result """ content_type = content_type.strip() if not content_type.startswith("pt:union"): return False if not _has_matched_brackets(content_type): return False if not _has_brackets(content_type): return False sub_types = _get_sub_types_of_compositional_types(content_type) # check there are at least two subtypes in the union if len(sub_types) < 2: return False # check there are no duplicate subtypes in the union sub_types_set = set(sub_types) if len(sub_types) != len(sub_types_set): return False for sub_type in sub_types: if not (_is_valid_ct(sub_type) or _is_valid_pt(sub_type) or _is_valid_set(sub_type) or _is_valid_list(sub_type) or _is_valid_dict(sub_type)): return False return True
def test_has_matched_brackets(self, ): """Positive test the '_has_matched_brackets' method.""" valid_text_1 = "[so[met[hi]]ng]" assert _has_matched_brackets(valid_text_1) is True valid_text_2 = "[[][[]]]" assert _has_matched_brackets(valid_text_2) is True valid_text_3 = "[[[[[[[]]]]]]]" assert _has_matched_brackets(valid_text_3) is True invalid_text_1 = "[]]som[]et[hi[ng][sf]" assert _has_matched_brackets(invalid_text_1) is False invalid_text_2 = "[]][][[][]" assert _has_matched_brackets(invalid_text_2) is False invalid_text_3 = "[]]" assert _has_matched_brackets(invalid_text_3) is False invalid_text_4 = "[[]" assert _has_matched_brackets(invalid_text_4) is False