diff options
Diffstat (limited to '_test')
52 files changed, 2079 insertions, 1013 deletions
diff --git a/_test/lib/canonical.py b/_test/lib/canonical.py index 64f3153..af2c3cf 100644 --- a/_test/lib/canonical.py +++ b/_test/lib/canonical.py @@ -11,7 +11,6 @@ class CanonicalError(ruamel.yaml.YAMLError): class CanonicalScanner: - def __init__(self, data): try: if PY3: @@ -20,7 +19,7 @@ class CanonicalScanner: else: data = unicode(data, 'utf-8') # NOQA except UnicodeDecodeError: - raise CanonicalError("utf-8 stream is expected") + raise CanonicalError('utf-8 stream is expected') self.data = data + u'\0' self.index = 0 self.tokens = [] @@ -48,7 +47,7 @@ class CanonicalScanner: self.scan() token = self.tokens.pop(0) if choice and not isinstance(token, choice): - raise CanonicalError("unexpected token " + repr(token)) + raise CanonicalError('unexpected token ' + repr(token)) return token def get_token_value(self): @@ -65,7 +64,7 @@ class CanonicalScanner: break elif ch == u'%': self.tokens.append(self.scan_directive()) - elif ch == u'-' and self.data[self.index:self.index + 3] == u'---': + elif ch == u'-' and self.data[self.index : self.index + 3] == u'---': self.index += 3 self.tokens.append(ruamel.yaml.DocumentStartToken(None, None)) elif ch == u'[': @@ -96,18 +95,20 @@ class CanonicalScanner: elif ch == u'"': self.tokens.append(self.scan_scalar()) else: - raise CanonicalError("invalid token") + raise CanonicalError('invalid token') self.scanned = True DIRECTIVE = u'%YAML 1.1' def scan_directive(self): - if self.data[self.index:self.index + len(self.DIRECTIVE)] == self.DIRECTIVE and \ - self.data[self.index + len(self.DIRECTIVE)] in u' \n\0': + if ( + self.data[self.index : self.index + len(self.DIRECTIVE)] == self.DIRECTIVE + and self.data[self.index + len(self.DIRECTIVE)] in u' \n\0' + ): self.index += len(self.DIRECTIVE) return ruamel.yaml.DirectiveToken('YAML', (1, 1), None, None) else: - raise CanonicalError("invalid directive") + raise CanonicalError('invalid directive') def scan_alias(self): if self.data[self.index] == u'*': @@ -118,7 +119,7 @@ class CanonicalScanner: start = self.index while self.data[self.index] not in u', \n\0': self.index += 1 - value = self.data[start:self.index] + value = self.data[start : self.index] return TokenClass(value, None, None) def scan_tag(self): @@ -126,7 +127,7 @@ class CanonicalScanner: start = self.index while self.data[self.index] not in u' \n\0': self.index += 1 - value = self.data[start:self.index] + value = self.data[start : self.index] if not value: value = u'!' elif value[0] == u'!': @@ -137,15 +138,11 @@ class CanonicalScanner: value = u'!' + value return ruamel.yaml.TagToken(value, None, None) - QUOTE_CODES = { - 'x': 2, - 'u': 4, - 'U': 8, - } + QUOTE_CODES = {'x': 2, 'u': 4, 'U': 8} QUOTE_REPLACES = { u'\\': u'\\', - u'\"': u'\"', + u'"': u'"', u' ': u' ', u'a': u'\x07', u'b': u'\x08', @@ -160,7 +157,6 @@ class CanonicalScanner: u'P': u'\u2029', u'_': u'_', u'0': u'\x00', - } def scan_scalar(self): @@ -171,7 +167,7 @@ class CanonicalScanner: while self.data[self.index] != u'"': if self.data[self.index] == u'\\': ignore_spaces = False - chunks.append(self.data[start:self.index]) + chunks.append(self.data[start : self.index]) self.index += 1 ch = self.data[self.index] self.index += 1 @@ -179,16 +175,16 @@ class CanonicalScanner: ignore_spaces = True elif ch in self.QUOTE_CODES: length = self.QUOTE_CODES[ch] - code = int(self.data[self.index:self.index + length], 16) + code = int(self.data[self.index : self.index + length], 16) chunks.append(unichr(code)) self.index += length else: if ch not in self.QUOTE_REPLACES: - raise CanonicalError("invalid escape code") + raise CanonicalError('invalid escape code') chunks.append(self.QUOTE_REPLACES[ch]) start = self.index elif self.data[self.index] == u'\n': - chunks.append(self.data[start:self.index]) + chunks.append(self.data[start : self.index]) chunks.append(u' ') self.index += 1 start = self.index @@ -199,9 +195,9 @@ class CanonicalScanner: else: ignore_spaces = False self.index += 1 - chunks.append(self.data[start:self.index]) + chunks.append(self.data[start : self.index]) self.index += 1 - return ruamel.yaml.ScalarToken(u''.join(chunks), False, None, None) + return ruamel.yaml.ScalarToken("".join(chunks), False, None, None) def find_token(self): found = False @@ -233,7 +229,7 @@ class CanonicalParser: if self.check_token(ruamel.yaml.DirectiveToken, ruamel.yaml.DocumentStartToken): self.parse_document() else: - raise CanonicalError("document is expected, got " + repr(self.tokens[0])) + raise CanonicalError('document is expected, got ' + repr(self.tokens[0])) self.get_token(ruamel.yaml.StreamEndToken) self.events.append(ruamel.yaml.StreamEndEvent(None, None)) @@ -259,8 +255,11 @@ class CanonicalParser: if self.check_token(ruamel.yaml.TagToken): tag = self.get_token_value() if self.check_token(ruamel.yaml.ScalarToken): - self.events.append(ruamel.yaml.ScalarEvent(anchor, tag, (False, False), - self.get_token_value(), None, None)) + self.events.append( + ruamel.yaml.ScalarEvent( + anchor, tag, (False, False), self.get_token_value(), None, None + ) + ) elif self.check_token(ruamel.yaml.FlowSequenceStartToken): self.events.append(ruamel.yaml.SequenceStartEvent(anchor, tag, None, None)) self.parse_sequence() @@ -268,8 +267,9 @@ class CanonicalParser: self.events.append(ruamel.yaml.MappingStartEvent(anchor, tag, None, None)) self.parse_mapping() else: - raise CanonicalError("SCALAR, '[', or '{' is expected, got " + - repr(self.tokens[0])) + raise CanonicalError( + "SCALAR, '[', or '{' is expected, got " + repr(self.tokens[0]) + ) # sequence: SEQUENCE-START (node (ENTRY node)*)? ENTRY? SEQUENCE-END def parse_sequence(self): @@ -328,9 +328,7 @@ class CanonicalParser: return self.events[0] -class CanonicalLoader(CanonicalScanner, CanonicalParser, - Composer, Constructor, Resolver): - +class CanonicalLoader(CanonicalScanner, CanonicalParser, Composer, Constructor, Resolver): def __init__(self, stream): if hasattr(stream, 'read'): stream = stream.read() diff --git a/_test/lib/test_all.py b/_test/lib/test_all.py index 9e951eb..8099ec8 100644 --- a/_test/lib/test_all.py +++ b/_test/lib/test_all.py @@ -7,9 +7,11 @@ import test_appliance def main(args=None): collections = [] import test_yaml + collections.append(test_yaml) if ruamel.yaml.__with_libyaml__: import test_yaml_ext + collections.append(test_yaml_ext) test_appliance.run(collections, args) diff --git a/_test/lib/test_appliance.py b/_test/lib/test_appliance.py index a96052d..137c271 100644 --- a/_test/lib/test_appliance.py +++ b/_test/lib/test_appliance.py @@ -44,31 +44,34 @@ def find_test_filenames(directory): def parse_arguments(args): """""" - parser = argparse.ArgumentParser(usage=""" run the yaml tests. By default + parser = argparse.ArgumentParser( + usage=""" run the yaml tests. By default all functions on all appropriate test_files are run. Functions have unittest attributes that determine the required extensions to filenames that need to be available in order to run that test. E.g.\n\n python test_yaml.py test_constructor_types\n python test_yaml.py --verbose test_tokens spec-02-05\n\n The presence of an extension in the .skip attribute of a function - disables the test for that function.""") + disables the test for that function.""" + ) # ToDo: make into int and test > 0 in functions parser.add_argument( - '--verbose', '-v', action="store_true", + '--verbose', + '-v', + action='store_true', default='YAML_TEST_VERBOSE' in os.environ, - help="set verbosity output", + help='set verbosity output', ) parser.add_argument( - '--list-functions', action="store_true", + '--list-functions', + action='store_true', help="""list all functions with required file extensions for test files - """ - ) - parser.add_argument( - 'function', nargs='?', - help="""restrict function to run""", + """, ) + parser.add_argument('function', nargs='?', help="""restrict function to run""") parser.add_argument( - 'filenames', nargs='*', + 'filenames', + nargs='*', help="""basename of filename set, extensions (.code, .data) have to be a superset of those in the unittest attribute of the selected function""", @@ -194,7 +197,7 @@ def run(collections, args=None): results = [] for function in test_functions: if include_functions and function.__name__ not in include_functions: - continue + continue if function.unittest: for base, exts in test_filenames: if include_filenames and base not in include_filenames: diff --git a/_test/lib/test_build.py b/_test/lib/test_build.py index 5d19e3a..f7837eb 100644 --- a/_test/lib/test_build.py +++ b/_test/lib/test_build.py @@ -3,11 +3,14 @@ if __name__ == '__main__': import sys import os import distutils.util + build_lib = 'build/lib' - build_lib_ext = os.path.join('build', 'lib.%s-%s' % (distutils.util.get_platform(), - sys.version[0:3])) + build_lib_ext = os.path.join( + 'build', 'lib.%s-%s' % (distutils.util.get_platform(), sys.version[0:3]) + ) sys.path.insert(0, build_lib) sys.path.insert(0, build_lib_ext) import test_yaml import test_appliance + test_appliance.run(test_yaml) diff --git a/_test/lib/test_build_ext.py b/_test/lib/test_build_ext.py index 92d927e..1a58fd2 100644 --- a/_test/lib/test_build_ext.py +++ b/_test/lib/test_build_ext.py @@ -4,11 +4,14 @@ if __name__ == '__main__': import sys import os import distutils.util + build_lib = 'build/lib' - build_lib_ext = os.path.join('build', 'lib.%s-%s' % (distutils.util.get_platform(), - sys.version[0:3])) + build_lib_ext = os.path.join( + 'build', 'lib.%s-%s' % (distutils.util.get_platform(), sys.version[0:3]) + ) sys.path.insert(0, build_lib) sys.path.insert(0, build_lib_ext) import test_yaml_ext import test_appliance + test_appliance.run(test_yaml_ext) diff --git a/_test/lib/test_canonical.py b/_test/lib/test_canonical.py index 682f6ab..48a1764 100644 --- a/_test/lib/test_canonical.py +++ b/_test/lib/test_canonical.py @@ -40,7 +40,7 @@ def test_canonical_error(data_filename, canonical_filename, verbose=False): if verbose: print(exc) else: - raise AssertionError("expected an exception") + raise AssertionError('expected an exception') test_canonical_error.unittest = ['.data', '.canonical'] @@ -48,4 +48,5 @@ test_canonical_error.skip = ['.empty'] if __name__ == '__main__': import test_appliance + test_appliance.run(globals()) diff --git a/_test/lib/test_constructor.py b/_test/lib/test_constructor.py index d10ea4d..a66ff1a 100644 --- a/_test/lib/test_constructor.py +++ b/_test/lib/test_constructor.py @@ -6,6 +6,7 @@ import pprint from ruamel.yaml.compat import PY2 import datetime + try: set except NameError: @@ -20,10 +21,7 @@ def execute(code): def _make_objects(): - global MyLoader, MyDumper, MyTestClass1, MyTestClass2, MyTestClass3, YAMLobject1, \ - YAMLobject2, AnObject, AnInstance, AState, ACustomState, InitArgs, InitArgsWithState, \ - NewArgs, NewArgsWithState, Reduce, ReduceWithState, MyInt, MyList, MyDict, \ - FixedOffset, today, execute + global MyLoader, MyDumper, MyTestClass1, MyTestClass2, MyTestClass3, YAMLobject1, YAMLobject2, AnObject, AnInstance, AState, ACustomState, InitArgs, InitArgsWithState, NewArgs, NewArgsWithState, Reduce, ReduceWithState, MyInt, MyList, MyDict, FixedOffset, today, execute class MyLoader(ruamel.yaml.Loader): pass @@ -48,27 +46,29 @@ def _make_objects(): return MyTestClass1(**mapping) def represent1(representer, native): - return representer.represent_mapping("!tag1", native.__dict__) + return representer.represent_mapping('!tag1', native.__dict__) - ruamel.yaml.add_constructor("!tag1", construct1, Loader=MyLoader) + ruamel.yaml.add_constructor('!tag1', construct1, Loader=MyLoader) ruamel.yaml.add_representer(MyTestClass1, represent1, Dumper=MyDumper) class MyTestClass2(MyTestClass1, ruamel.yaml.YAMLObject): ruamel.yaml.loader = MyLoader ruamel.yaml.dumper = MyDumper - ruamel.yaml.tag = "!tag2" + ruamel.yaml.tag = '!tag2' def from_yaml(cls, constructor, node): x = constructor.construct_yaml_int(node) return cls(x=x) + from_yaml = classmethod(from_yaml) def to_yaml(cls, representer, native): return representer.represent_scalar(cls.yaml_tag, str(native.x)) + to_yaml = classmethod(to_yaml) class MyTestClass3(MyTestClass2): - ruamel.yaml.tag = "!tag3" + ruamel.yaml.tag = '!tag3' def from_yaml(cls, constructor, node): mapping = constructor.construct_mapping(node) @@ -77,10 +77,12 @@ def _make_objects(): del mapping['='] mapping['x'] = x return cls(**mapping) + from_yaml = classmethod(from_yaml) def to_yaml(cls, representer, native): return representer.represent_mapping(cls.yaml_tag, native.__dict__) + to_yaml = classmethod(to_yaml) class YAMLobject1(ruamel.yaml.YAMLObject): @@ -131,12 +133,17 @@ def _make_objects(): return self def __cmp__(self, other): - return cmp((type(self), self.foo, self.bar, self.baz), # NOQA - (type(other), other.foo, other.bar, other.baz)) + return cmp( + (type(self), self.foo, self.bar, self.baz), # NOQA + (type(other), other.foo, other.bar, other.baz), + ) def __eq__(self, other): - return type(self) is type(other) and \ - (self.foo, self.bar, self.baz) == (other.foo, other.bar, other.baz) + return type(self) is type(other) and (self.foo, self.bar, self.baz) == ( + other.foo, + other.bar, + other.baz, + ) class AnInstance: def __init__(self, foo=None, bar=None, baz=None): @@ -145,20 +152,21 @@ def _make_objects(): self.baz = baz def __cmp__(self, other): - return cmp((type(self), self.foo, self.bar, self.baz), # NOQA - (type(other), other.foo, other.bar, other.baz)) + return cmp( + (type(self), self.foo, self.bar, self.baz), # NOQA + (type(other), other.foo, other.bar, other.baz), + ) def __eq__(self, other): - return type(self) is type(other) and \ - (self.foo, self.bar, self.baz) == (other.foo, other.bar, other.baz) + return type(self) is type(other) and (self.foo, self.bar, self.baz) == ( + other.foo, + other.bar, + other.baz, + ) class AState(AnInstance): def __getstate__(self): - return { - '_foo': self.foo, - '_bar': self.bar, - '_baz': self.baz, - } + return {'_foo': self.foo, '_bar': self.bar, '_baz': self.baz} def __setstate__(self, state): self.foo = state['_foo'] @@ -259,6 +267,7 @@ try: from ruamel.ordereddict import ordereddict except ImportError: from collections import OrderedDict + # to get the right name import ... as ordereddict doesn't do that class ordereddict(OrderedDict): @@ -277,7 +286,7 @@ def _serialize_value(data): for key, value in data.items(): key = _serialize_value(key) value = _serialize_value(value) - items.append("%s: %s" % (key, value)) + items.append('%s: %s' % (key, value)) items.sort() return '{%s}' % ', '.join(items) elif isinstance(data, datetime.datetime): @@ -308,16 +317,16 @@ def test_constructor_types(data_filename, code_filename, verbose=False): pass # print('native1', native1) if verbose: - print("SERIALIZED NATIVE1:") + print('SERIALIZED NATIVE1:') print(_serialize_value(native1)) - print("SERIALIZED NATIVE2:") + print('SERIALIZED NATIVE2:') print(_serialize_value(native2)) assert _serialize_value(native1) == _serialize_value(native2), (native1, native2) finally: if verbose: - print("NATIVE1:") + print('NATIVE1:') pprint.pprint(native1) - print("NATIVE2:") + print('NATIVE2:') pprint.pprint(native2) @@ -327,23 +336,28 @@ test_constructor_types.unittest = ['.data', '.code'] def test_roundtrip_data(code_filename, roundtrip_filename, verbose=False): _make_objects() with open(code_filename, 'rb') as fp0: - value1 = fp0 .read() + value1 = fp0.read() native2 = list(ruamel.yaml.load_all(value1, Loader=MyLoader)) if len(native2) == 1: native2 = native2[0] try: - value2 = ruamel.yaml.dump(native2, Dumper=MyDumper, default_flow_style=False, - allow_unicode=True, encoding='utf-8') + value2 = ruamel.yaml.dump( + native2, + Dumper=MyDumper, + default_flow_style=False, + allow_unicode=True, + encoding='utf-8', + ) # value2 += x if verbose: - print("SERIALIZED NATIVE1:") + print('SERIALIZED NATIVE1:') print(value1) - print("SERIALIZED NATIVE2:") + print('SERIALIZED NATIVE2:') print(value2) assert value1 == value2, (value1, value2) finally: if verbose: - print("NATIVE2:") + print('NATIVE2:') pprint.pprint(native2) @@ -353,6 +367,8 @@ test_roundtrip_data.unittest = ['.data', '.roundtrip'] if __name__ == '__main__': import sys import test_constructor # NOQA + sys.modules['test_constructor'] = sys.modules['__main__'] import test_appliance + test_appliance.run(globals()) diff --git a/_test/lib/test_emitter.py b/_test/lib/test_emitter.py index 4b6fb76..fbdbb79 100644 --- a/_test/lib/test_emitter.py +++ b/_test/lib/test_emitter.py @@ -23,7 +23,7 @@ def test_emitter_on_data(data_filename, canonical_filename, verbose=False): events = list(yaml.parse(fp0)) output = yaml.emit(events) if verbose: - print("OUTPUT:") + print('OUTPUT:') print(output) new_events = list(yaml.parse(output)) _compare_events(events, new_events) @@ -38,7 +38,7 @@ def test_emitter_on_canonical(canonical_filename, verbose=False): for canonical in [False, True]: output = yaml.emit(events, canonical=canonical) if verbose: - print("OUTPUT (canonical=%s):" % canonical) + print('OUTPUT (canonical=%s):' % canonical) print(output) new_events = list(yaml.parse(output)) _compare_events(events, new_events) @@ -52,23 +52,28 @@ def test_emitter_styles(data_filename, canonical_filename, verbose=False): with open(filename, 'rb') as fp0: events = list(yaml.parse(fp0)) for flow_style in [False, True]: - for style in ['|', '>', '"', '\'', '']: + for style in ['|', '>', '"', "'", ""]: styled_events = [] for event in events: if isinstance(event, yaml.ScalarEvent): - event = yaml.ScalarEvent(event.anchor, event.tag, - event.implicit, event.value, style=style) + event = yaml.ScalarEvent( + event.anchor, event.tag, event.implicit, event.value, style=style + ) elif isinstance(event, yaml.SequenceStartEvent): - event = yaml.SequenceStartEvent(event.anchor, event.tag, - event.implicit, flow_style=flow_style) + event = yaml.SequenceStartEvent( + event.anchor, event.tag, event.implicit, flow_style=flow_style + ) elif isinstance(event, yaml.MappingStartEvent): - event = yaml.MappingStartEvent(event.anchor, event.tag, - event.implicit, flow_style=flow_style) + event = yaml.MappingStartEvent( + event.anchor, event.tag, event.implicit, flow_style=flow_style + ) styled_events.append(event) output = yaml.emit(styled_events) if verbose: - print("OUTPUT (filename=%r, flow_style=%r, style=%r)" % - (filename, flow_style, style)) + print( + 'OUTPUT (filename=%r, flow_style=%r, style=%r)' + % (filename, flow_style, style) + ) print(output) new_events = list(yaml.parse(output)) _compare_events(events, new_events) @@ -78,15 +83,18 @@ test_emitter_styles.unittest = ['.data', '.canonical'] class EventsLoader(yaml.Loader): - def construct_event(self, node): if isinstance(node, yaml.ScalarNode): mapping = {} else: mapping = self.construct_mapping(node) class_name = str(node.tag[1:]) + 'Event' - if class_name in ['AliasEvent', 'ScalarEvent', 'SequenceStartEvent', - 'MappingStartEvent']: + if class_name in [ + 'AliasEvent', + 'ScalarEvent', + 'SequenceStartEvent', + 'MappingStartEvent', + ]: mapping.setdefault('anchor', None) if class_name in ['ScalarEvent', 'SequenceStartEvent', 'MappingStartEvent']: mapping.setdefault('tag', None) @@ -94,10 +102,11 @@ class EventsLoader(yaml.Loader): mapping.setdefault('implicit', True) if class_name == 'ScalarEvent': mapping.setdefault('implicit', (False, True)) - mapping.setdefault('value', '') + mapping.setdefault('value', "") value = getattr(yaml, class_name)(**mapping) return value + # if Loader is not a composite, add this function # EventsLoader.add_constructor = yaml.constructor.Constructor.add_constructor @@ -110,7 +119,7 @@ def test_emitter_events(events_filename, verbose=False): events = list(yaml.load(fp0, Loader=EventsLoader)) output = yaml.emit(events) if verbose: - print("OUTPUT:") + print('OUTPUT:') print(output) new_events = list(yaml.parse(output)) _compare_events(events, new_events) @@ -118,4 +127,5 @@ def test_emitter_events(events_filename, verbose=False): if __name__ == '__main__': import test_appliance + test_appliance.run(globals()) diff --git a/_test/lib/test_errors.py b/_test/lib/test_errors.py index cfaa000..b43540c 100644 --- a/_test/lib/test_errors.py +++ b/_test/lib/test_errors.py @@ -4,6 +4,7 @@ from __future__ import print_function import ruamel.yaml as yaml import test_emitter import warnings + warnings.simplefilter('ignore', yaml.error.UnsafeLoaderWarning) @@ -13,9 +14,9 @@ def test_loader_error(error_filename, verbose=False): list(yaml.load_all(fp0)) except yaml.YAMLError as exc: if verbose: - print("%s:" % exc.__class__.__name__, exc) + print('%s:' % exc.__class__.__name__, exc) else: - raise AssertionError("expected an exception") + raise AssertionError('expected an exception') test_loader_error.unittest = ['.loader-error'] @@ -27,9 +28,9 @@ def test_loader_error_string(error_filename, verbose=False): list(yaml.load_all(fp0.read())) except yaml.YAMLError as exc: if verbose: - print("%s:" % exc.__class__.__name__, exc) + print('%s:' % exc.__class__.__name__, exc) else: - raise AssertionError("expected an exception") + raise AssertionError('expected an exception') test_loader_error_string.unittest = ['.loader-error'] @@ -41,9 +42,9 @@ def test_loader_error_single(error_filename, verbose=False): yaml.load(fp0.read()) except yaml.YAMLError as exc: if verbose: - print("%s:" % exc.__class__.__name__, exc) + print('%s:' % exc.__class__.__name__, exc) else: - raise AssertionError("expected an exception") + raise AssertionError('expected an exception') test_loader_error_single.unittest = ['.single-loader-error'] @@ -51,15 +52,14 @@ test_loader_error_single.unittest = ['.single-loader-error'] def test_emitter_error(error_filename, verbose=False): with open(error_filename, 'rb') as fp0: - events = list(yaml.load(fp0, - Loader=test_emitter.EventsLoader)) + events = list(yaml.load(fp0, Loader=test_emitter.EventsLoader)) try: yaml.emit(events) except yaml.YAMLError as exc: if verbose: - print("%s:" % exc.__class__.__name__, exc) + print('%s:' % exc.__class__.__name__, exc) else: - raise AssertionError("expected an exception") + raise AssertionError('expected an exception') test_emitter_error.unittest = ['.emitter-error'] @@ -70,16 +70,18 @@ def test_dumper_error(error_filename, verbose=False): code = fp0.read() try: import yaml + exec(code) except yaml.YAMLError as exc: if verbose: - print("%s:" % exc.__class__.__name__, exc) + print('%s:' % exc.__class__.__name__, exc) else: - raise AssertionError("expected an exception") + raise AssertionError('expected an exception') test_dumper_error.unittest = ['.dumper-error'] if __name__ == '__main__': import test_appliance + test_appliance.run(globals()) diff --git a/_test/lib/test_input_output.py b/_test/lib/test_input_output.py index 27f7aed..c36477f 100644 --- a/_test/lib/test_input_output.py +++ b/_test/lib/test_input_output.py @@ -9,6 +9,7 @@ import os.path from ruamel.yaml.compat import PY2, PY3, StringIO, BytesIO if PY2: + def _unicode_open(file, encoding, errors='strict'): info = codecs.lookup(encoding) if isinstance(info, tuple): @@ -21,7 +22,9 @@ if PY2: srw.encoding = encoding return srw + if PY3: + def test_unicode_input(unicode_filename, verbose=False): with open(unicode_filename, 'rb') as fp: data = fp.read().decode('utf-8') @@ -30,64 +33,77 @@ if PY3: assert output == value, (output, value) output = yaml.load(StringIO(data)) assert output == value, (output, value) - for input in [data.encode('utf-8'), - codecs.BOM_UTF8 + data.encode('utf-8'), - codecs.BOM_UTF16_BE + data.encode('utf-16-be'), - codecs.BOM_UTF16_LE + data.encode('utf-16-le')]: + for input in [ + data.encode('utf-8'), + codecs.BOM_UTF8 + data.encode('utf-8'), + codecs.BOM_UTF16_BE + data.encode('utf-16-be'), + codecs.BOM_UTF16_LE + data.encode('utf-16-le'), + ]: if verbose: - print("INPUT:", repr(input[:10]), "...") + print('INPUT:', repr(input[:10]), '...') output = yaml.load(input) assert output == value, (output, value) output = yaml.load(BytesIO(input)) assert output == value, (output, value) + + else: + def test_unicode_input(unicode_filename, verbose=False): with open(unicode_filename, 'rb') as fp: data = fp.read().decode('utf-8') value = ' '.join(data.split()) output = yaml.load(_unicode_open(StringIO(data.encode('utf-8')), 'utf-8')) assert output == value, (output, value) - for input in [data, data.encode('utf-8'), - codecs.BOM_UTF8 + data.encode('utf-8'), - codecs.BOM_UTF16_BE + data.encode('utf-16-be'), - codecs.BOM_UTF16_LE + data.encode('utf-16-le')]: + for input in [ + data, + data.encode('utf-8'), + codecs.BOM_UTF8 + data.encode('utf-8'), + codecs.BOM_UTF16_BE + data.encode('utf-16-be'), + codecs.BOM_UTF16_LE + data.encode('utf-16-le'), + ]: if verbose: - print("INPUT:", repr(input[:10]), "...") + print('INPUT:', repr(input[:10]), '...') output = yaml.load(input) assert output == value, (output, value) output = yaml.load(StringIO(input)) assert output == value, (output, value) + test_unicode_input.unittest = ['.unicode'] def test_unicode_input_errors(unicode_filename, verbose=False): with open(unicode_filename, 'rb') as fp: data = fp.read().decode('utf-8') - for input in [data.encode('latin1', 'ignore'), - data.encode('utf-16-be'), data.encode('utf-16-le'), - codecs.BOM_UTF8 + data.encode('utf-16-be'), - codecs.BOM_UTF16_BE + data.encode('utf-16-le'), - codecs.BOM_UTF16_LE + data.encode('utf-8') + b'!']: + for input in [ + data.encode('latin1', 'ignore'), + data.encode('utf-16-be'), + data.encode('utf-16-le'), + codecs.BOM_UTF8 + data.encode('utf-16-be'), + codecs.BOM_UTF16_BE + data.encode('utf-16-le'), + codecs.BOM_UTF16_LE + data.encode('utf-8') + b'!', + ]: try: yaml.load(input) except yaml.YAMLError as exc: if verbose: print(exc) else: - raise AssertionError("expected an exception") + raise AssertionError('expected an exception') try: yaml.load(BytesIO(input) if PY3 else StringIO(input)) except yaml.YAMLError as exc: if verbose: print(exc) else: - raise AssertionError("expected an exception") + raise AssertionError('expected an exception') test_unicode_input_errors.unittest = ['.unicode'] if PY3: + def test_unicode_output(unicode_filename, verbose=False): with open(unicode_filename, 'rb') as fp: data = fp.read().decode('utf-8') @@ -105,19 +121,20 @@ if PY3: stream = BytesIO() if encoding is None: try: - yaml.dump(value, stream, encoding=encoding, - allow_unicode=allow_unicode) + yaml.dump( + value, stream, encoding=encoding, allow_unicode=allow_unicode + ) except TypeError as exc: if verbose: print(exc) data4 = None else: - raise AssertionError("expected an exception") + raise AssertionError('expected an exception') else: yaml.dump(value, stream, encoding=encoding, allow_unicode=allow_unicode) data4 = stream.getvalue() if verbose: - print("BYTES:", data4[:50]) + print('BYTES:', data4[:50]) data4 = data4.decode(encoding) for copy in [data1, data2, data3, data4]: if copy is None: @@ -130,12 +147,15 @@ if PY3: if verbose: print(exc) else: - raise AssertionError("expected an exception") + raise AssertionError('expected an exception') else: copy[4:].encode('ascii') assert isinstance(data1, str), (type(data1), encoding) assert isinstance(data2, str), (type(data2), encoding) + + else: + def test_unicode_output(unicode_filename, verbose=False): with open(unicode_filename, 'rb') as fp: data = fp.read().decode('utf-8') @@ -144,8 +164,12 @@ else: data1 = yaml.dump(value, allow_unicode=allow_unicode) for encoding in [None, 'utf-8', 'utf-16-be', 'utf-16-le']: stream = StringIO() - yaml.dump(value, _unicode_open(stream, 'utf-8'), encoding=encoding, - allow_unicode=allow_unicode) + yaml.dump( + value, + _unicode_open(stream, 'utf-8'), + encoding=encoding, + allow_unicode=allow_unicode, + ) data2 = stream.getvalue() data3 = yaml.dump(value, encoding=encoding, allow_unicode=allow_unicode) stream = StringIO() @@ -159,7 +183,7 @@ else: if verbose: print(exc) else: - raise AssertionError("expected an exception") + raise AssertionError('expected an exception') else: copy[4:].encode('ascii') assert isinstance(data1, str), (type(data1), encoding) @@ -206,8 +230,7 @@ def test_file_output(unicode_filename, verbose=False): with open(filename, 'rb') as fp0: data2 = fp0.read() with open(filename, 'wb') as stream: - yaml.dump(data, stream, encoding='utf-16-le', - allow_unicode=True) + yaml.dump(data, stream, encoding='utf-16-le', allow_unicode=True) with open(filename, 'rb') as fp0: data3 = fp0.read().decode('utf-16-le')[1:].encode('utf-8') stream = _unicode_open(open(filename, 'wb'), 'utf-8') @@ -267,4 +290,5 @@ test_unicode_transfer.unittest = ['.unicode'] if __name__ == '__main__': import test_appliance + test_appliance.run(globals()) diff --git a/_test/lib/test_mark.py b/_test/lib/test_mark.py index 4e0728f..0ff2789 100644 --- a/_test/lib/test_mark.py +++ b/_test/lib/test_mark.py @@ -19,8 +19,7 @@ def test_marks(marks_filename, verbose=False): else: column += 1 index += 1 - mark = yaml.Mark(marks_filename, index, line, column, text_type(input), - index) + mark = yaml.Mark(marks_filename, index, line, column, text_type(input), index) snippet = mark.get_snippet(indent=2, max_length=79) if verbose: print(snippet) @@ -35,4 +34,5 @@ test_marks.unittest = ['.marks'] if __name__ == '__main__': import test_appliance + test_appliance.run(globals()) diff --git a/_test/lib/test_reader.py b/_test/lib/test_reader.py index 7ce0dc9..6604f24 100644 --- a/_test/lib/test_reader.py +++ b/_test/lib/test_reader.py @@ -1,7 +1,7 @@ from __future__ import absolute_import from __future__ import print_function -import codecs # NOQA +import codecs # NOQA import io from ruamel.yaml.compat import PY2 @@ -17,7 +17,7 @@ def _run_reader(data, verbose): if verbose: print(exc) else: - raise AssertionError("expected an exception") + raise AssertionError('expected an exception') def test_stream_error(error_filename, verbose=False): @@ -47,4 +47,5 @@ test_stream_error.unittest = ['.stream-error'] if __name__ == '__main__': import test_appliance + test_appliance.run(globals()) diff --git a/_test/lib/test_recursive.py b/_test/lib/test_recursive.py index e7084e7..c87f879 100644 --- a/_test/lib/test_recursive.py +++ b/_test/lib/test_recursive.py @@ -11,14 +11,12 @@ class AnInstance: def __repr__(self): try: - return "%s(foo=%r, bar=%r)" % (self.__class__.__name__, - self.foo, self.bar) + return '%s(foo=%r, bar=%r)' % (self.__class__.__name__, self.foo, self.bar) except RuntimeError: - return "%s(foo=..., bar=...)" % self.__class__.__name__ + return '%s(foo=..., bar=...)' % self.__class__.__name__ class AnInstanceWithState(AnInstance): - def __getstate__(self): return {'attributes': [self.foo, self.bar]} @@ -41,11 +39,11 @@ def test_recursive(recursive_filename, verbose=False): assert output1 == output2, (output1, output2) finally: if verbose: - print("VALUE1:", value1) - print("VALUE2:", value2) - print("OUTPUT1:") + print('VALUE1:', value1) + print('VALUE2:', value2) + print('OUTPUT1:') print(output1) - print("OUTPUT2:") + print('OUTPUT2:') print(output2) @@ -53,4 +51,5 @@ test_recursive.unittest = ['.recursive'] if __name__ == '__main__': import test_appliance + test_appliance.run(globals()) diff --git a/_test/lib/test_representer.py b/_test/lib/test_representer.py index 2c7e2c8..a83d2b2 100644 --- a/_test/lib/test_representer.py +++ b/_test/lib/test_representer.py @@ -14,8 +14,12 @@ def test_representer_types(code_filename, verbose=False): native1 = test_constructor._load_code(fp0.read()) native2 = None try: - output = yaml.dump(native1, Dumper=test_constructor.MyDumper, - allow_unicode=allow_unicode, encoding=encoding) + output = yaml.dump( + native1, + Dumper=test_constructor.MyDumper, + allow_unicode=allow_unicode, + encoding=encoding, + ) native2 = yaml.load(output, Loader=test_constructor.MyLoader) try: if native1 == native2: @@ -25,18 +29,18 @@ def test_representer_types(code_filename, verbose=False): value1 = test_constructor._serialize_value(native1) value2 = test_constructor._serialize_value(native2) if verbose: - print("SERIALIZED NATIVE1:") + print('SERIALIZED NATIVE1:') print(value1) - print("SERIALIZED NATIVE2:") + print('SERIALIZED NATIVE2:') print(value2) assert value1 == value2, (native1, native2) finally: if verbose: - print("NATIVE1:") + print('NATIVE1:') pprint.pprint(native1) - print("NATIVE2:") + print('NATIVE2:') pprint.pprint(native2) - print("OUTPUT:") + print('OUTPUT:') print(output) @@ -44,4 +48,5 @@ test_representer_types.unittest = ['.code'] if __name__ == '__main__': import test_appliance + test_appliance.run(globals()) diff --git a/_test/lib/test_resolver.py b/_test/lib/test_resolver.py index 4d1e6a4..0a04e7a 100644 --- a/_test/lib/test_resolver.py +++ b/_test/lib/test_resolver.py @@ -20,9 +20,9 @@ def test_implicit_resolver(data_filename, detect_filename, verbose=False): assert scalar.tag == correct_tag, (scalar.tag, correct_tag) finally: if verbose: - print("CORRECT TAG:", correct_tag) + print('CORRECT TAG:', correct_tag) if hasattr(node, 'value'): - print("CHILDREN:") + print('CHILDREN:') pprint.pprint(node.value) @@ -38,16 +38,19 @@ def _make_path_loader_and_dumper(): class MyDumper(yaml.Dumper): pass - yaml.add_path_resolver(u'!root', [], - Loader=MyLoader, Dumper=MyDumper) - yaml.add_path_resolver(u'!root/scalar', [], str, - Loader=MyLoader, Dumper=MyDumper) - yaml.add_path_resolver(u'!root/key11/key12/*', ['key11', 'key12'], - Loader=MyLoader, Dumper=MyDumper) - yaml.add_path_resolver(u'!root/key21/1/*', ['key21', 1], - Loader=MyLoader, Dumper=MyDumper) - yaml.add_path_resolver(u'!root/key31/*/*/key14/map', ['key31', None, None, 'key14'], dict, - Loader=MyLoader, Dumper=MyDumper) + yaml.add_path_resolver(u'!root', [], Loader=MyLoader, Dumper=MyDumper) + yaml.add_path_resolver(u'!root/scalar', [], str, Loader=MyLoader, Dumper=MyDumper) + yaml.add_path_resolver( + u'!root/key11/key12/*', ['key11', 'key12'], Loader=MyLoader, Dumper=MyDumper + ) + yaml.add_path_resolver(u'!root/key21/1/*', ['key21', 1], Loader=MyLoader, Dumper=MyDumper) + yaml.add_path_resolver( + u'!root/key31/*/*/key14/map', + ['key31', None, None, 'key14'], + dict, + Loader=MyLoader, + Dumper=MyDumper, + ) return MyLoader, MyDumper @@ -106,4 +109,5 @@ test_path_resolver_dumper.unittest = ['.data', '.path'] if __name__ == '__main__': import test_appliance + test_appliance.run(globals()) diff --git a/_test/lib/test_structure.py b/_test/lib/test_structure.py index 4d04b11..2656bbb 100644 --- a/_test/lib/test_structure.py +++ b/_test/lib/test_structure.py @@ -2,7 +2,7 @@ from __future__ import absolute_import from __future__ import print_function import ruamel.yaml as yaml -import canonical # NOQA +import canonical # NOQA import pprint from ruamel.yaml.compat import text_type, PY3 @@ -46,8 +46,12 @@ def test_structure(data_filename, structure_filename, verbose=False): with open(data_filename, 'rb') as fp: loader = yaml.Loader(fp) while loader.check_event(): - if loader.check_event(yaml.StreamStartEvent, yaml.StreamEndEvent, - yaml.DocumentStartEvent, yaml.DocumentEndEvent): + if loader.check_event( + yaml.StreamStartEvent, + yaml.StreamEndEvent, + yaml.DocumentStartEvent, + yaml.DocumentEndEvent, + ): loader.get_event() continue nodes1.append(_convert_structure(loader)) @@ -56,9 +60,9 @@ def test_structure(data_filename, structure_filename, verbose=False): assert nodes1 == nodes2, (nodes1, nodes2) finally: if verbose: - print("NODES1:") + print('NODES1:') pprint.pprint(nodes1) - print("NODES2:") + print('NODES2:') pprint.pprint(nodes2) @@ -89,9 +93,9 @@ def test_parser(data_filename, canonical_filename, verbose=False): _compare_events(events1, events2) finally: if verbose: - print("EVENTS1:") + print('EVENTS1:') pprint.pprint(events1) - print("EVENTS2:") + print('EVENTS2:') pprint.pprint(events2) @@ -109,9 +113,9 @@ def test_parser_on_canonical(canonical_filename, verbose=False): _compare_events(events1, events2, full=True) finally: if verbose: - print("EVENTS1:") + print('EVENTS1:') pprint.pprint(events1) - print("EVENTS2:") + print('EVENTS2:') pprint.pprint(events2) @@ -146,9 +150,9 @@ def test_composer(data_filename, canonical_filename, verbose=False): _compare_nodes(node1, node2) finally: if verbose: - print("NODES1:") + print('NODES1:') pprint.pprint(nodes1) - print("NODES2:") + print('NODES2:') pprint.pprint(nodes2) @@ -189,8 +193,9 @@ def _make_canonical_loader(): def construct_undefined(self, node): return self.construct_scalar(node) - MyCanonicalLoader.add_constructor(u'tag:yaml.org,2002:map', - MyCanonicalLoader.construct_mapping) + MyCanonicalLoader.add_constructor( + u'tag:yaml.org,2002:map', MyCanonicalLoader.construct_mapping + ) MyCanonicalLoader.add_constructor(None, MyCanonicalLoader.construct_undefined) @@ -207,9 +212,9 @@ def test_constructor(data_filename, canonical_filename, verbose=False): assert native1 == native2, (native1, native2) finally: if verbose: - print("NATIVE1:") + print('NATIVE1:') pprint.pprint(native1) - print("NATIVE2:") + print('NATIVE2:') pprint.pprint(native2) @@ -217,4 +222,5 @@ test_constructor.unittest = ['.data', '.canonical'] if __name__ == '__main__': import test_appliance + test_appliance.run(globals()) diff --git a/_test/lib/test_tokens.py b/_test/lib/test_tokens.py index e240efe..cdb41ba 100644 --- a/_test/lib/test_tokens.py +++ b/_test/lib/test_tokens.py @@ -53,13 +53,12 @@ def test_tokens(data_filename, tokens_filename, verbose=False): try: with open(data_filename, 'rb') as fp1: for token in yaml.scan(fp1): - if not isinstance( - token, (yaml.StreamStartToken, yaml.StreamEndToken)): + if not isinstance(token, (yaml.StreamStartToken, yaml.StreamEndToken)): tokens1.append(_replaces[token.__class__]) finally: if verbose: - print("TOKENS1:", ' '.join(tokens1)) - print("TOKENS2:", ' '.join(tokens2)) + print('TOKENS1:', ' '.join(tokens1)) + print('TOKENS2:', ' '.join(tokens2)) assert len(tokens1) == len(tokens2), (tokens1, tokens2) for token1, token2 in zip(tokens1, tokens2): assert token1 == token2, (token1, token2) @@ -84,4 +83,5 @@ test_scanner.unittest = ['.data', '.canonical'] if __name__ == '__main__': import test_appliance + test_appliance.run(globals()) diff --git a/_test/lib/test_yaml.py b/_test/lib/test_yaml.py index c650762..cf64a73 100644 --- a/_test/lib/test_yaml.py +++ b/_test/lib/test_yaml.py @@ -1,19 +1,20 @@ # coding: utf-8 -from test_mark import * # NOQA -from test_reader import * # NOQA -from test_canonical import * # NOQA -from test_tokens import * # NOQA -from test_structure import * # NOQA -from test_errors import * # NOQA -from test_resolver import * # NOQA -from test_constructor import * # NOQA -from test_emitter import * # NOQA -from test_representer import * # NOQA -from test_recursive import * # NOQA +from test_mark import * # NOQA +from test_reader import * # NOQA +from test_canonical import * # NOQA +from test_tokens import * # NOQA +from test_structure import * # NOQA +from test_errors import * # NOQA +from test_resolver import * # NOQA +from test_constructor import * # NOQA +from test_emitter import * # NOQA +from test_representer import * # NOQA +from test_recursive import * # NOQA from test_input_output import * # NOQA if __name__ == '__main__': import sys import test_appliance + sys.exit(test_appliance.run(globals())) diff --git a/_test/lib/test_yaml_ext.py b/_test/lib/test_yaml_ext.py index c4a1493..e36ddd0 100644 --- a/_test/lib/test_yaml_ext.py +++ b/_test/lib/test_yaml_ext.py @@ -173,8 +173,10 @@ def test_c_version(verbose=False): if verbose: print(_ruamel_yaml.get_version()) print(_ruamel_yaml.get_version_string()) - assert ("%s.%s.%s" % _ruamel_yaml.get_version()) == _ruamel_yaml.get_version_string(), \ - (_ruamel_yaml.get_version(), _ruamel_yaml.get_version_string()) + assert ('%s.%s.%s' % _ruamel_yaml.get_version()) == _ruamel_yaml.get_version_string(), ( + _ruamel_yaml.get_version(), + _ruamel_yaml.get_version_string(), + ) def _compare_scanners(py_data, c_data, verbose): @@ -190,20 +192,29 @@ def _compare_scanners(py_data, c_data, verbose): assert py_token.value == c_token.value, (py_token, c_token) if isinstance(py_token, ruamel.yaml.StreamEndToken): continue - py_start = (py_token.start_mark.index, py_token.start_mark.line, - py_token.start_mark.column) - py_end = (py_token.end_mark.index, py_token.end_mark.line, - py_token.end_mark.column) - c_start = (c_token.start_mark.index, c_token.start_mark.line, - c_token.start_mark.column) + py_start = ( + py_token.start_mark.index, + py_token.start_mark.line, + py_token.start_mark.column, + ) + py_end = ( + py_token.end_mark.index, + py_token.end_mark.line, + py_token.end_mark.column, + ) + c_start = ( + c_token.start_mark.index, + c_token.start_mark.line, + c_token.start_mark.column, + ) c_end = (c_token.end_mark.index, c_token.end_mark.line, c_token.end_mark.column) assert py_start == c_start, (py_start, c_start) assert py_end == c_end, (py_end, c_end) finally: if verbose: - print("PY_TOKENS:") + print('PY_TOKENS:') pprint.pprint(py_tokens) - print("C_TOKENS:") + print('C_TOKENS:') pprint.pprint(c_tokens) @@ -234,16 +245,24 @@ def _compare_parsers(py_data, c_data, verbose): c_events.append(event) assert len(py_events) == len(c_events), (len(py_events), len(c_events)) for py_event, c_event in zip(py_events, c_events): - for attribute in ['__class__', 'anchor', 'tag', 'implicit', - 'value', 'explicit', 'version', 'tags']: + for attribute in [ + '__class__', + 'anchor', + 'tag', + 'implicit', + 'value', + 'explicit', + 'version', + 'tags', + ]: py_value = getattr(py_event, attribute, None) c_value = getattr(c_event, attribute, None) assert py_value == c_value, (py_event, c_event, attribute) finally: if verbose: - print("PY_EVENTS:") + print('PY_EVENTS:') pprint.pprint(py_events) - print("C_EVENTS:") + print('C_EVENTS:') pprint.pprint(c_events) @@ -277,13 +296,25 @@ def _compare_emitters(data, verbose): assert len(events) == len(py_events), (len(events), len(py_events)) assert len(events) == len(c_events), (len(events), len(c_events)) for event, py_event, c_event in zip(events, py_events, c_events): - for attribute in ['__class__', 'anchor', 'tag', 'implicit', - 'value', 'explicit', 'version', 'tags']: + for attribute in [ + '__class__', + 'anchor', + 'tag', + 'implicit', + 'value', + 'explicit', + 'version', + 'tags', + ]: value = getattr(event, attribute, None) py_value = getattr(py_event, attribute, None) c_value = getattr(c_event, attribute, None) - if attribute == 'tag' and value in [None, u'!'] \ - and py_value in [None, u'!'] and c_value in [None, u'!']: + if ( + attribute == 'tag' + and value in [None, u'!'] + and py_value in [None, u'!'] + and c_value in [None, u'!'] + ): continue if attribute == 'explicit' and (py_value or c_value): continue @@ -291,11 +322,11 @@ def _compare_emitters(data, verbose): assert value == c_value, (event, c_event, attribute) finally: if verbose: - print("EVENTS:") + print('EVENTS:') pprint.pprint(events) - print("PY_EVENTS:") + print('PY_EVENTS:') pprint.pprint(py_events) - print("C_EVENTS:") + print('C_EVENTS:') pprint.pprint(c_events) @@ -317,6 +348,7 @@ def wrap_ext_function(function): function(*args, **kwds) finally: _tear_down() + if PY3: wrapper.__name__ = '%s_ext' % function.__name__ else: @@ -349,19 +381,33 @@ def wrap_ext(collections): assert function.unittest_name not in globals() globals()[function.unittest_name] = function -import test_tokens # NOQA -import test_structure # NOQA -import test_errors # NOQA -import test_resolver # NOQA -import test_constructor # NOQA -import test_emitter # NOQA -import test_representer # NOQA -import test_recursive # NOQA -import test_input_output # NOQA -wrap_ext([test_tokens, test_structure, test_errors, test_resolver, test_constructor, - test_emitter, test_representer, test_recursive, test_input_output]) + +import test_tokens # NOQA +import test_structure # NOQA +import test_errors # NOQA +import test_resolver # NOQA +import test_constructor # NOQA +import test_emitter # NOQA +import test_representer # NOQA +import test_recursive # NOQA +import test_input_output # NOQA + +wrap_ext( + [ + test_tokens, + test_structure, + test_errors, + test_resolver, + test_constructor, + test_emitter, + test_representer, + test_recursive, + test_input_output, + ] +) if __name__ == '__main__': import sys import test_appliance + sys.exit(test_appliance.run(globals())) diff --git a/_test/roundtrip.py b/_test/roundtrip.py index 8548969..86e4862 100644 --- a/_test/roundtrip.py +++ b/_test/roundtrip.py @@ -21,12 +21,13 @@ def dedent(data): except ValueError: pass else: - data = data[position_of_first_newline + 1:] + data = data[position_of_first_newline + 1 :] return textwrap.dedent(data) def round_trip_load(inp, preserve_quotes=None, version=None): import ruamel.yaml # NOQA + dinp = dedent(inp) return ruamel.yaml.load( dinp, @@ -38,6 +39,7 @@ def round_trip_load(inp, preserve_quotes=None, version=None): def round_trip_load_all(inp, preserve_quotes=None, version=None): import ruamel.yaml # NOQA + dinp = dedent(inp) return ruamel.yaml.load_all( dinp, @@ -47,21 +49,35 @@ def round_trip_load_all(inp, preserve_quotes=None, version=None): ) -def round_trip_dump(data, stream=None, - indent=None, block_seq_indent=None, top_level_colon_align=None, - prefix_colon=None, explicit_start=None, explicit_end=None, version=None): +def round_trip_dump( + data, + stream=None, + indent=None, + block_seq_indent=None, + top_level_colon_align=None, + prefix_colon=None, + explicit_start=None, + explicit_end=None, + version=None, +): import ruamel.yaml # NOQA - return ruamel.yaml.round_trip_dump(data, stream=stream, - indent=indent, block_seq_indent=block_seq_indent, - top_level_colon_align=top_level_colon_align, - prefix_colon=prefix_colon, - explicit_start=explicit_start, - explicit_end=explicit_end, - version=version) + + return ruamel.yaml.round_trip_dump( + data, + stream=stream, + indent=indent, + block_seq_indent=block_seq_indent, + top_level_colon_align=top_level_colon_align, + prefix_colon=prefix_colon, + explicit_start=explicit_start, + explicit_end=explicit_end, + version=version, + ) def diff(inp, outp, file_name='stdin'): import difflib + inl = inp.splitlines(True) # True for keepends outl = outp.splitlines(True) diff = difflib.unified_diff(inl, outl, file_name, 'round trip YAML') @@ -73,11 +89,20 @@ def diff(inp, outp, file_name='stdin'): sys.stdout.write(line) -def round_trip(inp, outp=None, extra=None, intermediate=None, indent=None, - block_seq_indent=None, top_level_colon_align=None, prefix_colon=None, - preserve_quotes=None, - explicit_start=None, explicit_end=None, - version=None): +def round_trip( + inp, + outp=None, + extra=None, + intermediate=None, + indent=None, + block_seq_indent=None, + top_level_colon_align=None, + prefix_colon=None, + preserve_quotes=None, + explicit_start=None, + explicit_end=None, + version=None, +): """ inp: input string to parse outp: expected output (equals input if not specified) @@ -94,23 +119,31 @@ def round_trip(inp, outp=None, extra=None, intermediate=None, indent=None, if data[k] != v: print('{0!r} <> {1!r}'.format(data[k], v)) raise ValueError - res = round_trip_dump(data, indent=indent, block_seq_indent=block_seq_indent, - top_level_colon_align=top_level_colon_align, - prefix_colon=prefix_colon, - explicit_start=explicit_start, - explicit_end=explicit_end, - version=version) + res = round_trip_dump( + data, + indent=indent, + block_seq_indent=block_seq_indent, + top_level_colon_align=top_level_colon_align, + prefix_colon=prefix_colon, + explicit_start=explicit_start, + explicit_end=explicit_end, + version=version, + ) if res != doutp: - diff(doutp, res, "input string") - print('\nroundtrip data:\n', res, sep='') + diff(doutp, res, 'input string') + print('\nroundtrip data:\n', res, sep="") assert res == doutp - res = round_trip_dump(data, indent=indent, block_seq_indent=block_seq_indent, - top_level_colon_align=top_level_colon_align, - prefix_colon=prefix_colon, - explicit_start=explicit_start, - explicit_end=explicit_end, - version=version) - print('roundtrip second round data:\n', res, sep='') + res = round_trip_dump( + data, + indent=indent, + block_seq_indent=block_seq_indent, + top_level_colon_align=top_level_colon_align, + prefix_colon=prefix_colon, + explicit_start=explicit_start, + explicit_end=explicit_end, + version=version, + ) + print('roundtrip second round data:\n', res, sep="") assert res == doutp return data @@ -120,6 +153,7 @@ def YAML(**kw): class MyYAML(ruamel.yaml.YAML): """auto dedent string parameters on load""" + def load(self, stream): if isinstance(stream, str): if stream and stream[0] == '\n': @@ -137,6 +171,7 @@ def YAML(**kw): def dump(self, data, **kw): from ruamel.yaml.compat import StringIO, BytesIO # NOQA + assert ('stream' in kw) ^ ('compare' in kw) if 'stream' in kw: return ruamel.yaml.YAML.dump(data, **kw) @@ -156,6 +191,7 @@ def YAML(**kw): def round_trip(self, stream, **kw): from ruamel.yaml.compat import StringIO, BytesIO # NOQA + assert isinstance(stream, ruamel.yaml.compat.text_type) lkw = kw.copy() if stream and stream[0] == '\n': @@ -167,7 +203,7 @@ def YAML(**kw): ruamel.yaml.YAML.dump(self, data, **lkw) res = st.getvalue() if res != outp: - diff(outp, res, "input string") + diff(outp, res, 'input string') assert res == outp return MyYAML(**kw) diff --git a/_test/test_a_dedent.py b/_test/test_a_dedent.py index 1362deb..984e1a2 100644 --- a/_test/test_a_dedent.py +++ b/_test/test_a_dedent.py @@ -4,39 +4,54 @@ from roundtrip import dedent class TestDedent: def test_start_newline(self): - x = dedent(""" + x = dedent( + """ 123 456 - """) - assert x == "123\n 456\n" + """ + ) + assert x == '123\n 456\n' def test_start_space_newline(self): # special construct to prevent stripping of following whitespac - x = dedent(" " """ + x = dedent( + ' ' + """ 123 - """) - assert x == "123\n" + """ + ) + assert x == '123\n' def test_start_no_newline(self): # special construct to prevent stripping of following whitespac - x = dedent("""\ + x = dedent( + """\ 123 456 - """) - assert x == "123\n 456\n" + """ + ) + assert x == '123\n 456\n' def test_preserve_no_newline_at_end(self): - x = dedent(""" - 123""") - assert x == "123" + x = dedent( + """ + 123""" + ) + assert x == '123' def test_preserve_no_newline_at_all(self): - x = dedent("""\ - 123""") - assert x == "123" + x = dedent( + """\ + 123""" + ) + assert x == '123' def test_multiple_dedent(self): - x = dedent(dedent(""" + x = dedent( + dedent( + """ 123 - """)) - assert x == "123\n" + """ + ) + ) + assert x == '123\n' diff --git a/_test/test_add_xxx.py b/_test/test_add_xxx.py index f2e976f..031b89f 100644 --- a/_test/test_add_xxx.py +++ b/_test/test_add_xxx.py @@ -1,7 +1,7 @@ # coding: utf-8 import re -import pytest # NOQA +import pytest # NOQA from roundtrip import dedent @@ -12,7 +12,7 @@ class Dice(tuple): return tuple.__new__(cls, [a, b]) def __repr__(self): - return "Dice(%s,%s)" % self + return 'Dice(%s,%s)' % self def dice_constructor(loader, node): @@ -27,6 +27,7 @@ def dice_representer(dumper, data): def test_dice_constructor(): import ruamel.yaml # NOQA + ruamel.yaml.add_constructor(u'!dice', dice_constructor) data = ruamel.yaml.load('initial hit points: !dice 8d4', Loader=ruamel.yaml.Loader) assert str(data) == "{'initial hit points': Dice(8,4)}" @@ -34,6 +35,7 @@ def test_dice_constructor(): def test_dice_constructor_with_loader(): import ruamel.yaml # NOQA + ruamel.yaml.add_constructor(u'!dice', dice_constructor, Loader=ruamel.yaml.Loader) data = ruamel.yaml.load('initial hit points: !dice 8d4', Loader=ruamel.yaml.Loader) assert str(data) == "{'initial hit points': Dice(8,4)}" @@ -41,20 +43,27 @@ def test_dice_constructor_with_loader(): def test_dice_representer(): import ruamel.yaml # NOQA + ruamel.yaml.add_representer(Dice, dice_representer) # ruamel.yaml 0.15.8+ no longer forces quotes tagged scalars - assert ruamel.yaml.dump(dict(gold=Dice(10, 6)), default_flow_style=False) == \ - "gold: !dice 10d6\n" + assert ( + ruamel.yaml.dump(dict(gold=Dice(10, 6)), default_flow_style=False) + == 'gold: !dice 10d6\n' + ) def test_dice_implicit_resolver(): import ruamel.yaml # NOQA + pattern = re.compile(r'^\d+d\d+$') ruamel.yaml.add_implicit_resolver(u'!dice', pattern) - assert ruamel.yaml.dump(dict(treasure=Dice(10, 20)), default_flow_style=False) == \ - 'treasure: 10d20\n' - assert ruamel.yaml.load('damage: 5d10', Loader=ruamel.yaml.Loader) == \ - dict(damage=Dice(5, 10)) + assert ( + ruamel.yaml.dump(dict(treasure=Dice(10, 20)), default_flow_style=False) + == 'treasure: 10d20\n' + ) + assert ruamel.yaml.load('damage: 5d10', Loader=ruamel.yaml.Loader) == dict( + damage=Dice(5, 10) + ) class Obj1(dict): @@ -78,6 +87,7 @@ class YAMLObj1(object): @classmethod def from_yaml(cls, loader, suffix, node): import ruamel.yaml # NOQA + obj1 = Obj1(suffix) if isinstance(node, ruamel.yaml.MappingNode): obj1.add_node(loader.construct_mapping(node)) @@ -92,22 +102,25 @@ class YAMLObj1(object): def test_yaml_obj(): import ruamel.yaml # NOQA + ruamel.yaml.add_representer(Obj1, YAMLObj1.to_yaml) ruamel.yaml.add_multi_constructor(YAMLObj1.yaml_tag, YAMLObj1.from_yaml) x = ruamel.yaml.load('!obj:x.2\na: 1', Loader=ruamel.yaml.Loader) print(x) - assert ruamel.yaml.dump(x) == '''!obj:x.2 "{'a': 1}"\n''' + assert ruamel.yaml.dump(x) == """!obj:x.2 "{'a': 1}"\n""" def test_yaml_obj_with_loader_and_dumper(): import ruamel.yaml # NOQA + ruamel.yaml.add_representer(Obj1, YAMLObj1.to_yaml, Dumper=ruamel.yaml.Dumper) - ruamel.yaml.add_multi_constructor(YAMLObj1.yaml_tag, YAMLObj1.from_yaml, - Loader=ruamel.yaml.Loader) + ruamel.yaml.add_multi_constructor( + YAMLObj1.yaml_tag, YAMLObj1.from_yaml, Loader=ruamel.yaml.Loader + ) x = ruamel.yaml.load('!obj:x.2\na: 1', Loader=ruamel.yaml.Loader) # x = ruamel.yaml.load('!obj:x.2\na: 1') print(x) - assert ruamel.yaml.dump(x) == '''!obj:x.2 "{'a': 1}"\n''' + assert ruamel.yaml.dump(x) == """!obj:x.2 "{'a': 1}"\n""" # ToDo use nullege to search add_multi_representer and add_path_resolver @@ -134,12 +147,13 @@ def test_issue_127(): @classmethod def to_yaml(cls, dumper, data): if isinstance(data.logical_id, ruamel.yaml.scalarstring.ScalarString): - style = data.logical_id.style # ruamel.yaml>0.15.8 + style = data.logical_id.style # ruamel.yaml>0.15.8 else: style = None return dumper.represent_scalar(cls.yaml_tag, data.logical_id, style=style) - document = dedent('''\ + document = dedent( + """\ AList: - !Ref One - !Ref 'Two' @@ -149,7 +163,9 @@ def test_issue_127(): CList: - Five Six - 'Seven Eight' - ''') + """ + ) data = ruamel.yaml.round_trip_load(document, preserve_quotes=True) - assert ruamel.yaml.round_trip_dump(data, indent=4, block_seq_indent=2) == \ - document.replace('\n Two and', ' Two and') + assert ruamel.yaml.round_trip_dump(data, indent=4, block_seq_indent=2) == document.replace( + '\n Two and', ' Two and' + ) diff --git a/_test/test_anchor.py b/_test/test_anchor.py index ae6469a..cb632d8 100644 --- a/_test/test_anchor.py +++ b/_test/test_anchor.py @@ -22,23 +22,30 @@ def compare(d, s): class TestAnchorsAliases: def test_anchor_id_renumber(self): from ruamel.yaml.serializer import Serializer + assert Serializer.ANCHOR_TEMPLATE == 'id%03d' - data = load(""" + data = load( + """ a: &id002 b: 1 c: 2 d: *id002 - """) - compare(data, """ + """ + ) + compare( + data, + """ a: &id001 b: 1 c: 2 d: *id001 - """) + """, + ) def test_template_matcher(self): """test if id matches the anchor template""" from ruamel.yaml.serializer import templated_id + assert templated_id(u'id001') assert templated_id(u'id999') assert templated_id(u'id1000') @@ -56,7 +63,9 @@ class TestAnchorsAliases: def test_anchor_assigned(self): from ruamel.yaml.comments import CommentedMap - data = load(""" + + data = load( + """ a: &id002 b: 1 c: 2 @@ -65,7 +74,8 @@ class TestAnchorsAliases: b: 1 c: 2 f: *etemplate - """) + """ + ) d = data['d'] assert isinstance(d, CommentedMap) assert d.yaml_anchor() is None # got dropped as it matches pattern @@ -75,7 +85,8 @@ class TestAnchorsAliases: assert e.yaml_anchor().always_dump is False def test_anchor_id_retained(self): - data = load(""" + data = load( + """ a: &id002 b: 1 c: 2 @@ -84,8 +95,11 @@ class TestAnchorsAliases: b: 1 c: 2 f: *etemplate - """) - compare(data, """ + """ + ) + compare( + data, + """ a: &id001 b: 1 c: 2 @@ -94,26 +108,33 @@ class TestAnchorsAliases: b: 1 c: 2 f: *etemplate - """) + """, + ) - @pytest.mark.skipif(platform.python_implementation() == 'Jython', - reason="Jython throws RepresenterError") + @pytest.mark.skipif( + platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' + ) def test_alias_before_anchor(self): from ruamel.yaml.composer import ComposerError + with pytest.raises(ComposerError): - data = load(""" + data = load( + """ d: *id002 a: &id002 b: 1 c: 2 - """) + """ + ) data = data def test_anchor_on_sequence(self): # as reported by Bjorn Stabell # https://bitbucket.org/ruamel/yaml/issue/7/anchor-names-not-preserved from ruamel.yaml.comments import CommentedSeq - data = load(""" + + data = load( + """ nut1: &alice - 1 - 2 @@ -123,13 +144,15 @@ class TestAnchorsAliases: nut3: - *blake - *alice - """) + """ + ) r = data['nut1'] assert isinstance(r, CommentedSeq) assert r.yaml_anchor() is not None assert r.yaml_anchor().value == 'alice' - merge_yaml = dedent(""" + merge_yaml = dedent( + """ - &CENTER {x: 1, y: 2} - &LEFT {x: 0, y: 2} - &BIG {r: 10} @@ -151,7 +174,8 @@ class TestAnchorsAliases: - <<: [*BIG, *LEFT, *SMALL] x: 1 label: center/huge - """) + """ + ) def test_merge_00(self): data = load(self.merge_yaml) @@ -171,14 +195,17 @@ class TestAnchorsAliases: def test_merge_accessible(self): from ruamel.yaml.comments import CommentedMap, merge_attrib - data = load(""" + + data = load( + """ k: &level_2 { a: 1, b2 } l: &level_1 { a: 10, c: 3 } m: <<: *level_1 c: 30 d: 40 - """) + """ + ) d = data['m'] assert isinstance(d, CommentedMap) assert hasattr(d, merge_attrib) @@ -188,7 +215,7 @@ class TestAnchorsAliases: compare(data, self.merge_yaml) def test_merge_nested(self): - yaml = ''' + yaml = """ a: <<: &content 1: plugh @@ -196,11 +223,11 @@ class TestAnchorsAliases: 0: xyzzy b: <<: *content - ''' + """ data = round_trip(yaml) # NOQA def test_merge_nested_with_sequence(self): - yaml = ''' + yaml = """ a: <<: &content <<: &y2 @@ -209,11 +236,12 @@ class TestAnchorsAliases: 0: xyzzy b: <<: [*content, *y2] - ''' + """ data = round_trip(yaml) # NOQA def test_add_anchor(self): from ruamel.yaml.comments import CommentedMap + data = CommentedMap() data_a = CommentedMap() data['a'] = data_a @@ -221,31 +249,37 @@ class TestAnchorsAliases: data['b'] = 2 data.yaml_set_anchor('klm', always_dump=True) data['a'].yaml_set_anchor('xyz', always_dump=True) - compare(data, """ + compare( + data, + """ &klm a: &xyz c: 3 b: 2 - """) + """, + ) # this is an error in PyYAML def test_reused_anchor(self): from ruamel.yaml.error import ReusedAnchorWarning - yaml = ''' + + yaml = """ - &a x: 1 - <<: *a - &a x: 2 - <<: *a - ''' + """ with pytest.warns(ReusedAnchorWarning): data = round_trip(yaml) # NOQA def test_issue_130(self): # issue 130 reported by Devid Fee import ruamel.yaml - ys = dedent("""\ + + ys = dedent( + """\ components: server: &server_component type: spark.server:ServerComponent @@ -261,14 +295,17 @@ class TestAnchorsAliases: <<: *shell_component components: server: {<<: *server_service} - """) + """ + ) data = ruamel.yaml.safe_load(ys) assert data['services']['shell']['components']['server']['port'] == 8000 def test_issue_130a(self): # issue 130 reported by Devid Fee import ruamel.yaml - ys = dedent("""\ + + ys = dedent( + """\ components: server: &server_component type: spark.server:ServerComponent @@ -285,14 +322,16 @@ class TestAnchorsAliases: <<: *shell_component components: server: {<<: *server_service} - """) + """ + ) data = ruamel.yaml.safe_load(ys) assert data['services']['shell']['components']['server']['port'] == 4000 class TestMergeKeysValues: - yaml_str = dedent("""\ + yaml_str = dedent( + """\ - &mx a: x1 b: x2 @@ -306,12 +345,14 @@ class TestMergeKeysValues: <<: *mx m: 6 <<: *my - """) + """ + ) # in the following d always has "expanded" the merges def test_merge_for(self): from ruamel.yaml import safe_load + d = safe_load(self.yaml_str) data = round_trip_load(self.yaml_str) count = 0 @@ -322,6 +363,7 @@ class TestMergeKeysValues: def test_merge_keys(self): from ruamel.yaml import safe_load + d = safe_load(self.yaml_str) data = round_trip_load(self.yaml_str) count = 0 @@ -332,6 +374,7 @@ class TestMergeKeysValues: def test_merge_values(self): from ruamel.yaml import safe_load + d = safe_load(self.yaml_str) data = round_trip_load(self.yaml_str) count = 0 @@ -342,6 +385,7 @@ class TestMergeKeysValues: def test_merge_items(self): from ruamel.yaml import safe_load + d = safe_load(self.yaml_str) data = round_trip_load(self.yaml_str) count = 0 @@ -353,6 +397,7 @@ class TestMergeKeysValues: def test_len_items_delete(self): from ruamel.yaml import safe_load from ruamel.yaml.compat import PY3 + d = safe_load(self.yaml_str) data = round_trip_load(self.yaml_str) x = data[2].items() @@ -377,13 +422,16 @@ class TestDuplicateKeyThroughAnchor: from ruamel.yaml import version_info from ruamel.yaml import safe_load, round_trip_load from ruamel.yaml.constructor import DuplicateKeyFutureWarning, DuplicateKeyError - s = dedent("""\ + + s = dedent( + """\ &anchor foo: foo: bar *anchor : duplicate key baz: bat *anchor : duplicate key - """) + """ + ) if version_info < (0, 15, 1): pass elif version_info < (0, 16, 0): @@ -402,27 +450,27 @@ class TestFullCharSetAnchors: def test_master_of_orion(self): # https://bitbucket.org/ruamel/yaml/issues/72/not-allowed-in-anchor-names # submitted by Shalon Wood - yaml_str = ''' + yaml_str = """ - collection: &Backend.Civilizations.RacialPerk items: - key: perk_population_growth_modifier - *Backend.Civilizations.RacialPerk - ''' + """ data = load(yaml_str) # NOQA def test_roundtrip_00(self): - yaml_str = ''' + yaml_str = """ - &dotted.words.here a: 1 b: 2 - *dotted.words.here - ''' + """ data = round_trip(yaml_str) # NOQA def test_roundtrip_01(self): - yaml_str = ''' + yaml_str = """ - &dotted.words.here[a, b] - *dotted.words.here - ''' + """ data = load(yaml_str) # NOQA compare(data, yaml_str.replace('[', ' [')) # an extra space is inserted diff --git a/_test/test_api_change.py b/_test/test_api_change.py index 59473fe..f191c56 100644 --- a/_test/test_api_change.py +++ b/_test/test_api_change.py @@ -16,6 +16,7 @@ class TestNewAPI: def test_duplicate_keys_00(self): from ruamel.yaml import YAML from ruamel.yaml.constructor import DuplicateKeyError + yaml = YAML() with pytest.raises(DuplicateKeyError): yaml.load('{a: 1, a: 2}') @@ -23,6 +24,7 @@ class TestNewAPI: def test_duplicate_keys_01(self): from ruamel.yaml import YAML from ruamel.yaml.constructor import DuplicateKeyError + yaml = YAML(typ='safe', pure=True) with pytest.raises(DuplicateKeyError): yaml.load('{a: 1, a: 2}') @@ -31,6 +33,7 @@ class TestNewAPI: def test_duplicate_keys_02(self): from ruamel.yaml import YAML from ruamel.yaml.constructor import DuplicateKeyError + yaml = YAML(typ='safe') with pytest.raises(DuplicateKeyError): yaml.load('{a: 1, a: 2}') @@ -38,6 +41,7 @@ class TestNewAPI: def test_issue_135(self): # reported by Andrzej Ostrowski from ruamel.yaml import YAML + data = {'a': 1, 'b': 2} yaml = YAML(typ='safe') # originally on 2.7: with pytest.raises(TypeError): @@ -46,6 +50,7 @@ class TestNewAPI: def test_issue_135_temporary_workaround(self): # never raised error from ruamel.yaml import YAML + data = {'a': 1, 'b': 2} yaml = YAML(typ='safe', pure=True) yaml.dump(data, sys.stdout) @@ -54,16 +59,18 @@ class TestNewAPI: class TestWrite: def test_dump_path(self, tmpdir): from ruamel.yaml import YAML + fn = Path(str(tmpdir)) / 'test.yaml' yaml = YAML() data = yaml.map() data['a'] = 1 data['b'] = 2 yaml.dump(data, fn) - assert fn.read_text() == "a: 1\nb: 2\n" + assert fn.read_text() == 'a: 1\nb: 2\n' def test_dump_file(self, tmpdir): from ruamel.yaml import YAML + fn = Path(str(tmpdir)) / 'test.yaml' yaml = YAML() data = yaml.map() @@ -71,10 +78,11 @@ class TestWrite: data['b'] = 2 with open(str(fn), 'w') as fp: yaml.dump(data, fp) - assert fn.read_text() == "a: 1\nb: 2\n" + assert fn.read_text() == 'a: 1\nb: 2\n' def test_dump_missing_stream(self): from ruamel.yaml import YAML + yaml = YAML() data = yaml.map() data['a'] = 1 @@ -84,6 +92,7 @@ class TestWrite: def test_dump_too_many_args(self, tmpdir): from ruamel.yaml import YAML + fn = Path(str(tmpdir)) / 'test.yaml' yaml = YAML() data = yaml.map() @@ -104,23 +113,25 @@ class TestWrite: data['a'] = 1 data['b'] = 2 yaml.dump(data, fn, transform=tr) - assert fn.read_text() == "a: 1\nb: 2\n" + assert fn.read_text() == 'a: 1\nb: 2\n' def test_print(self, capsys): from ruamel.yaml import YAML + yaml = YAML() data = yaml.map() data['a'] = 1 data['b'] = 2 yaml.dump(data, sys.stdout) out, err = capsys.readouterr() - assert out == "a: 1\nb: 2\n" + assert out == 'a: 1\nb: 2\n' class TestRead: def test_multi_load(self): # make sure reader, scanner, parser get reset from ruamel.yaml import YAML + yaml = YAML() yaml.load('a: 1') yaml.load('a: 1') # did not work in 0.15.4 @@ -130,14 +141,19 @@ class TestLoadAll: def test_multi_document_load(self, tmpdir): """this went wrong on 3.7 because of StopIteration, PR 37 and Issue 211""" from ruamel.yaml import YAML + fn = Path(str(tmpdir)) / 'test.yaml' - fn.write_text(textwrap.dedent(u"""\ + fn.write_text( + textwrap.dedent( + u"""\ --- - a --- - b ... - """)) + """ + ) + ) yaml = YAML() assert list(yaml.load_all(fn)) == [['a'], ['b']] @@ -147,15 +163,20 @@ class TestDuplSet: # round-trip-loader should except from ruamel.yaml import YAML from ruamel.yaml.constructor import DuplicateKeyError + yaml = YAML() with pytest.raises(DuplicateKeyError): - yaml.load(textwrap.dedent("""\ + yaml.load( + textwrap.dedent( + """\ !!set ? a ? b ? c ? a - """)) + """ + ) + ) class TestDumpLoadUnicode: @@ -163,26 +184,29 @@ class TestDumpLoadUnicode: # and answer by randomir (https://stackoverflow.com/a/45281922/1307905) def test_write_unicode(self, tmpdir): from ruamel.yaml import YAML + yaml = YAML() - text_dict = {"text": u"HELLO_WORLD©"} + text_dict = {'text': u'HELLO_WORLD©'} file_name = str(tmpdir) + '/tstFile.yaml' yaml.dump(text_dict, open(file_name, 'w')) assert open(file_name, 'rb').read().decode('utf-8') == u'text: HELLO_WORLD©\n' def test_read_unicode(self, tmpdir): from ruamel.yaml import YAML + yaml = YAML() file_name = str(tmpdir) + '/tstFile.yaml' with open(file_name, 'wb') as fp: fp.write(u'text: HELLO_WORLD©\n'.encode('utf-8')) text_dict = yaml.load(open(file_name, 'r')) - assert text_dict["text"] == u"HELLO_WORLD©" + assert text_dict['text'] == u'HELLO_WORLD©' class TestFlowStyle: def test_flow_style(self, capsys): # https://stackoverflow.com/questions/45791712/ from ruamel.yaml import YAML + yaml = YAML() yaml.default_flow_style = None data = yaml.map() @@ -190,15 +214,16 @@ class TestFlowStyle: data['a'] = [[1, 2], [3, 4]] yaml.dump(data, sys.stdout) out, err = capsys.readouterr() - assert out == "b: 1\na:\n- [1, 2]\n- [3, 4]\n" + assert out == 'b: 1\na:\n- [1, 2]\n- [3, 4]\n' class TestOldAPI: - @pytest.mark.skipif(sys.version_info >= (3, 0), reason="ok on Py3") + @pytest.mark.skipif(sys.version_info >= (3, 0), reason='ok on Py3') @pytest.mark.xfail(strict=True) def test_duplicate_keys_02(self): # Issue 165 unicode keys in error/warning from ruamel.yaml import safe_load from ruamel.yaml.constructor import DuplicateKeyFutureWarning + with pytest.warns(DuplicateKeyFutureWarning): safe_load('type: Doméstica\ntype: International') diff --git a/_test/test_class_register.py b/_test/test_class_register.py index 3da9fb7..126d93f 100644 --- a/_test/test_class_register.py +++ b/_test/test_class_register.py @@ -22,8 +22,7 @@ class User1(object): @classmethod def to_yaml(cls, representer, node): - return representer.represent_scalar(cls.yaml_tag, - u'{.name}-{.age}'.format(node, node)) + return representer.represent_scalar(cls.yaml_tag, u'{.name}-{.age}'.format(node, node)) @classmethod def from_yaml(cls, constructor, node): @@ -34,66 +33,66 @@ class TestRegisterClass(object): def test_register_0_rt(self): yaml = YAML() yaml.register_class(User0) - ys = ''' + ys = """ - !User0 name: Anthon age: 18 - ''' + """ d = yaml.load(ys) yaml.dump(d, compare=ys, unordered_lines=True) def test_register_0_safe(self): # default_flow_style = None - yaml = YAML(typ="safe") + yaml = YAML(typ='safe') yaml.register_class(User0) - ys = ''' + ys = """ - !User0 {age: 18, name: Anthon} - ''' + """ d = yaml.load(ys) yaml.dump(d, compare=ys) def test_register_0_unsafe(self): # default_flow_style = None - yaml = YAML(typ="unsafe") + yaml = YAML(typ='unsafe') yaml.register_class(User0) - ys = ''' + ys = """ - !User0 {age: 18, name: Anthon} - ''' + """ d = yaml.load(ys) yaml.dump(d, compare=ys) def test_register_1_rt(self): yaml = YAML() yaml.register_class(User1) - ys = ''' + ys = """ - !user Anthon-18 - ''' + """ d = yaml.load(ys) yaml.dump(d, compare=ys) def test_register_1_safe(self): - yaml = YAML(typ="safe") + yaml = YAML(typ='safe') yaml.register_class(User1) - ys = ''' + ys = """ [!user Anthon-18] - ''' + """ d = yaml.load(ys) yaml.dump(d, compare=ys) def test_register_1_unsafe(self): - yaml = YAML(typ="unsafe") + yaml = YAML(typ='unsafe') yaml.register_class(User1) - ys = ''' + ys = """ [!user Anthon-18] - ''' + """ d = yaml.load(ys) yaml.dump(d, compare=ys) class TestDecorator(object): - def test_decorator_implicit(self): from ruamel.yaml import yaml_object + yml = YAML() @yaml_object(yml) @@ -102,16 +101,17 @@ class TestDecorator(object): self.name = name self.age = age - ys = ''' + ys = """ - !User2 name: Anthon age: 18 - ''' + """ d = yml.load(ys) yml.dump(d, compare=ys, unordered_lines=True) def test_decorator_explicit(self): from ruamel.yaml import yaml_object + yml = YAML() @yaml_object(yml) @@ -124,15 +124,16 @@ class TestDecorator(object): @classmethod def to_yaml(cls, representer, node): - return representer.represent_scalar(cls.yaml_tag, - u'{.name}-{.age}'.format(node, node)) + return representer.represent_scalar( + cls.yaml_tag, u'{.name}-{.age}'.format(node, node) + ) @classmethod def from_yaml(cls, constructor, node): return cls(*node.value.split('-')) - ys = ''' + ys = """ - !USER Anthon-18 - ''' + """ d = yml.load(ys) yml.dump(d, compare=ys) diff --git a/_test/test_collections.py b/_test/test_collections.py index e70dbd2..e6033bb 100644 --- a/_test/test_collections.py +++ b/_test/test_collections.py @@ -7,7 +7,7 @@ This is now so integrated in Python that it can be mapped to !!omap """ -import pytest # NOQA +import pytest # NOQA from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NOQA @@ -16,5 +16,6 @@ from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NO class TestOrderedDict: def test_ordereddict(self): from collections import OrderedDict - import ruamel.yaml # NOQA + import ruamel.yaml # NOQA + assert ruamel.yaml.dump(OrderedDict()) == '!!omap []\n' diff --git a/_test/test_comment_manipulation.py b/_test/test_comment_manipulation.py index 7586954..92810da 100644 --- a/_test/test_comment_manipulation.py +++ b/_test/test_comment_manipulation.py @@ -16,8 +16,11 @@ def compare(data, s, **kw): def compare_eol(data, s): - assert round_trip_dump(data).replace('\n', '|\n') == \ - dedent(s).replace('EOL', '').replace('\n', '|\n') + assert round_trip_dump(data).replace('\n', '|\n') == dedent(s).replace('EOL', "").replace( + '\n', '|\n' + ) + + # @pytest.mark.xfail @@ -25,336 +28,451 @@ class TestCommentsManipulation: # list def test_seq_set_comment_on_existing_explicit_column(self): - data = load(""" + data = load( + """ - a # comment 1 - b - c - """) + """ + ) data.yaml_add_eol_comment('comment 2', key=1, column=6) - compare(data, """ + compare( + data, + """ - a # comment 1 - b # comment 2 - c - """) + """, + ) def test_seq_overwrite_comment_on_existing_explicit_column(self): - data = load(""" + data = load( + """ - a # comment 1 - b - c - """) + """ + ) data.yaml_add_eol_comment('comment 2', key=0, column=6) - compare(data, """ + compare( + data, + """ - a # comment 2 - b - c - """) + """, + ) def test_seq_first_comment_explicit_column(self): - data = load(""" + data = load( + """ - a - b - c - """) + """ + ) data.yaml_add_eol_comment('comment 1', key=1, column=6) - compare(data, """ + compare( + data, + """ - a - b # comment 1 - c - """) + """, + ) def test_seq_set_comment_on_existing_column_prev(self): - data = load(""" + data = load( + """ - a # comment 1 - b - c - d # comment 3 - """) + """ + ) data.yaml_add_eol_comment('comment 2', key=1) - compare(data, """ + compare( + data, + """ - a # comment 1 - b # comment 2 - c - d # comment 3 - """) + """, + ) def test_seq_set_comment_on_existing_column_next(self): - data = load(""" + data = load( + """ - a # comment 1 - b - c - d # comment 3 - """) + """ + ) print(data._yaml_comment) # print(type(data._yaml_comment._items[0][0].start_mark)) # ruamel.yaml.error.Mark # print(type(data._yaml_comment._items[0][0].start_mark)) data.yaml_add_eol_comment('comment 2', key=2) - compare(data, """ + compare( + data, + """ - a # comment 1 - b - c # comment 2 - d # comment 3 - """) + """, + ) def test_seq_set_comment_on_existing_column_further_away(self): """ no comment line before or after, take the latest before the new position """ - data = load(""" + data = load( + """ - a # comment 1 - b - c - d - e - f # comment 3 - """) + """ + ) print(data._yaml_comment) # print(type(data._yaml_comment._items[0][0].start_mark)) # ruamel.yaml.error.Mark # print(type(data._yaml_comment._items[0][0].start_mark)) data.yaml_add_eol_comment('comment 2', key=3) - compare(data, """ + compare( + data, + """ - a # comment 1 - b - c - d # comment 2 - e - f # comment 3 - """) + """, + ) def test_seq_set_comment_on_existing_explicit_column_with_hash(self): - data = load(""" + data = load( + """ - a # comment 1 - b - c - """) + """ + ) data.yaml_add_eol_comment('# comment 2', key=1, column=6) - compare(data, """ + compare( + data, + """ - a # comment 1 - b # comment 2 - c - """) + """, + ) # dict def test_dict_set_comment_on_existing_explicit_column(self): - data = load(""" + data = load( + """ a: 1 # comment 1 b: 2 c: 3 d: 4 e: 5 - """) + """ + ) data.yaml_add_eol_comment('comment 2', key='c', column=7) - compare(data, """ + compare( + data, + """ a: 1 # comment 1 b: 2 c: 3 # comment 2 d: 4 e: 5 - """) + """, + ) def test_dict_overwrite_comment_on_existing_explicit_column(self): - data = load(""" + data = load( + """ a: 1 # comment 1 b: 2 c: 3 d: 4 e: 5 - """) + """ + ) data.yaml_add_eol_comment('comment 2', key='a', column=7) - compare(data, """ + compare( + data, + """ a: 1 # comment 2 b: 2 c: 3 d: 4 e: 5 - """) + """, + ) def test_map_set_comment_on_existing_column_prev(self): - data = load(""" + data = load( + """ a: 1 # comment 1 b: 2 c: 3 d: 4 e: 5 # comment 3 - """) + """ + ) data.yaml_add_eol_comment('comment 2', key='b') - compare(data, """ + compare( + data, + """ a: 1 # comment 1 b: 2 # comment 2 c: 3 d: 4 e: 5 # comment 3 - """) + """, + ) def test_map_set_comment_on_existing_column_next(self): - data = load(""" + data = load( + """ a: 1 # comment 1 b: 2 c: 3 d: 4 e: 5 # comment 3 - """) + """ + ) data.yaml_add_eol_comment('comment 2', key='d') - compare(data, """ + compare( + data, + """ a: 1 # comment 1 b: 2 c: 3 d: 4 # comment 2 e: 5 # comment 3 - """) + """, + ) def test_map_set_comment_on_existing_column_further_away(self): """ no comment line before or after, take the latest before the new position """ - data = load(""" + data = load( + """ a: 1 # comment 1 b: 2 c: 3 d: 4 e: 5 # comment 3 - """) + """ + ) data.yaml_add_eol_comment('comment 2', key='c') print(round_trip_dump(data)) - compare(data, """ + compare( + data, + """ a: 1 # comment 1 b: 2 c: 3 # comment 2 d: 4 e: 5 # comment 3 - """) + """, + ) # @pytest.mark.xfail def test_before_top_map_rt(self): - data = load(""" + data = load( + """ a: 1 b: 2 - """) + """ + ) data.yaml_set_start_comment('Hello\nWorld\n') - compare(data, """ + compare( + data, + """ # Hello # World a: 1 b: 2 - """.format(comment='#')) + """.format( + comment='#' + ), + ) def test_before_top_map_replace(self): - data = load(""" + data = load( + """ # abc # def a: 1 # 1 b: 2 - """) + """ + ) data.yaml_set_start_comment('Hello\nWorld\n') - compare(data, """ + compare( + data, + """ # Hello # World a: 1 # 1 b: 2 - """.format(comment='#')) + """.format( + comment='#' + ), + ) def test_before_top_map_from_scratch(self): from ruamel.yaml.comments import CommentedMap + data = CommentedMap() data['a'] = 1 data['b'] = 2 data.yaml_set_start_comment('Hello\nWorld\n') # print(data.ca) # print(data.ca._items) - compare(data, """ + compare( + data, + """ # Hello # World a: 1 b: 2 - """.format(comment='#')) + """.format( + comment='#' + ), + ) def test_before_top_seq_rt(self): - data = load(""" + data = load( + """ - a - b - """) + """ + ) data.yaml_set_start_comment('Hello\nWorld\n') print(round_trip_dump(data)) - compare(data, """ + compare( + data, + """ # Hello # World - a - b - """) + """, + ) def test_before_top_seq_rt_replace(self): - data = load(""" + data = load( + """ # this # that - a - b - """.format(comment='#')) + """.format( + comment='#' + ) + ) data.yaml_set_start_comment('Hello\nWorld\n') print(round_trip_dump(data)) - compare(data, """ + compare( + data, + """ # Hello # World - a - b - """.format(comment='#')) + """.format( + comment='#' + ), + ) def test_before_top_seq_from_scratch(self): from ruamel.yaml.comments import CommentedSeq + data = CommentedSeq() data.append('a') data.append('b') data.yaml_set_start_comment('Hello\nWorld\n') print(round_trip_dump(data)) - compare(data, """ + compare( + data, + """ # Hello # World - a - b - """.format(comment='#')) + """.format( + comment='#' + ), + ) # nested variants def test_before_nested_map_rt(self): - data = load(""" + data = load( + """ a: 1 b: c: 2 d: 3 - """) + """ + ) data['b'].yaml_set_start_comment('Hello\nWorld\n') - compare(data, """ + compare( + data, + """ a: 1 b: # Hello # World c: 2 d: 3 - """.format(comment='#')) + """.format( + comment='#' + ), + ) def test_before_nested_map_rt_indent(self): - data = load(""" + data = load( + """ a: 1 b: c: 2 d: 3 - """) + """ + ) data['b'].yaml_set_start_comment('Hello\nWorld\n', indent=2) - compare(data, """ + compare( + data, + """ a: 1 b: # Hello # World c: 2 d: 3 - """.format(comment='#')) + """.format( + comment='#' + ), + ) print(data['b'].ca) def test_before_nested_map_from_scratch(self): from ruamel.yaml.comments import CommentedMap + data = CommentedMap() datab = CommentedMap() data['a'] = 1 @@ -362,17 +480,23 @@ class TestCommentsManipulation: datab['c'] = 2 datab['d'] = 3 data['b'].yaml_set_start_comment('Hello\nWorld\n') - compare(data, """ + compare( + data, + """ a: 1 b: # Hello # World c: 2 d: 3 - """.format(comment='#')) + """.format( + comment='#' + ), + ) def test_before_nested_seq_from_scratch(self): from ruamel.yaml.comments import CommentedMap, CommentedSeq + data = CommentedMap() datab = CommentedSeq() data['a'] = 1 @@ -380,17 +504,23 @@ class TestCommentsManipulation: datab.append('c') datab.append('d') data['b'].yaml_set_start_comment('Hello\nWorld\n', indent=2) - compare(data, """ + compare( + data, + """ a: 1 b: # Hello # World - c - d - """.format(comment='#')) + """.format( + comment='#' + ), + ) def test_before_nested_seq_from_scratch_block_seq_indent(self): from ruamel.yaml.comments import CommentedMap, CommentedSeq + data = CommentedMap() datab = CommentedSeq() data['a'] = 1 @@ -398,18 +528,26 @@ class TestCommentsManipulation: datab.append('c') datab.append('d') data['b'].yaml_set_start_comment('Hello\nWorld\n', indent=2) - compare(data, """ + compare( + data, + """ a: 1 b: # Hello # World - c - d - """.format(comment='#'), indent=4, block_seq_indent=2) + """.format( + comment='#' + ), + indent=4, + block_seq_indent=2, + ) def test_map_set_comment_before_and_after_non_first_key_00(self): # http://stackoverflow.com/a/40705671/1307905 - data = load(""" + data = load( + """ xyz: a: 1 # comment 1 b: 2 @@ -417,11 +555,15 @@ class TestCommentsManipulation: test1: test2: test3: 3 - """) - data.yaml_set_comment_before_after_key('test1', 'before test1 (top level)', - after='before test2') + """ + ) + data.yaml_set_comment_before_after_key( + 'test1', 'before test1 (top level)', after='before test2' + ) data['test1']['test2'].yaml_set_start_comment('after test2', indent=4) - compare(data, """ + compare( + data, + """ xyz: a: 1 # comment 1 b: 2 @@ -432,10 +574,12 @@ class TestCommentsManipulation: test2: # after test2 test3: 3 - """) + """, + ) def test_map_set_comment_before_and_after_non_first_key_01(self): - data = load(""" + data = load( + """ xyz: a: 1 # comment 1 b: 2 @@ -443,12 +587,16 @@ class TestCommentsManipulation: test1: test2: test3: 3 - """) - data.yaml_set_comment_before_after_key('test1', 'before test1 (top level)', - after='before test2\n\n') + """ + ) + data.yaml_set_comment_before_after_key( + 'test1', 'before test1 (top level)', after='before test2\n\n' + ) data['test1']['test2'].yaml_set_start_comment('after test2', indent=4) # EOL is needed here as dedenting gets rid of spaces (as well as does Emacs - compare_eol(data, """ + compare_eol( + data, + """ xyz: a: 1 # comment 1 b: 2 @@ -460,10 +608,12 @@ class TestCommentsManipulation: test2: # after test2 test3: 3 - """) + """, + ) def test_map_set_comment_before_and_after_non_first_key_02(self): - data = load(""" + data = load( + """ xyz: a: 1 # comment 1 b: 2 @@ -471,12 +621,16 @@ class TestCommentsManipulation: test1: test2: test3: 3 - """) - data.yaml_set_comment_before_after_key('test1', 'xyz\n\nbefore test1 (top level)', - after='\nbefore test2', after_indent=4) + """ + ) + data.yaml_set_comment_before_after_key( + 'test1', 'xyz\n\nbefore test1 (top level)', after='\nbefore test2', after_indent=4 + ) data['test1']['test2'].yaml_set_start_comment('after test2', indent=4) # EOL is needed here as dedenting gets rid of spaces (as well as does Emacs - compare_eol(data, """ + compare_eol( + data, + """ xyz: a: 1 # comment 1 b: 2 @@ -490,4 +644,5 @@ class TestCommentsManipulation: test2: # after test2 test3: 3 - """) + """, + ) diff --git a/_test/test_comments.py b/_test/test_comments.py index 921b193..7a43a97 100644 --- a/_test/test_comments.py +++ b/_test/test_comments.py @@ -27,15 +27,18 @@ class TestComments: round_trip(x, extra='a\n') def test_no_comments(self): - round_trip(""" + round_trip( + """ - europe: 10 - usa: - ohio: 2 - california: 9 - """) + """ + ) def test_round_trip_ordering(self): - round_trip(""" + round_trip( + """ a: 1 b: 2 c: 3 @@ -44,25 +47,32 @@ class TestComments: d: 4 e: 5 f: 6 - """) + """ + ) def test_complex(self): - round_trip(""" + round_trip( + """ - europe: 10 # top - usa: - ohio: 2 - california: 9 # o - """) + """ + ) def test_dropped(self): - round_trip(""" + round_trip( + """ # comment scalar ... - """, "scalar\n...\n") + """, + 'scalar\n...\n', + ) def test_main_mapping_begin_end(self): - round_trip(""" + round_trip( + """ # C start a # C start b abc: 1 @@ -70,7 +80,8 @@ class TestComments: klm: 3 # C end a # C end b - """) + """ + ) def test_reindent(self): x = """\ @@ -80,14 +91,17 @@ class TestComments: """ d = round_trip_load(x) y = round_trip_dump(d, indent=4) - assert y == dedent("""\ + assert y == dedent( + """\ a: b: # comment 1 c: 1 # comment 2 - """) + """ + ) def test_main_mapping_begin_end_items_post(self): - round_trip(""" + round_trip( + """ # C start a # C start b abc: 1 # abc comment @@ -95,10 +109,12 @@ class TestComments: klm: 3 # klm comment # C end a # C end b - """) + """ + ) def test_main_sequence_begin_end(self): - round_trip(""" + round_trip( + """ # C start a # C start b - abc @@ -106,10 +122,12 @@ class TestComments: - klm # C end a # C end b - """) + """ + ) def test_main_sequence_begin_end_items_post(self): - round_trip(""" + round_trip( + """ # C start a # C start b - abc # abc comment @@ -117,10 +135,12 @@ class TestComments: - klm # klm comment # C end a # C end b - """) + """ + ) def test_main_mapping_begin_end_complex(self): - round_trip(""" + round_trip( + """ # C start a # C start b abc: 1 @@ -130,10 +150,12 @@ class TestComments: 3b: beta # it is all greek to me # C end a # C end b - """) + """ + ) - def test_09(self): # 2.9 from the examples in the spec - round_trip(""" + def test_09(self): # 2.9 from the examples in the spec + round_trip( + """ hr: # 1998 hr ranking - Mark McGwire - Sammy Sosa @@ -141,10 +163,14 @@ class TestComments: # 1998 rbi ranking - Sammy Sosa - Ken Griffey - """, indent=4, block_seq_indent=2) + """, + indent=4, + block_seq_indent=2, + ) def test_09a(self): - round_trip(""" + round_trip( + """ hr: # 1998 hr ranking - Mark McGwire - Sammy Sosa @@ -152,36 +178,44 @@ class TestComments: # 1998 rbi ranking - Sammy Sosa - Ken Griffey - """) + """ + ) def test_simple_map_middle_comment(self): - round_trip(""" + round_trip( + """ abc: 1 # C 3a # C 3b ghi: 2 - """) + """ + ) def test_map_in_map_0(self): - round_trip(""" + round_trip( + """ map1: # comment 1 # comment 2 map2: key1: val1 - """) + """ + ) def test_map_in_map_1(self): # comment is moved from value to key - round_trip(""" + round_trip( + """ map1: # comment 1 map2: key1: val1 - """) + """ + ) def test_application_arguments(self): # application configur - round_trip(""" + round_trip( + """ args: username: anthon passwd: secret @@ -190,7 +224,8 @@ class TestComments: session-name: test loop: wait: 10 - """) + """ + ) def test_substitute(self): x = """ @@ -210,7 +245,8 @@ class TestComments: assert round_trip_dump(data) == dedent(x) def test_set_comment(self): - round_trip(""" + round_trip( + """ !!set # the beginning ? a @@ -218,29 +254,35 @@ class TestComments: ? b # You see? Promised you. ? c # this is the end - """) + """ + ) def test_omap_comment_roundtrip(self): - round_trip(""" + round_trip( + """ !!omap - a: 1 - b: 2 # two - c: 3 # three - d: 4 - """) + """ + ) def test_omap_comment_roundtrip_pre_comment(self): - round_trip(""" + round_trip( + """ !!omap - a: 1 - b: 2 # two - c: 3 # three # last one - d: 4 - """) + """ + ) def test_non_ascii(self): - round_trip(""" + round_trip( + """ verbosity: 1 # 0 is minimal output, -1 none base_url: http://gopher.net special_indices: [1, 5, 8] @@ -259,34 +301,43 @@ class TestComments: <<: *asia_europe Spain: Madrid Italy: Rome - """) + """ + ) def test_dump_utf8(self): import ruamel.yaml # NOQA - x = dedent("""\ + + x = dedent( + """\ ab: - x # comment - y # more comment - """) + """ + ) data = round_trip_load(x) dumper = ruamel.yaml.RoundTripDumper for utf in [True, False]: - y = ruamel.yaml.dump(data, default_flow_style=False, Dumper=dumper, - allow_unicode=utf) + y = ruamel.yaml.dump( + data, default_flow_style=False, Dumper=dumper, allow_unicode=utf + ) assert y == x def test_dump_unicode_utf8(self): import ruamel.yaml # NOQA - x = dedent(u"""\ + + x = dedent( + u"""\ ab: - x # comment - y # more comment - """) + """ + ) data = round_trip_load(x) dumper = ruamel.yaml.RoundTripDumper for utf in [True, False]: - y = ruamel.yaml.dump(data, default_flow_style=False, Dumper=dumper, - allow_unicode=utf) + y = ruamel.yaml.dump( + data, default_flow_style=False, Dumper=dumper, allow_unicode=utf + ) assert y == x def test_mlget_00(self): @@ -327,7 +378,8 @@ class TestInsertPopList: d = round_trip_load(self.ins) d['ab'].insert(0, 'xyz') y = round_trip_dump(d, indent=2) - assert y == dedent("""\ + assert y == dedent( + """\ ab: - xyz - a # a @@ -338,13 +390,15 @@ class TestInsertPopList: de: - 1 - 2 - """) + """ + ) def test_insert_1(self): d = round_trip_load(self.ins) d['ab'].insert(4, 'xyz') y = round_trip_dump(d, indent=2) - assert y == dedent("""\ + assert y == dedent( + """\ ab: - a # a - b # b @@ -355,13 +409,15 @@ class TestInsertPopList: de: - 1 - 2 - """) + """ + ) def test_insert_2(self): d = round_trip_load(self.ins) d['ab'].insert(1, 'xyz') y = round_trip_dump(d, indent=2) - assert y == dedent("""\ + assert y == dedent( + """\ ab: - a # a - xyz @@ -372,14 +428,16 @@ class TestInsertPopList: de: - 1 - 2 - """) + """ + ) def test_pop_0(self): d = round_trip_load(self.ins) d['ab'].pop(0) y = round_trip_dump(d, indent=2) print(y) - assert y == dedent("""\ + assert y == dedent( + """\ ab: - b # b - c @@ -388,14 +446,16 @@ class TestInsertPopList: de: - 1 - 2 - """) + """ + ) def test_pop_1(self): d = round_trip_load(self.ins) d['ab'].pop(1) y = round_trip_dump(d, indent=2) print(y) - assert y == dedent("""\ + assert y == dedent( + """\ ab: - a # a - c @@ -404,14 +464,16 @@ class TestInsertPopList: de: - 1 - 2 - """) + """ + ) def test_pop_2(self): d = round_trip_load(self.ins) d['ab'].pop(2) y = round_trip_dump(d, indent=2) print(y) - assert y == dedent("""\ + assert y == dedent( + """\ ab: - a # a - b # b @@ -420,14 +482,16 @@ class TestInsertPopList: de: - 1 - 2 - """) + """ + ) def test_pop_3(self): d = round_trip_load(self.ins) d['ab'].pop(3) y = round_trip_dump(d, indent=2) print(y) - assert y == dedent("""\ + assert y == dedent( + """\ ab: - a # a - b # b @@ -435,7 +499,8 @@ class TestInsertPopList: de: - 1 - 2 - """) + """ + ) # inspired by demux' question on stackoverflow @@ -451,45 +516,52 @@ class TestInsertInMapping: def test_insert_at_pos_1(self): d = round_trip_load(self.ins) - d.insert(1, 'last name', 'Vandelay', comment="new key") + d.insert(1, 'last name', 'Vandelay', comment='new key') y = round_trip_dump(d) print(y) - assert y == dedent("""\ + assert y == dedent( + """\ first_name: Art last name: Vandelay # new key occupation: Architect # This is an occupation comment about: Art Vandelay is a fictional character that George invents... - """) + """ + ) def test_insert_at_pos_0(self): d = round_trip_load(self.ins) - d.insert(0, 'last name', 'Vandelay', comment="new key") + d.insert(0, 'last name', 'Vandelay', comment='new key') y = round_trip_dump(d) print(y) - assert y == dedent("""\ + assert y == dedent( + """\ last name: Vandelay # new key first_name: Art occupation: Architect # This is an occupation comment about: Art Vandelay is a fictional character that George invents... - """) + """ + ) def test_insert_at_pos_3(self): # much more simple if done with appending. d = round_trip_load(self.ins) - d.insert(3, 'last name', 'Vandelay', comment="new key") + d.insert(3, 'last name', 'Vandelay', comment='new key') y = round_trip_dump(d) print(y) - assert y == dedent("""\ + assert y == dedent( + """\ first_name: Art occupation: Architect # This is an occupation comment about: Art Vandelay is a fictional character that George invents... last name: Vandelay # new key - """) + """ + ) class TestCommentedMapMerge: def test_in_operator(self): - data = round_trip_load(""" + data = round_trip_load( + """ x: &base a: 1 b: 2 @@ -498,31 +570,36 @@ class TestCommentedMapMerge: <<: *base k: 4 l: 5 - """) + """ + ) assert data['x']['a'] == 1 assert 'a' in data['x'] assert data['y']['a'] == 1 assert 'a' in data['y'] def test_issue_60(self): - data = round_trip_load(""" + data = round_trip_load( + """ x: &base a: 1 y: <<: *base - """) + """ + ) assert data['x']['a'] == 1 assert data['y']['a'] == 1 assert str(data['y']) == """ordereddict([('a', 1)])""" def test_issue_60_1(self): - data = round_trip_load(""" + data = round_trip_load( + """ x: &base a: 1 y: <<: *base b: 2 - """) + """ + ) assert data['x']['a'] == 1 assert data['y']['a'] == 1 assert str(data['y']) == """ordereddict([('b', 2), ('a', 1)])""" @@ -531,7 +608,8 @@ class TestCommentedMapMerge: class TestEmptyLines: # prompted by issue 46 from Alex Harvey def test_issue_46(self): - yaml_str = dedent("""\ + yaml_str = dedent( + """\ --- # Please add key/value pairs in alphabetical order @@ -540,13 +618,15 @@ class TestEmptyLines: jenkins_ad_credentials: bind_name: 'CN=svc-AAA-BBB-T,OU=Example,DC=COM,DC=EXAMPLE,DC=Local' bind_pass: 'xxxxyyyy{' - """) + """ + ) d = round_trip_load(yaml_str, preserve_quotes=True) y = round_trip_dump(d, explicit_start=True) assert yaml_str == y def test_multispace_map(self): - round_trip(""" + round_trip( + """ a: 1x b: 2x @@ -558,11 +638,13 @@ class TestEmptyLines: d: 4x - """) + """ + ) @pytest.mark.xfail(strict=True) def test_multispace_map_initial(self): - round_trip(""" + round_trip( + """ a: 1x @@ -575,27 +657,33 @@ class TestEmptyLines: d: 4x - """) + """ + ) def test_embedded_map(self): - round_trip(""" + round_trip( + """ - a: 1y b: 2y c: 3y - """) + """ + ) def test_toplevel_seq(self): - round_trip("""\ + round_trip( + """\ - 1 - 2 - 3 - """) + """ + ) def test_embedded_seq(self): - round_trip(""" + round_trip( + """ a: b: - 1 @@ -604,7 +692,8 @@ class TestEmptyLines: - 3 - """) + """ + ) def test_line_with_only_spaces(self): # issue 54 @@ -629,12 +718,14 @@ class TestEmptyLines: assert stripped == y def test_issue_54_not_ok(self): - yaml_str = dedent("""\ + yaml_str = dedent( + """\ toplevel: # some comment sublevel: 300 - """) + """ + ) d = round_trip_load(yaml_str) print(d.ca) y = round_trip_dump(d, indent=4) @@ -642,50 +733,61 @@ class TestEmptyLines: assert yaml_str == y def test_issue_54_ok(self): - yaml_str = dedent("""\ + yaml_str = dedent( + """\ toplevel: # some comment sublevel: 300 - """) + """ + ) d = round_trip_load(yaml_str) y = round_trip_dump(d, indent=4) assert yaml_str == y def test_issue_93(self): - round_trip("""\ + round_trip( + """\ a: b: - c1: cat # a1 # my comment on catfish - c2: catfish # a2 - """) + """ + ) def test_issue_93_00(self): - round_trip("""\ + round_trip( + """\ a: - - c1: cat # a1 # my comment on catfish - c2: catfish # a2 - """) + """ + ) def test_issue_93_01(self): - round_trip("""\ + round_trip( + """\ - - c1: cat # a1 # my comment on catfish - c2: catfish # a2 - """) + """ + ) def test_issue_93_02(self): # never failed as there is no indent - round_trip("""\ + round_trip( + """\ - c1: cat # my comment on catfish - c2: catfish - """) + """ + ) def test_issue_96(self): # inserted extra line on trailing spaces - round_trip("""\ + round_trip( + """\ a: b: c: c_val @@ -693,14 +795,15 @@ class TestEmptyLines: e: g: g_val - """) + """ + ) class TestUnicodeComments: - - @pytest.mark.skipif(sys.version_info < (2, 7), reason="wide unicode") + @pytest.mark.skipif(sys.version_info < (2, 7), reason='wide unicode') def test_issue_55(self): # reported by Haraguroicha Hsu - round_trip("""\ + round_trip( + """\ name: TEST description: test using author: Harguroicha @@ -715,87 +818,111 @@ class TestUnicodeComments: - :no: 05338777 # 〇〇啓 - :no: 05273867 # 〇 - :no: 05205786 # 〇𤦌 - """) + """ + ) class TestEmptyValueBeforeComments: def test_issue_25a(self): - round_trip("""\ + round_trip( + """\ - a: b c: d d: # foo - e: f - """) + """ + ) def test_issue_25a1(self): - round_trip("""\ + round_trip( + """\ - a: b c: d d: # foo e: f - """) + """ + ) def test_issue_25b(self): - round_trip("""\ + round_trip( + """\ var1: #empty var2: something #notempty - """) + """ + ) def test_issue_25c(self): - round_trip("""\ + round_trip( + """\ params: a: 1 # comment a b: # comment b c: 3 # comment c - """) + """ + ) def test_issue_25c1(self): - round_trip("""\ + round_trip( + """\ params: a: 1 # comment a b: # comment b # extra c: 3 # comment c - """) + """ + ) def test_issue_25_00(self): - round_trip("""\ + round_trip( + """\ params: a: 1 # comment a b: # comment b - """) + """ + ) def test_issue_25_01(self): - round_trip("""\ + round_trip( + """\ a: # comment 1 # comment 2 - b: # comment 3 c: 1 # comment 4 - """) + """ + ) def test_issue_25_02(self): - round_trip("""\ + round_trip( + """\ a: # comment 1 # comment 2 - b: 2 # comment 3 - """) + """ + ) def test_issue_25_03(self): - round_trip("""\ + round_trip( + """\ a: # comment 1 # comment 2 - b: 2 # comment 3 - """, indent=4, block_seq_indent=2) + """, + indent=4, + block_seq_indent=2, + ) def test_issue_25_04(self): - round_trip("""\ + round_trip( + """\ a: # comment 1 # comment 2 b: 1 # comment 3 - """) + """ + ) def test_flow_seq_within_seq(self): - round_trip("""\ + round_trip( + """\ # comment 1 - a - b @@ -807,7 +934,8 @@ class TestEmptyValueBeforeComments: - f # comment 4 - [] - """) + """ + ) test_block_scalar_commented_line_template = """\ @@ -824,8 +952,17 @@ class TestBlockScalarWithComments: # issue 99 reported by Colm O'Connor def test_scalar_with_comments(self): import ruamel.yaml # NOQA - for x in ['', '\n', '\n# Another comment\n', '\n\n', '\n\n# abc\n#xyz\n', - '\n\n# abc\n#xyz\n', '# abc\n\n#xyz\n', '\n\n # abc\n #xyz\n']: + + for x in [ + "", + '\n', + '\n# Another comment\n', + '\n\n', + '\n\n# abc\n#xyz\n', + '\n\n# abc\n#xyz\n', + '# abc\n\n#xyz\n', + '\n\n # abc\n #xyz\n', + ]: commented_line = test_block_scalar_commented_line_template.format(x) data = ruamel.yaml.round_trip_load(commented_line) diff --git a/_test/test_copy.py b/_test/test_copy.py index 9a6deb0..a912259 100644 --- a/_test/test_copy.py +++ b/_test/test_copy.py @@ -6,16 +6,18 @@ Testing copy and deepcopy, instigated by Issue 84 (Peter Amstutz) import copy -import pytest # NOQA +import pytest # NOQA from roundtrip import dedent, round_trip_load, round_trip_dump class TestDeepCopy: def test_preserve_flow_style_simple(self): - x = dedent("""\ + x = dedent( + """\ {foo: bar, baz: quux} - """) + """ + ) data = round_trip_load(x) data_copy = copy.deepcopy(data) y = round_trip_dump(data_copy) @@ -25,9 +27,11 @@ class TestDeepCopy: assert data.fa.flow_style() == data_copy.fa.flow_style() def test_deepcopy_flow_style_nested_dict(self): - x = dedent("""\ + x = dedent( + """\ a: {foo: bar, baz: quux} - """) + """ + ) data = round_trip_load(x) assert data['a'].fa.flow_style() is True data_copy = copy.deepcopy(data) @@ -40,16 +44,20 @@ class TestDeepCopy: print('x [{}]'.format(x)) print('y [{}]'.format(y)) - assert y == dedent("""\ + assert y == dedent( + """\ a: foo: bar baz: quux - """) + """ + ) def test_deepcopy_flow_style_nested_list(self): - x = dedent("""\ + x = dedent( + """\ a: [1, 2, 3] - """) + """ + ) data = round_trip_load(x) assert data['a'].fa.flow_style() is True data_copy = copy.deepcopy(data) @@ -62,19 +70,23 @@ class TestDeepCopy: print('x [{}]'.format(x)) print('y [{}]'.format(y)) - assert y == dedent("""\ + assert y == dedent( + """\ a: - 1 - 2 - 3 - """) + """ + ) class TestCopy: def test_copy_flow_style_nested_dict(self): - x = dedent("""\ + x = dedent( + """\ a: {foo: bar, baz: quux} - """) + """ + ) data = round_trip_load(x) assert data['a'].fa.flow_style() is True data_copy = copy.copy(data) @@ -87,16 +99,20 @@ class TestCopy: z = round_trip_dump(data) assert y == z - assert y == dedent("""\ + assert y == dedent( + """\ a: foo: bar baz: quux - """) + """ + ) def test_copy_flow_style_nested_list(self): - x = dedent("""\ + x = dedent( + """\ a: [1, 2, 3] - """) + """ + ) data = round_trip_load(x) assert data['a'].fa.flow_style() is True data_copy = copy.copy(data) @@ -109,9 +125,11 @@ class TestCopy: print('x [{}]'.format(x)) print('y [{}]'.format(y)) - assert y == dedent("""\ + assert y == dedent( + """\ a: - 1 - 2 - 3 - """) + """ + ) diff --git a/_test/test_cyaml.py b/_test/test_cyaml.py index 4c5c5db..2d67509 100644 --- a/_test/test_cyaml.py +++ b/_test/test_cyaml.py @@ -4,18 +4,26 @@ import platform import pytest -@pytest.mark.skipif(platform.python_implementation() == 'Jython', - reason="Jython throws RepresenterError") +@pytest.mark.skipif( + platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' +) def test_load_cyaml(): import ruamel.yaml + assert ruamel.yaml.__with_libyaml__ from ruamel.yaml.cyaml import CLoader - ruamel.yaml.load("abc: 1", Loader=CLoader) + + ruamel.yaml.load('abc: 1', Loader=CLoader) def test_dump_cyaml(): import ruamel.yaml + data = {'a': 1, 'b': 2} - res = ruamel.yaml.dump(data, Dumper=ruamel.yaml.cyaml.CSafeDumper, - default_flow_style=False, allow_unicode=True) - assert res == "a: 1\nb: 2\n" + res = ruamel.yaml.dump( + data, + Dumper=ruamel.yaml.cyaml.CSafeDumper, + default_flow_style=False, + allow_unicode=True, + ) + assert res == 'a: 1\nb: 2\n' diff --git a/_test/test_datetime.py b/_test/test_datetime.py index b48d529..fe94c02 100644 --- a/_test/test_datetime.py +++ b/_test/test_datetime.py @@ -20,110 +20,147 @@ Please note that a fraction can only be included if not equal to 0 """ import copy -import pytest # NOQA +import pytest # NOQA from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NOQA class TestDateTime: def test_date_only(self): - round_trip(""" + round_trip( + """ - 2011-10-02 - """, """ + """, + """ - 2011-10-02 - """) + """, + ) def test_zero_fraction(self): - round_trip(""" + round_trip( + """ - 2011-10-02 16:45:00.0 - """, """ + """, + """ - 2011-10-02 16:45:00 - """) + """, + ) def test_long_fraction(self): - round_trip(""" + round_trip( + """ - 2011-10-02 16:45:00.1234 # expand with zeros - 2011-10-02 16:45:00.123456 - 2011-10-02 16:45:00.12345612 # round to microseconds - 2011-10-02 16:45:00.1234565 # round up - 2011-10-02 16:45:00.12345678 # round up - """, """ + """, + """ - 2011-10-02 16:45:00.123400 # expand with zeros - 2011-10-02 16:45:00.123456 - 2011-10-02 16:45:00.123456 # round to microseconds - 2011-10-02 16:45:00.123457 # round up - 2011-10-02 16:45:00.123457 # round up - """) + """, + ) def test_canonical(self): - round_trip(""" + round_trip( + """ - 2011-10-02T16:45:00.1Z - """, """ + """, + """ - 2011-10-02T16:45:00.100000Z - """) + """, + ) def test_spaced_timezone(self): - round_trip(""" + round_trip( + """ - 2011-10-02T11:45:00 -5 - """, """ + """, + """ - 2011-10-02T11:45:00-5 - """) + """, + ) def test_normal_timezone(self): - round_trip(""" + round_trip( + """ - 2011-10-02T11:45:00-5 - 2011-10-02 11:45:00-5 - 2011-10-02T11:45:00-05:00 - 2011-10-02 11:45:00-05:00 - """) + """ + ) def test_no_timezone(self): - round_trip(""" + round_trip( + """ - 2011-10-02 6:45:00 - """, """ + """, + """ - 2011-10-02 06:45:00 - """) + """, + ) def test_explicit_T(self): - round_trip(""" + round_trip( + """ - 2011-10-02T16:45:00 - """, """ + """, + """ - 2011-10-02T16:45:00 - """) + """, + ) def test_explicit_t(self): # to upper - round_trip(""" + round_trip( + """ - 2011-10-02t16:45:00 - """, """ + """, + """ - 2011-10-02T16:45:00 - """) + """, + ) def test_no_T_multi_space(self): - round_trip(""" + round_trip( + """ - 2011-10-02 16:45:00 - """, """ + """, + """ - 2011-10-02 16:45:00 - """) + """, + ) def test_iso(self): - round_trip(""" + round_trip( + """ - 2011-10-02T15:45:00+01:00 - """) + """ + ) def test_zero_tz(self): - round_trip(""" + round_trip( + """ - 2011-10-02T15:45:00+0 - """) + """ + ) def test_issue_45(self): - round_trip(""" + round_trip( + """ dt: 2016-08-19T22:45:47Z - """) + """ + ) def test_deepcopy_datestring(self): # reported by Quuxplusone, http://stackoverflow.com/a/41577841/1307905 - x = dedent("""\ + x = dedent( + """\ foo: 2016-10-12T12:34:56 - """) + """ + ) data = copy.deepcopy(round_trip_load(x)) assert round_trip_dump(data) == x diff --git a/_test/test_deprecation.py b/_test/test_deprecation.py index f1a5419..35cb095 100644 --- a/_test/test_deprecation.py +++ b/_test/test_deprecation.py @@ -6,7 +6,7 @@ import sys import pytest # NOQA -@pytest.mark.skipif(sys.version_info < (3, 7), reason="collections not available?") +@pytest.mark.skipif(sys.version_info < (3, 7), reason='collections not available?') def test_collections_deprecation(): with pytest.warns(DeprecationWarning): from collections import Hashable # NOQA diff --git a/_test/test_documents.py b/_test/test_documents.py index 6da293a..476f70c 100644 --- a/_test/test_documents.py +++ b/_test/test_documents.py @@ -1,70 +1,99 @@ # coding: utf-8 -import pytest # NOQA +import pytest # NOQA from roundtrip import round_trip, round_trip_load_all class TestDocument: def test_single_doc_begin_end(self): - round_trip("""\ + round_trip( + """\ --- - a - b ... - """, explicit_start=True, explicit_end=True) + """, + explicit_start=True, + explicit_end=True, + ) def test_multi_doc_begin_end(self): from ruamel import yaml - docs = list(round_trip_load_all("""\ + + docs = list( + round_trip_load_all( + """\ --- - a ... --- - b ... - """)) + """ + ) + ) assert docs == [['a'], ['b']] - out = yaml.dump_all(docs, Dumper=yaml.RoundTripDumper, explicit_start=True, - explicit_end=True) - assert out == "---\n- a\n...\n---\n- b\n...\n" + out = yaml.dump_all( + docs, Dumper=yaml.RoundTripDumper, explicit_start=True, explicit_end=True + ) + assert out == '---\n- a\n...\n---\n- b\n...\n' def test_multi_doc_no_start(self): - docs = list(round_trip_load_all("""\ + docs = list( + round_trip_load_all( + """\ - a ... --- - b ... - """)) + """ + ) + ) assert docs == [['a'], ['b']] def test_multi_doc_no_end(self): - docs = list(round_trip_load_all("""\ + docs = list( + round_trip_load_all( + """\ - a --- - b - """)) + """ + ) + ) assert docs == [['a'], ['b']] def test_multi_doc_ends_only(self): # this is ok in 1.2 - docs = list(round_trip_load_all("""\ + docs = list( + round_trip_load_all( + """\ - a ... - b ... - """, version=(1, 2))) + """, + version=(1, 2), + ) + ) assert docs == [['a'], ['b']] def test_multi_doc_ends_only_1_1(self): from ruamel import yaml + # this is not ok in 1.1 with pytest.raises(yaml.parser.ParserError): - docs = list(round_trip_load_all("""\ + docs = list( + round_trip_load_all( + """\ - a ... - b ... - """, version=(1, 1))) + """, + version=(1, 1), + ) + ) assert docs == [['a'], ['b']] # not True, but not reached diff --git a/_test/test_fail.py b/_test/test_fail.py index fb85e5f..9c318a0 100644 --- a/_test/test_fail.py +++ b/_test/test_fail.py @@ -15,7 +15,8 @@ class TestCommentFailures: @pytest.mark.xfail(strict=True) def test_set_comment_before_tag(self): # no comments before tags - round_trip(""" + round_trip( + """ # the beginning !!set # or this one? @@ -24,11 +25,15 @@ class TestCommentFailures: ? b # You see? Promised you. ? c # this is the end - """) + """ + ) def test_set_comment_before_tag_no_fail(self): # no comments before tags - assert round_trip_dump(round_trip_load(""" + assert ( + round_trip_dump( + round_trip_load( + """ # the beginning !!set # or this one? @@ -37,7 +42,11 @@ class TestCommentFailures: ? b # You see? Promised you. ? c # this is the end - """)) == dedent(""" + """ + ) + ) + == dedent( + """ !!set # or this one? ? a @@ -45,15 +54,19 @@ class TestCommentFailures: ? b # You see? Promised you. ? c # this is the end - """) + """ + ) + ) @pytest.mark.xfail(strict=True) def test_comment_dash_line(self): - round_trip(""" + round_trip( + """ - # abc a: 1 b: 2 - """) + """ + ) def test_comment_dash_line_fail(self): x = """ @@ -63,18 +76,20 @@ class TestCommentFailures: """ data = round_trip_load(x) # this is not nice - assert round_trip_dump(data) == dedent(""" + assert round_trip_dump(data) == dedent( + """ # abc - a: 1 b: 2 - """) + """ + ) class TestIndentFailures: - @pytest.mark.xfail(strict=True) def test_indent_not_retained(self): - round_trip(""" + round_trip( + """ verbosity: 1 # 0 is minimal output, -1 none base_url: http://gopher.net special_indices: [1, 5, 8] @@ -95,10 +110,14 @@ class TestIndentFailures: Italy: Rome Antarctica: - too cold - """) + """ + ) def test_indent_not_retained_no_fail(self): - assert round_trip_dump(round_trip_load(""" + assert ( + round_trip_dump( + round_trip_load( + """ verbosity: 1 # 0 is minimal output, -1 none base_url: http://gopher.net special_indices: [1, 5, 8] @@ -119,7 +138,12 @@ class TestIndentFailures: Italy: Rome Antarctica: - too cold - """), indent=4) == dedent(""" + """ + ), + indent=4, + ) + == dedent( + """ verbosity: 1 # 0 is minimal output, -1 none base_url: http://gopher.net special_indices: [1, 5, 8] @@ -140,46 +164,67 @@ class TestIndentFailures: Italy: Rome Antarctica: - too cold - """) + """ + ) + ) def Xtest_indent_top_level_no_fail(self): - round_trip(""" + round_trip( + """ - a: - b - """, indent=4) + """, + indent=4, + ) class TestTagFailures: @pytest.mark.xfail(strict=True) def test_standard_short_tag(self): - round_trip("""\ + round_trip( + """\ !!map name: Anthon location: Germany language: python - """) + """ + ) def test_standard_short_tag_no_fail(self): - assert round_trip_dump(round_trip_load(""" + assert ( + round_trip_dump( + round_trip_load( + """ !!map name: Anthon location: Germany language: python - """)) == dedent(""" + """ + ) + ) + == dedent( + """ name: Anthon location: Germany language: python - """) + """ + ) + ) class TestFlowValues: def test_flow_value_with_colon(self): - round_trip("""\ + round_trip( + """\ {a: bcd:efg} - """) + """ + ) # @pytest.mark.xfail(strict=True) def test_flow_value_with_colon_quoted(self): - round_trip("""\ + round_trip( + """\ {a: 'bcd:efg'} - """, preserve_quotes=True) + """, + preserve_quotes=True, + ) diff --git a/_test/test_float.py b/_test/test_float.py index 2bfe098..b115eb3 100644 --- a/_test/test_float.py +++ b/_test/test_float.py @@ -11,7 +11,8 @@ from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NO class TestFloat: def test_round_trip_non_exp(self): - data = round_trip("""\ + data = round_trip( + """\ - 1.0 - 1.00 - 23.100 @@ -21,7 +22,8 @@ class TestFloat: - 42. - -42. - +42. - """) + """ + ) print(data) assert 0.999 < data[0] < 1.001 assert 0.999 < data[1] < 1.001 @@ -34,7 +36,8 @@ class TestFloat: assert 41.999 < data[8] < 42.001 def test_round_trip_zeros_0(self): - data = round_trip("""\ + data = round_trip( + """\ - 0. - +0. - -0. @@ -44,7 +47,8 @@ class TestFloat: - 0.00 - +0.00 - -0.00 - """) + """ + ) print(data) for d in data: assert -0.00001 < d < 0.00001 @@ -52,114 +56,137 @@ class TestFloat: # @pytest.mark.xfail(strict=True) def test_round_trip_zeros_1(self): # not sure if this should be supported, but it is - data = round_trip("""\ + data = round_trip( + """\ - 00.0 - +00.0 - -00.0 - """) + """ + ) print(data) for d in data: assert -0.00001 < d < 0.00001 def Xtest_round_trip_non_exp_trailing_dot(self): - data = round_trip("""\ - """) + data = round_trip( + """\ + """ + ) print(data) def test_round_trip_exp_00(self): - data = round_trip("""\ + data = round_trip( + """\ - 42e56 - 42E56 - 42.0E56 - +42.0e56 - 42.0E+056 - +42.00e+056 - """) + """ + ) print(data) for d in data: assert 41.99e56 < d < 42.01e56 # @pytest.mark.xfail(strict=True) def test_round_trip_exp_00f(self): - data = round_trip("""\ + data = round_trip( + """\ - 42.E56 - """) + """ + ) print(data) for d in data: assert 41.99e56 < d < 42.01e56 def test_round_trip_exp_01(self): - data = round_trip("""\ + data = round_trip( + """\ - -42e56 - -42E56 - -42.0e56 - -42.0E+056 - """) + """ + ) print(data) for d in data: assert -41.99e56 > d > -42.01e56 def test_round_trip_exp_02(self): - data = round_trip("""\ + data = round_trip( + """\ - 42e-56 - 42E-56 - 42.0E-56 - +42.0e-56 - 42.0E-056 - +42.0e-056 - """) + """ + ) print(data) for d in data: assert 41.99e-56 < d < 42.01e-56 def test_round_trip_exp_03(self): - data = round_trip("""\ + data = round_trip( + """\ - -42e-56 - -42E-56 - -42.0e-56 - -42.0E-056 - """) + """ + ) print(data) for d in data: assert -41.99e-56 > d > -42.01e-56 def test_round_trip_exp_04(self): - round_trip("""\ + round_trip( + """\ - 1.2e+34 - 1.23e+034 - 1.230e+34 - 1.023e+34 - -1.023e+34 - 250e6 - """) + """ + ) def test_round_trip_exp_05(self): - data = round_trip("""\ + data = round_trip( + """\ - 3.0517578123e-56 - 3.0517578123E-56 - 3.0517578123e-056 - 3.0517578123E-056 - """) + """ + ) print(data) for d in data: assert 3.0517578122e-56 < d < 3.0517578124e-56 def test_yaml_1_1_no_dot(self): from ruamel.yaml.error import MantissaNoDotYAML1_1Warning + with pytest.warns(MantissaNoDotYAML1_1Warning): - round_trip_load("""\ + round_trip_load( + """\ %YAML 1.1 --- - 1e6 - """) + """ + ) class TestCalculations(object): def test_mul_00(self): # issue 149 reported by jan.brezina@tul.cz - d = round_trip_load("""\ + d = round_trip_load( + """\ - 0.1 - """) + """ + ) d[0] *= -1 x = round_trip_dump(d) assert x == '- -0.1\n' diff --git a/_test/test_flowsequencekey.py b/_test/test_flowsequencekey.py index 8490430..f8f122e 100644 --- a/_test/test_flowsequencekey.py +++ b/_test/test_flowsequencekey.py @@ -12,7 +12,8 @@ from roundtrip import round_trip # , dedent, round_trip_load, round_trip_dump class TestFlowStyleSequenceKey: def test_so_39595807(self): - round_trip(""" + round_trip( + """ %YAML 1.2 --- [2, 3, 4]: @@ -21,4 +22,8 @@ class TestFlowStyleSequenceKey: - 2 b: Hello World! c: 'Voilà !' - """, preserve_quotes=True, explicit_start=True, version=(1, 2)) + """, + preserve_quotes=True, + explicit_start=True, + version=(1, 2), + ) diff --git a/_test/test_indentation.py b/_test/test_indentation.py index 528e3b6..dcac772 100644 --- a/_test/test_indentation.py +++ b/_test/test_indentation.py @@ -12,10 +12,14 @@ from roundtrip import round_trip, round_trip_load, round_trip_dump, dedent, YAML def rt(s): import ruamel.yaml - return ruamel.yaml.dump( - ruamel.yaml.load(s, Loader=ruamel.yaml.RoundTripLoader), - Dumper=ruamel.yaml.RoundTripDumper, - ).strip() + '\n' + + return ( + ruamel.yaml.dump( + ruamel.yaml.load(s, Loader=ruamel.yaml.RoundTripLoader), + Dumper=ruamel.yaml.RoundTripDumper, + ).strip() + + '\n' + ) class TestIndent: @@ -25,41 +29,50 @@ class TestIndent: assert s == output def test_roundtrip_mapping_of_inline_lists(self): - s = dedent("""\ + s = dedent( + """\ a: [a, b, c] j: [k, l, m] - """) + """ + ) output = rt(s) assert s == output def test_roundtrip_mapping_of_inline_lists_comments(self): - s = dedent("""\ + s = dedent( + """\ # comment A a: [a, b, c] # comment B j: [k, l, m] - """) + """ + ) output = rt(s) assert s == output def test_roundtrip_mapping_of_inline_sequence_eol_comments(self): - s = dedent("""\ + s = dedent( + """\ # comment A a: [a, b, c] # comment B j: [k, l, m] # comment C - """) + """ + ) output = rt(s) assert s == output # first test by explicitly setting flow style def test_added_inline_list(self): import ruamel.yaml - s1 = dedent(""" + + s1 = dedent( + """ a: - b - c - d - """) + """ + ) s = 'a: [b, c, d]\n' data = ruamel.yaml.load(s1, Loader=ruamel.yaml.RoundTripLoader) val = data['a'] @@ -72,58 +85,79 @@ class TestIndent: def test_roundtrip_flow_mapping(self): import ruamel.yaml - s = dedent("""\ + + s = dedent( + """\ - {a: 1, b: hallo} - {j: fka, k: 42} - """) + """ + ) data = ruamel.yaml.load(s, Loader=ruamel.yaml.RoundTripLoader) output = ruamel.yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper) assert s == output def test_roundtrip_sequence_of_inline_mappings_eol_comments(self): - s = dedent("""\ + s = dedent( + """\ # comment A - {a: 1, b: hallo} # comment B - {j: fka, k: 42} # comment C - """) + """ + ) output = rt(s) assert s == output def test_indent_top_level(self): - round_trip(""" + round_trip( + """ - a: - b - """, indent=4) + """, + indent=4, + ) def test_set_indent_5_block_list_indent_1(self): - round_trip(""" + round_trip( + """ a: - b: c - 1 - d: - 2 - """, indent=5, block_seq_indent=1) + """, + indent=5, + block_seq_indent=1, + ) def test_set_indent_4_block_list_indent_2(self): - round_trip(""" + round_trip( + """ a: - b: c - 1 - d: - 2 - """, indent=4, block_seq_indent=2) + """, + indent=4, + block_seq_indent=2, + ) def test_set_indent_3_block_list_indent_0(self): - round_trip(""" + round_trip( + """ a: - b: c - 1 - d: - 2 - """, indent=3, block_seq_indent=0) + """, + indent=3, + block_seq_indent=0, + ) def Xtest_set_indent_3_block_list_indent_2(self): - round_trip(""" + round_trip( + """ a: - b: c @@ -133,19 +167,27 @@ class TestIndent: d: - 2 - """, indent=3, block_seq_indent=2) + """, + indent=3, + block_seq_indent=2, + ) def test_set_indent_3_block_list_indent_2(self): - round_trip(""" + round_trip( + """ a: - b: c - 1 - d: - 2 - """, indent=3, block_seq_indent=2) + """, + indent=3, + block_seq_indent=2, + ) def Xtest_set_indent_2_block_list_indent_2(self): - round_trip(""" + round_trip( + """ a: - b: c @@ -155,42 +197,55 @@ class TestIndent: d: - 2 - """, indent=2, block_seq_indent=2) + """, + indent=2, + block_seq_indent=2, + ) # this is how it should be: block_seq_indent stretches the indent def test_set_indent_2_block_list_indent_2(self): - round_trip(""" + round_trip( + """ a: - b: c - 1 - d: - 2 - """, indent=2, block_seq_indent=2) + """, + indent=2, + block_seq_indent=2, + ) # have to set indent! def test_roundtrip_four_space_indents(self): - s = ( - 'a:\n' - '- foo\n' - '- bar\n' - ) + s = 'a:\n' '- foo\n' '- bar\n' round_trip(s, indent=4) def test_roundtrip_four_space_indents_no_fail(self): - assert round_trip_dump(round_trip_load(""" + assert ( + round_trip_dump( + round_trip_load( + """ a: - foo - bar - """)) == dedent(""" + """ + ) + ) + == dedent( + """ a: - foo - bar - """) + """ + ) + ) class TestYpkgIndent: def test_00(self): - round_trip(""" + round_trip( + """ name : nano version : 2.3.2 release : 1 @@ -205,41 +260,67 @@ class TestYpkgIndent: GNU nano is an easy-to-use text editor originally designed as a replacement for Pico, the ncurses-based editor from the non-free mailer package Pine (itself now available under the Apache License as Alpine). - """, indent=4, block_seq_indent=2, top_level_colon_align=True, prefix_colon=' ') + """, + indent=4, + block_seq_indent=2, + top_level_colon_align=True, + prefix_colon=' ', + ) def guess(s): from ruamel.yaml.util import load_yaml_guess_indent + x, y, z = load_yaml_guess_indent(dedent(s)) return y, z class TestGuessIndent: def test_guess_20(self): - assert guess("""\ + assert ( + guess( + """\ a: - 1 - """) == (2, 0) + """ + ) + == (2, 0) + ) def test_guess_42(self): - assert guess("""\ + assert ( + guess( + """\ a: - 1 - """) == (4, 2) + """ + ) + == (4, 2) + ) def test_guess_42a(self): # block seq indent prevails over nested key indent level - assert guess("""\ + assert ( + guess( + """\ b: a: - 1 - """) == (4, 2) + """ + ) + == (4, 2) + ) def test_guess_3None(self): - assert guess("""\ + assert ( + guess( + """\ b: a: 1 - """) == (3, None) + """ + ) + == (3, None) + ) class TestSeparateMapSeqIndents: @@ -250,58 +331,70 @@ class TestSeparateMapSeqIndents: yaml = YAML() yaml.indent = 6 yaml.block_seq_indent = 3 - yaml.round_trip(""" + yaml.round_trip( + """ a: - 1 - [1, 2] - """) + """ + ) def test_01(self): yaml = YAML() yaml.indent(sequence=6) yaml.indent(offset=3) - yaml.round_trip(""" + yaml.round_trip( + """ a: - 1 - {b: 3} - """) + """ + ) def test_02(self): yaml = YAML() yaml.indent(mapping=5, sequence=6, offset=3) - yaml.round_trip(""" + yaml.round_trip( + """ a: b: - 1 - [1, 2] - """) + """ + ) def test_03(self): - round_trip(""" + round_trip( + """ a: b: c: - 1 - [1, 2] - """, indent=4) + """, + indent=4, + ) def test_04(self): yaml = YAML() yaml.indent(mapping=5, sequence=6) - yaml.round_trip(""" + yaml.round_trip( + """ a: b: - 1 - [1, 2] - {d: 3.14} - """) + """ + ) def test_issue_51(self): yaml = YAML() # yaml.map_indent = 2 # the default yaml.indent(sequence=4, offset=2) yaml.preserve_quotes = True - yaml.round_trip(""" + yaml.round_trip( + """ role::startup::author::rsyslog_inputs: imfile: - ruleset: 'AEM-slinglog' @@ -312,6 +405,8 @@ class TestSeparateMapSeqIndents: File: '/opt/aem/author/crx-quickstart/logs/stdout.log' startmsg.regex: '^[-+T.:[:digit:]]*' tag: 'stdout' - """) + """ + ) + # ############ indentation diff --git a/_test/test_int.py b/_test/test_int.py index 080eb54..daf4fda 100644 --- a/_test/test_int.py +++ b/_test/test_int.py @@ -12,23 +12,27 @@ from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump class TestBinHexOct: # @pytest.mark.xfail(strict=True) def test_round_trip_hex_oct(self): - round_trip("""\ + round_trip( + """\ - 42 - 0b101010 - 0x2a - 0x2A - 0o52 - """) + """ + ) def test_calculate(self): # make sure type, leading zero(s) and underscore are preserved - s = dedent("""\ + s = dedent( + """\ - 42 - 0b101010 - 0x_2a - 0x2A - 0o00_52 - """) + """ + ) x = round_trip_load(s) for idx, elem in enumerate(x): # x[idx] = type(elem)(elem - 21) @@ -51,7 +55,8 @@ class TestBinHexOct: # the old octal representation. def test_leading_zero_hex_oct_bin(self): - round_trip("""\ + round_trip( + """\ - 0b0101010 - 0b00101010 - 0x02a @@ -60,26 +65,32 @@ class TestBinHexOct: - 0x002A - 0o052 - 0o0052 - """) + """ + ) def test_leading_zero_int(self): - round_trip("""\ + round_trip( + """\ - 042 - 0042 - """) + """ + ) def test_leading_zero_YAML_1_1(self): - d = round_trip_load("""\ + d = round_trip_load( + """\ %YAML 1.1 --- - 042 - 0o42 - """) + """ + ) assert d[0] == 0o42 assert d[1] == '0o42' def test_underscore(self): - round_trip("""\ + round_trip( + """\ - 0b10000_10010010 - 0b0_0000_1001_0010 - 0x2_87_57_b2_ @@ -87,23 +98,28 @@ class TestBinHexOct: - 0x_0_2_8_7_5_7_B_2 - 0o2416_53662 - 42_42_ - """) + """ + ) def test_leading_underscore(self): - d = round_trip_load("""\ + d = round_trip_load( + """\ - 0x_2_8_7_5_7_B_2 - _42_42_ - 42_42_ - """) + """ + ) assert d[0] == 42424242 assert d[1] == '_42_42_' assert d[2] == 4242 def test_big(self): # bitbucket issue 144 reported by ccatterina - d = round_trip_load("""\ + d = round_trip_load( + """\ - 2_147_483_647 - 9_223_372_036_854_775_808 - """) + """ + ) assert d[0] == 2147483647 assert d[1] == 9223372036854775808 diff --git a/_test/test_issues.py b/_test/test_issues.py index 0e01875..559dcba 100644 --- a/_test/test_issues.py +++ b/_test/test_issues.py @@ -12,7 +12,9 @@ from roundtrip import round_trip, round_trip_load, round_trip_dump, dedent # NO class TestIssue61: def test_issue_61(self): import ruamel.yaml - s = dedent(""" + + s = dedent( + """ def1: &ANCHOR1 key1: value1 def: &ANCHOR @@ -20,7 +22,8 @@ class TestIssue61: key: value comb: <<: *ANCHOR - """) + """ + ) data = ruamel.yaml.round_trip_load(s) assert str(data['comb']) == str(data['def']) assert str(data['comb']) == "ordereddict([('key', 'value'), ('key1', 'value1')])" diff --git a/_test/test_json_numbers.py b/_test/test_json_numbers.py index a580277..56b7b6f 100644 --- a/_test/test_json_numbers.py +++ b/_test/test_json_numbers.py @@ -9,6 +9,7 @@ import json def load(s, typ=float): import ruamel.yaml + x = '{"low": %s }' % (s) print('input: [%s]' % (s), repr(x)) # just to check it is loadable json @@ -27,23 +28,29 @@ class TestJSONNumbers: # # which is not a superset of the JSON numbers def test_json_number_float(self): - for x in (y.split('#')[0].strip() for y in """ + for x in ( + y.split('#')[0].strip() + for y in """ 1.0 # should fail on YAML spec on 1-9 allowed as single digit -1.0 1e-06 3.1e-5 3.1e+5 3.1e5 # should fail on YAML spec: no +- after e - """.splitlines()): + """.splitlines() + ): if not x: continue res = load(x) assert isinstance(res, float) def test_json_number_int(self): - for x in (y.split('#')[0].strip() for y in """ + for x in ( + y.split('#')[0].strip() + for y in """ 42 - """.splitlines()): + """.splitlines() + ): if not x: continue res = load(x, int) diff --git a/_test/test_line_col.py b/_test/test_line_col.py index febe9c2..4f7ad5d 100644 --- a/_test/test_line_col.py +++ b/_test/test_line_col.py @@ -11,80 +11,94 @@ def load(s): class TestLineCol: def test_item_00(self): - data = load(""" + data = load( + """ - a - e - [b, d] - c - """) + """ + ) assert data[2].lc.line == 2 assert data[2].lc.col == 2 def test_item_01(self): - data = load(""" + data = load( + """ - a - e - {x: 3} - c - """) + """ + ) assert data[2].lc.line == 2 assert data[2].lc.col == 2 def test_item_02(self): - data = load(""" + data = load( + """ - a - e - !!set {x, y} - c - """) + """ + ) assert data[2].lc.line == 2 assert data[2].lc.col == 2 def test_item_03(self): - data = load(""" + data = load( + """ - a - e - !!omap - x: 1 - y: 3 - c - """) + """ + ) assert data[2].lc.line == 2 assert data[2].lc.col == 2 def test_item_04(self): - data = load(""" + data = load( + """ # testing line and column based on SO # http://stackoverflow.com/questions/13319067/ - key1: item 1 key2: item 2 - key3: another item 1 key4: another item 2 - """) + """ + ) assert data[0].lc.line == 2 assert data[0].lc.col == 2 assert data[1].lc.line == 4 assert data[1].lc.col == 2 def test_pos_mapping(self): - data = load(""" + data = load( + """ a: 1 b: 2 c: 3 # comment klm: 42 d: 4 - """) + """ + ) assert data.lc.key('klm') == (4, 0) assert data.lc.value('klm') == (4, 5) def test_pos_sequence(self): - data = load(""" + data = load( + """ - a - b - c # next one! - klm - d - """) + """ + ) assert data.lc.item(3) == (4, 2) diff --git a/_test/test_literal.py b/_test/test_literal.py index 0499a16..74dca3d 100644 --- a/_test/test_literal.py +++ b/_test/test_literal.py @@ -31,126 +31,178 @@ class TestNoIndent: def test_top_literal_scalar_indent_example_9_5(self): yaml = YAML() s = '%!PS-Adobe-2.0' - d = yaml.load(""" + d = yaml.load( + """ --- | {} - """.format(s)) + """.format( + s + ) + ) print(d) assert d == s + '\n' def test_top_literal_scalar_no_indent(self): yaml = YAML() s = 'testing123' - d = yaml.load(""" + d = yaml.load( + """ --- | {} - """.format(s)) + """.format( + s + ) + ) print(d) assert d == s + '\n' def test_top_literal_scalar_no_indent_1_1(self): yaml = YAML() s = 'testing123' - d = yaml.load(""" + d = yaml.load( + """ %YAML 1.1 --- | {} - """.format(s)) + """.format( + s + ) + ) print(d) assert d == s + '\n' def test_top_literal_scalar_no_indent_1_1_old_style(self): from textwrap import dedent from ruamel.yaml import safe_load + s = 'testing123' - d = safe_load(dedent(""" + d = safe_load( + dedent( + """ %YAML 1.1 --- | {} - """.format(s))) + """.format( + s + ) + ) + ) print(d) assert d == s + '\n' def test_top_literal_scalar_no_indent_1_1_raise(self): from ruamel.yaml.parser import ParserError + yaml = YAML() yaml.top_level_block_style_scalar_no_indent_error_1_1 = True s = 'testing123' with pytest.raises(ParserError): - yaml.load(""" + yaml.load( + """ %YAML 1.1 --- | {} - """.format(s)) + """.format( + s + ) + ) def test_top_literal_scalar_indent_offset_one(self): yaml = YAML() s = 'testing123' - d = yaml.load(""" + d = yaml.load( + """ --- |1 {} - """.format(s)) + """.format( + s + ) + ) print(d) assert d == s + '\n' def test_top_literal_scalar_indent_offset_four(self): yaml = YAML() s = 'testing123' - d = yaml.load(""" + d = yaml.load( + """ --- |4 {} - """.format(s)) + """.format( + s + ) + ) print(d) assert d == s + '\n' def test_top_literal_scalar_indent_offset_two_leading_space(self): yaml = YAML() s = ' testing123' - d = yaml.load(""" + d = yaml.load( + """ --- |4 {s} {s} - """.format(s=s)) + """.format( + s=s + ) + ) print(d) assert d == (s + '\n') * 2 def test_top_literal_scalar_no_indent_special(self): yaml = YAML() s = '%!PS-Adobe-2.0' - d = yaml.load(""" + d = yaml.load( + """ --- | {} - """.format(s)) + """.format( + s + ) + ) print(d) assert d == s + '\n' def test_top_folding_scalar_indent(self): yaml = YAML() s = '%!PS-Adobe-2.0' - d = yaml.load(""" + d = yaml.load( + """ --- > {} - """.format(s)) + """.format( + s + ) + ) print(d) assert d == s + '\n' def test_top_folding_scalar_no_indent(self): yaml = YAML() s = 'testing123' - d = yaml.load(""" + d = yaml.load( + """ --- > {} - """.format(s)) + """.format( + s + ) + ) print(d) assert d == s + '\n' def test_top_folding_scalar_no_indent_special(self): yaml = YAML() s = '%!PS-Adobe-2.0' - d = yaml.load(""" + d = yaml.load( + """ --- > {} - """.format(s)) + """.format( + s + ) + ) print(d) assert d == s + '\n' @@ -158,12 +210,18 @@ class TestNoIndent: yaml = YAML(typ='safe', pure=True) s1 = 'abc' s2 = 'klm' - for idx, d1 in enumerate(yaml.load_all(""" + for idx, d1 in enumerate( + yaml.load_all( + """ --- |- {} --- | {} - """.format(s1, s2))): + """.format( + s1, s2 + ) + ) + ): print('d1:', d1) assert ['abc', 'klm\n'][idx] == d1 @@ -176,7 +234,9 @@ class Test_RoundTripLiteral: ys = """ --- | {} - """.format(s) + """.format( + s + ) d = yaml.load(ys) yaml.dump(d, compare=ys) @@ -188,7 +248,9 @@ class Test_RoundTripLiteral: ys = """ --- | {} - """.format(s) + """.format( + s + ) d = yaml.load(ys) yaml.dump(d, compare=ys) @@ -200,7 +262,9 @@ class Test_RoundTripLiteral: ys = """ --- {} - """.format(s) + """.format( + s + ) d = yaml.load(ys) yaml.dump(d, compare=ys) @@ -212,7 +276,9 @@ class Test_RoundTripLiteral: ys = """ --- {} - """.format(s) + """.format( + s + ) d = yaml.load(ys) yaml.dump(d, compare=ys) @@ -224,7 +290,9 @@ class Test_RoundTripLiteral: ys = """ --- {} - """.format(s) + """.format( + s + ) d = yaml.load(ys) yaml.dump(d, compare=ys) @@ -238,7 +306,9 @@ class Test_RoundTripLiteral: ys = """ --- {} - """.format(s) + """.format( + s + ) d = yaml.load(ys) yaml.dump(d, compare=ys) @@ -249,7 +319,9 @@ class Test_RoundTripLiteral: ys = """ --- |- {} - """.format(s) + """.format( + s + ) d = yaml.load(ys) yaml.dump(d, compare=ys) @@ -259,6 +331,8 @@ class Test_RoundTripLiteral: ys = """ - | {} - """.format(s) + """.format( + s + ) d = yaml.load(ys) yaml.dump(d, compare=ys) diff --git a/_test/test_none.py b/_test/test_none.py index 681f1e0..e313edc 100644 --- a/_test/test_none.py +++ b/_test/test_none.py @@ -1,12 +1,13 @@ # coding: utf-8 -import pytest # NOQA +import pytest # NOQA class TestNone: def test_dump00(self): - import ruamel.yaml # NOQA + import ruamel.yaml # NOQA + data = None s = ruamel.yaml.round_trip_dump(data) assert s == 'null\n...\n' @@ -14,7 +15,8 @@ class TestNone: assert d == data def test_dump01(self): - import ruamel.yaml # NOQA + import ruamel.yaml # NOQA + data = None s = ruamel.yaml.round_trip_dump(data, explicit_end=True) assert s == 'null\n...\n' @@ -22,7 +24,8 @@ class TestNone: assert d == data def test_dump02(self): - import ruamel.yaml # NOQA + import ruamel.yaml # NOQA + data = None s = ruamel.yaml.round_trip_dump(data, explicit_end=False) assert s == 'null\n...\n' @@ -30,7 +33,8 @@ class TestNone: assert d == data def test_dump03(self): - import ruamel.yaml # NOQA + import ruamel.yaml # NOQA + data = None s = ruamel.yaml.round_trip_dump(data, explicit_start=True) assert s == '---\n...\n' @@ -38,7 +42,8 @@ class TestNone: assert d == data def test_dump04(self): - import ruamel.yaml # NOQA + import ruamel.yaml # NOQA + data = None s = ruamel.yaml.round_trip_dump(data, explicit_start=True, explicit_end=False) assert s == '---\n...\n' diff --git a/_test/test_numpy.py b/_test/test_numpy.py index e3a7718..2747fc4 100644 --- a/_test/test_numpy.py +++ b/_test/test_numpy.py @@ -10,6 +10,7 @@ except: # NOQA def Xtest_numpy(): import ruamel.yaml + if numpy is None: return data = numpy.arange(10) diff --git a/_test/test_program_config.py b/_test/test_program_config.py index dcd8351..4d7cbd5 100644 --- a/_test/test_program_config.py +++ b/_test/test_program_config.py @@ -8,7 +8,8 @@ from roundtrip import round_trip class TestProgramConfig: def test_application_arguments(self): # application configur - round_trip(""" + round_trip( + """ args: username: anthon passwd: secret @@ -17,11 +18,13 @@ class TestProgramConfig: session-name: test loop: wait: 10 - """) + """ + ) def test_single(self): # application configuration - round_trip(""" + round_trip( + """ # default arguments for the program args: # needed to prevent comment wrapping # this should be your username @@ -36,11 +39,13 @@ class TestProgramConfig: # experiment with the following wait: 10 # no more argument info to pass - """) + """ + ) def test_multi(self): # application configuration - round_trip(""" + round_trip( + """ # default arguments for the program args: # needed to prevent comment wrapping # this should be your username @@ -55,4 +60,5 @@ class TestProgramConfig: # experiment with the following wait: 10 # no more argument info to pass - """) + """ + ) diff --git a/_test/test_string.py b/_test/test_string.py index f095095..351ca0e 100644 --- a/_test/test_string.py +++ b/_test/test_string.py @@ -24,26 +24,35 @@ from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NO class TestPreservedScalarString: def test_basic_string(self): - round_trip(""" + round_trip( + """ a: abcdefg - """, ) + """ + ) def test_quoted_integer_string(self): - round_trip(""" + round_trip( + """ a: '12345' - """) + """ + ) - @pytest.mark.skipif(platform.python_implementation() == 'Jython', - reason="Jython throws RepresenterError") + @pytest.mark.skipif( + platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' + ) def test_preserve_string(self): - round_trip(""" + round_trip( + """ a: | abc def - """, intermediate=dict(a='abc\ndef\n')) + """, + intermediate=dict(a='abc\ndef\n'), + ) - @pytest.mark.skipif(platform.python_implementation() == 'Jython', - reason="Jython throws RepresenterError") + @pytest.mark.skipif( + platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' + ) def test_preserve_string_strip(self): s = """ a: |- @@ -53,105 +62,140 @@ class TestPreservedScalarString: """ round_trip(s, intermediate=dict(a='abc\ndef')) - @pytest.mark.skipif(platform.python_implementation() == 'Jython', - reason="Jython throws RepresenterError") + @pytest.mark.skipif( + platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' + ) def test_preserve_string_keep(self): - # with pytest.raises(AssertionError) as excinfo: - round_trip(""" + # with pytest.raises(AssertionError) as excinfo: + round_trip( + """ a: |+ ghi jkl b: x - """, intermediate=dict(a='ghi\njkl\n\n\n', b='x')) + """, + intermediate=dict(a='ghi\njkl\n\n\n', b='x'), + ) - @pytest.mark.skipif(platform.python_implementation() == 'Jython', - reason="Jython throws RepresenterError") + @pytest.mark.skipif( + platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' + ) def test_preserve_string_keep_at_end(self): # at EOF you have to specify the ... to get proper "closure" # of the multiline scalar - round_trip(""" + round_trip( + """ a: |+ ghi jkl ... - """, intermediate=dict(a='ghi\njkl\n\n')) + """, + intermediate=dict(a='ghi\njkl\n\n'), + ) def test_fold_string(self): with pytest.raises(AssertionError) as excinfo: # NOQA - round_trip(""" + round_trip( + """ a: > abc def - """, intermediate=dict(a='abc def\n')) + """, + intermediate=dict(a='abc def\n'), + ) def test_fold_string_strip(self): with pytest.raises(AssertionError) as excinfo: # NOQA - round_trip(""" + round_trip( + """ a: >- abc def - """, intermediate=dict(a='abc def')) + """, + intermediate=dict(a='abc def'), + ) def test_fold_string_keep(self): with pytest.raises(AssertionError) as excinfo: # NOQA - round_trip(""" + round_trip( + """ a: >+ abc def - """, intermediate=dict(a='abc def\n\n')) + """, + intermediate=dict(a='abc def\n\n'), + ) class TestQuotedScalarString: def test_single_quoted_string(self): - round_trip(""" + round_trip( + """ a: 'abc' - """, preserve_quotes=True) + """, + preserve_quotes=True, + ) def test_double_quoted_string(self): - round_trip(""" + round_trip( + """ a: "abc" - """, preserve_quotes=True) + """, + preserve_quotes=True, + ) def test_non_preserved_double_quoted_string(self): - round_trip(""" + round_trip( + """ a: "abc" - """, outp=""" + """, + outp=""" a: abc - """) + """, + ) class TestReplace: """inspired by issue 110 from sandres23""" + def test_replace_preserved_scalar_string(self): import ruamel - s = dedent("""\ + + s = dedent( + """\ foo: | foo foo bar foo - """) + """ + ) data = round_trip_load(s, preserve_quotes=True) so = data['foo'].replace('foo', 'bar', 2) assert isinstance(so, ruamel.yaml.scalarstring.PreservedScalarString) - assert so == dedent(""" + assert so == dedent( + """ bar bar bar foo - """) + """ + ) def test_replace_double_quoted_scalar_string(self): import ruamel - s = dedent("""\ + + s = dedent( + """\ foo: "foo foo bar foo" - """) + """ + ) data = round_trip_load(s, preserve_quotes=True) so = data['foo'].replace('foo', 'bar', 2) assert isinstance(so, ruamel.yaml.scalarstring.DoubleQuotedScalarString) diff --git a/_test/test_tag.py b/_test/test_tag.py index c4fabc0..824a0c3 100644 --- a/_test/test_tag.py +++ b/_test/test_tag.py @@ -1,6 +1,6 @@ # coding: utf-8 -import pytest # NOQA +import pytest # NOQA from roundtrip import round_trip, round_trip_load @@ -25,92 +25,112 @@ def register_xxx(**kw): class TestIndentFailures: def test_tag(self): - round_trip("""\ + round_trip( + """\ !!python/object:__main__.Developer name: Anthon location: Germany language: python - """) + """ + ) def test_full_tag(self): - round_trip("""\ + round_trip( + """\ !!tag:yaml.org,2002:python/object:__main__.Developer name: Anthon location: Germany language: python - """) + """ + ) def test_standard_tag(self): - round_trip("""\ + round_trip( + """\ !!tag:yaml.org,2002:python/object:map name: Anthon location: Germany language: python - """) + """ + ) def test_Y1(self): - round_trip("""\ + round_trip( + """\ !yyy name: Anthon location: Germany language: python - """) + """ + ) def test_Y2(self): - round_trip("""\ + round_trip( + """\ !!yyy name: Anthon location: Germany language: python - """) + """ + ) class TestRoundTripCustom: def test_X1(self): register_xxx() - round_trip("""\ + round_trip( + """\ !xxx name: Anthon location: Germany language: python - """) + """ + ) @pytest.mark.xfail(strict=True) def test_X_pre_tag_comment(self): register_xxx() - round_trip("""\ + round_trip( + """\ - # hello !xxx name: Anthon location: Germany language: python - """) + """ + ) @pytest.mark.xfail(strict=True) def test_X_post_tag_comment(self): register_xxx() - round_trip("""\ + round_trip( + """\ - !xxx # hello name: Anthon location: Germany language: python - """) + """ + ) def test_scalar_00(self): # https://stackoverflow.com/a/45967047/1307905 - round_trip("""\ + round_trip( + """\ Outputs: Vpc: Value: !Ref: vpc # first tag Export: Name: !Sub "${AWS::StackName}-Vpc" # second tag - """) + """ + ) class TestIssue201: def test_encoded_unicode_tag(self): - round_trip_load(""" + round_trip_load( + """ s: !!python/%75nicode 'abc' - """) + """ + ) diff --git a/_test/test_version.py b/_test/test_version.py index 0855a5c..9aa4133 100644 --- a/_test/test_version.py +++ b/_test/test_version.py @@ -1,18 +1,20 @@ # coding: utf-8 -import pytest # NOQA +import pytest # NOQA from roundtrip import dedent, round_trip, round_trip_load def load(s, version=None): import ruamel.yaml # NOQA + return ruamel.yaml.round_trip_load(dedent(s), version) class TestVersions: def test_explicit_1_2(self): - r = load("""\ + r = load( + """\ %YAML 1.2 --- - 12:34:56 @@ -24,7 +26,8 @@ class TestVersions: - yes - no - true - """) + """ + ) assert r[0] == '12:34:56' assert r[1] == 12 assert r[2] == 12345678 @@ -36,7 +39,8 @@ class TestVersions: assert r[8] is True def test_explicit_1_1(self): - r = load("""\ + r = load( + """\ %YAML 1.1 --- - 12:34:56 @@ -48,7 +52,8 @@ class TestVersions: - yes - no - true - """) + """ + ) assert r[0] == 45296 assert r[1] == 10 assert r[2] == '012345678' @@ -60,7 +65,8 @@ class TestVersions: assert r[8] is True def test_implicit_1_2(self): - r = load("""\ + r = load( + """\ - 12:34:56 - 12:34:56.78 - 012 @@ -71,7 +77,8 @@ class TestVersions: - yes - no - true - """) + """ + ) assert r[0] == '12:34:56' assert r[1] == '12:34:56.78' assert r[2] == 12 @@ -84,7 +91,8 @@ class TestVersions: assert r[9] is True def test_load_version_1_1(self): - r = load("""\ + r = load( + """\ - 12:34:56 - 12:34:56.78 - 012 @@ -95,7 +103,9 @@ class TestVersions: - yes - no - true - """, version="1.1") + """, + version='1.1', + ) assert r[0] == 45296 assert r[1] == 45296.78 assert r[2] == 10 @@ -112,7 +122,9 @@ class TestIssue62: # bitbucket issue 62, issue_62 def test_00(self): import ruamel.yaml # NOQA - s = dedent("""\ + + s = dedent( + """\ {}# Outside flow collection: - ::vector - ": - ()" @@ -121,14 +133,17 @@ class TestIssue62: - http://example.com/foo#bar # Inside flow collection: - [::vector, ": - ()", "Down, down and away!", -456, http://example.com/foo#bar] - """) + """ + ) with pytest.raises(ruamel.yaml.parser.ParserError): round_trip(s.format('%YAML 1.1\n---\n'), preserve_quotes=True) - round_trip(s.format(''), preserve_quotes=True) + round_trip(s.format(""), preserve_quotes=True) def test_00_single_comment(self): import ruamel.yaml # NOQA - s = dedent("""\ + + s = dedent( + """\ {}# Outside flow collection: - ::vector - ": - ()" @@ -136,22 +151,26 @@ class TestIssue62: - -123 - http://example.com/foo#bar - [::vector, ": - ()", "Down, down and away!", -456, http://example.com/foo#bar] - """) + """ + ) with pytest.raises(ruamel.yaml.parser.ParserError): round_trip(s.format('%YAML 1.1\n---\n'), preserve_quotes=True) - round_trip(s.format(''), preserve_quotes=True) + round_trip(s.format(""), preserve_quotes=True) # round_trip(s.format('%YAML 1.2\n---\n'), preserve_quotes=True, version=(1, 2)) def test_01(self): import ruamel.yaml # NOQA - s = dedent("""\ + + s = dedent( + """\ {}[random plain value that contains a ? character] - """) + """ + ) with pytest.raises(ruamel.yaml.parser.ParserError): round_trip(s.format('%YAML 1.1\n---\n'), preserve_quotes=True) - round_trip(s.format(''), preserve_quotes=True) + round_trip(s.format(""), preserve_quotes=True) # note the flow seq on the --- line! - round_trip(s.format('%YAML 1.2\n--- '), preserve_quotes=True, version="1.2") + round_trip(s.format('%YAML 1.2\n--- '), preserve_quotes=True, version='1.2') def test_so_45681626(self): # was not properly parsing diff --git a/_test/test_yamlfile.py b/_test/test_yamlfile.py index d1ba63c..b5897f0 100644 --- a/_test/test_yamlfile.py +++ b/_test/test_yamlfile.py @@ -6,7 +6,7 @@ various test cases for YAML files """ import sys -import pytest # NOQA +import pytest # NOQA import platform from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NOQA @@ -14,66 +14,77 @@ from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NO class TestYAML: def test_backslash(self): - round_trip(""" + round_trip( + """ handlers: static_files: applications/\\1/static/\\2 - """) + """ + ) def test_omap_out(self): # ordereddict mapped to !!omap from ruamel.yaml.compat import ordereddict import ruamel.yaml # NOQA + x = ordereddict([('a', 1), ('b', 2)]) res = ruamel.yaml.dump(x, default_flow_style=False) - assert res == dedent(""" + assert res == dedent( + """ !!omap - a: 1 - b: 2 - """) + """ + ) def test_omap_roundtrip(self): - round_trip(""" + round_trip( + """ !!omap - a: 1 - b: 2 - c: 3 - d: 4 - """) + """ + ) - @pytest.mark.skipif(sys.version_info < (2, 7), reason="collections not available") + @pytest.mark.skipif(sys.version_info < (2, 7), reason='collections not available') def test_dump_collections_ordereddict(self): from collections import OrderedDict import ruamel.yaml # NOQA + # OrderedDict mapped to !!omap x = OrderedDict([('a', 1), ('b', 2)]) - res = ruamel.yaml.dump(x, - Dumper=ruamel.yaml.RoundTripDumper, - default_flow_style=False) - assert res == dedent(""" + res = ruamel.yaml.dump(x, Dumper=ruamel.yaml.RoundTripDumper, default_flow_style=False) + assert res == dedent( + """ !!omap - a: 1 - b: 2 - """) + """ + ) - @pytest.mark.skipif(sys.version_info >= (3, 0) or - platform.python_implementation() != "CPython", - reason="ruamel.yaml not available") + @pytest.mark.skipif( + sys.version_info >= (3, 0) or platform.python_implementation() != 'CPython', + reason='ruamel.yaml not available', + ) def test_dump_ruamel_ordereddict(self): from ruamel.ordereddict import ordereddict import ruamel.yaml # NOQA + # OrderedDict mapped to !!omap x = ordereddict([('a', 1), ('b', 2)]) - res = ruamel.yaml.dump(x, - Dumper=ruamel.yaml.RoundTripDumper, - default_flow_style=False) - assert res == dedent(""" + res = ruamel.yaml.dump(x, Dumper=ruamel.yaml.RoundTripDumper, default_flow_style=False) + assert res == dedent( + """ !!omap - a: 1 - b: 2 - """) + """ + ) def test_CommentedSet(self): from ruamel.yaml.constructor import CommentedSet + s = CommentedSet(['a', 'b', 'c']) s.remove('b') s.add('d') @@ -86,46 +97,56 @@ class TestYAML: def test_set_out(self): # preferable would be the shorter format without the ': null' import ruamel.yaml # NOQA + x = set(['a', 'b', 'c']) res = ruamel.yaml.dump(x, default_flow_style=False) - assert res == dedent(""" + assert res == dedent( + """ !!set a: null b: null c: null - """) + """ + ) # @pytest.mark.xfail # ordering is not preserved in a set def test_set_compact(self): # this format is read and also should be written by default - round_trip(""" + round_trip( + """ !!set ? a ? b ? c - """) + """ + ) def test_blank_line_after_comment(self): - round_trip(""" + round_trip( + """ # Comment with spaces after it. a: 1 - """) + """ + ) def test_blank_line_between_seq_items(self): - round_trip(""" + round_trip( + """ # Seq with spaces in between items. b: - bar - baz - """) + """ + ) - @pytest.mark.skipif(platform.python_implementation() == 'Jython', - reason="Jython throws RepresenterError") + @pytest.mark.skipif( + platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' + ) def test_blank_line_after_literal_chip(self): s = """ c: @@ -147,8 +168,9 @@ class TestYAML: assert d['c'][0].split('it.')[1] == '\n' assert d['c'][1].split('line.')[1] == '\n' - @pytest.mark.skipif(platform.python_implementation() == 'Jython', - reason="Jython throws RepresenterError") + @pytest.mark.skipif( + platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' + ) def test_blank_line_after_literal_keep(self): """ have to insert an eof marker in YAML to test this""" s = """ @@ -172,8 +194,9 @@ class TestYAML: assert d['c'][0].split('it.')[1] == '\n\n' assert d['c'][1].split('line.')[1] == '\n\n\n' - @pytest.mark.skipif(platform.python_implementation() == 'Jython', - reason="Jython throws RepresenterError") + @pytest.mark.skipif( + platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' + ) def test_blank_line_after_literal_strip(self): s = """ c: @@ -192,16 +215,19 @@ class TestYAML: d = round_trip_load(dedent(s)) print(d) round_trip(s) - assert d['c'][0].split('it.')[1] == '' - assert d['c'][1].split('line.')[1] == '' + assert d['c'][0].split('it.')[1] == "" + assert d['c'][1].split('line.')[1] == "" def test_load_all_perserve_quotes(self): import ruamel.yaml # NOQA - s = dedent("""\ + + s = dedent( + """\ a: 'hello' --- b: "goodbye" - """) + """ + ) data = [] for x in ruamel.yaml.round_trip_load_all(s, preserve_quotes=True): data.append(x) diff --git a/_test/test_yamlobject.py b/_test/test_yamlobject.py index 4147bc3..1d730b5 100644 --- a/_test/test_yamlobject.py +++ b/_test/test_yamlobject.py @@ -2,7 +2,7 @@ from __future__ import print_function -import pytest # NOQA +import pytest # NOQA from roundtrip import save_and_run # NOQA diff --git a/_test/test_z_check_debug_leftovers.py b/_test/test_z_check_debug_leftovers.py index f5be5df..37d6970 100644 --- a/_test/test_z_check_debug_leftovers.py +++ b/_test/test_z_check_debug_leftovers.py @@ -10,25 +10,29 @@ class TestLeftOverDebug: # idea here is to capture round_trip_output via pytest stdout capture # if there is are any leftover debug statements they should show up def test_00(self, capsys): - s = dedent(""" + s = dedent( + """ a: 1 b: [] c: [a, 1] d: {f: 3.14, g: 42} - """) + """ + ) d = round_trip_load(s) round_trip_dump(d, sys.stdout) out, err = capsys.readouterr() assert out == s def test_01(self, capsys): - s = dedent(""" + s = dedent( + """ - 1 - [] - [a, 1] - {f: 3.14, g: 42} - - 123 - """) + """ + ) d = round_trip_load(s) round_trip_dump(d, sys.stdout) out, err = capsys.readouterr() diff --git a/_test/test_z_data.py b/_test/test_z_data.py index 9ea921b..5a142cf 100644 --- a/_test/test_z_data.py +++ b/_test/test_z_data.py @@ -4,12 +4,12 @@ from __future__ import print_function import sys import os -import pytest # NOQA +import pytest # NOQA import platform # NOQA sys.path.insert(0, os.path.dirname(__file__) + '/lib') -import warnings # NOQA +import warnings # NOQA args = [] @@ -17,8 +17,10 @@ args = [] def test_data(): import test_appliance # NOQA + collections = [] import test_yaml + collections.append(test_yaml) test_appliance.run(collections, args) @@ -26,12 +28,15 @@ def test_data(): # @pytest.mark.skipif(not ruamel.yaml.__with_libyaml__, # reason="no libyaml") + def test_data_ext(): collections = [] - import ruamel.yaml # NOQA + import ruamel.yaml # NOQA import test_appliance # NOQA + warnings.simplefilter('ignore', ruamel.yaml.error.UnsafeLoaderWarning) if ruamel.yaml.__with_libyaml__: import test_yaml_ext + collections.append(test_yaml_ext) test_appliance.run(collections, args) |