def parse_yaml(content, validator=None): assert isinstance(content, (str, bytes)) if isinstance(content, bytes): content = content.decode('utf-8', 'ignore') if not content.strip(): marker = Marker(0, '') raise ParseError('No content.', marker=marker, base_format='yaml') try: token = None if validator is None else tokenize_yaml(content) data = yaml.safe_load(content) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as exc: position = getattr(exc, 'index', 0) marker = Marker(position, content) message = exc.problem raise ParseError(message, marker=marker, base_format='yaml') from None if validator is None: return data try: return validator.validate(data) except ValidationError as exc: exc.set_error_context(token, content) raise exc
def test_tokenize_floats(): token = tokenize_yaml(YAML_FLOATS) expected = ListToken([ ScalarToken(100.0, 3, 7), ScalarToken(100.0, 11, 16), ], 1, 17) assert token == expected
def test_tokenize_list(): token = tokenize_yaml(YAML_LIST) expected = ListToken([ ScalarToken(True, 3, 6), ScalarToken(False, 10, 14), ScalarToken(None, 18, 21), ], 1, 22) assert token == expected
def test_tokenize_object(): token = tokenize_yaml(YAML_OBJECT) expected = DictToken( { ScalarToken('a', 1, 1): ListToken([ ScalarToken(1, 8, 8), ScalarToken(2, 14, 14), ScalarToken(3, 20, 20) ], 6, 21), ScalarToken('b', 22, 22): ScalarToken('test', 25, 30) }, 1, 31) assert token == expected
def test_tokenize_object(): token = tokenize_yaml(YAML_OBJECT) expected = DictToken( { ScalarToken("a", 1, 1): ListToken( [ ScalarToken(1, 8, 8), ScalarToken(2, 14, 14), ScalarToken(3, 20, 20) ], 6, 21, ), ScalarToken("b", 22, 22): ScalarToken("test", 25, 30), }, 1, 31, ) assert token == expected