diff options
author | Anthon van der Neut <anthon@mnt.org> | 2023-05-01 19:13:50 +0200 |
---|---|---|
committer | Anthon van der Neut <anthon@mnt.org> | 2023-05-01 19:13:50 +0200 |
commit | 8b731994b1543d7886af85f926d9eea5a22d0732 (patch) | |
tree | 3553d4cbc80b541484d7a3f39e00cdcfd8f9d030 /_test | |
parent | 45111ba0b67e8619265d89f3202635e62c13cde6 (diff) | |
download | ruamel.yaml-8b731994b1543d7886af85f926d9eea5a22d0732.tar.gz |
retrofitted 0.18 changes
Diffstat (limited to '_test')
42 files changed, 879 insertions, 801 deletions
diff --git a/_test/lib/canonical.py b/_test/lib/canonical.py index 8a00772..31c9728 100644 --- a/_test/lib/canonical.py +++ b/_test/lib/canonical.py @@ -348,28 +348,32 @@ ruamel.yaml.canonical_scan = canonical_scan def canonical_parse(stream): - return ruamel.yaml.parse(stream, Loader=CanonicalLoader) + yaml = ruamel.yaml.YAML() + return yaml.parse(stream, Loader=CanonicalLoader) ruamel.yaml.canonical_parse = canonical_parse def canonical_compose(stream): - return ruamel.yaml.compose(stream, Loader=CanonicalLoader) + yaml = ruamel.yaml.YAML() + return yaml.compose(stream, Loader=CanonicalLoader) ruamel.yaml.canonical_compose = canonical_compose def canonical_compose_all(stream): - return ruamel.yaml.compose_all(stream, Loader=CanonicalLoader) + yaml = ruamel.yaml.YAML() + return yaml.compose_all(stream, Loader=CanonicalLoader) ruamel.yaml.canonical_compose_all = canonical_compose_all def canonical_load(stream): - return ruamel.yaml.load(stream, Loader=CanonicalLoader) + yaml = ruamel.yaml.YAML() + return yaml.load(stream, Loader=CanonicalLoader) ruamel.yaml.canonical_load = canonical_load diff --git a/_test/lib/test_constructor.py b/_test/lib/test_constructor.py index 738aaec..b38bf2f 100644 --- a/_test/lib/test_constructor.py +++ b/_test/lib/test_constructor.py @@ -121,7 +121,7 @@ def _make_objects(): else: return False - class AnObject(object): + class AnObject: def __new__(cls, foo=None, bar=None, baz=None): self = object.__new__(cls) self.foo = foo diff --git a/_test/lib/test_emitter.py b/_test/lib/test_emitter.py index fbdbb79..b1991e3 100644 --- a/_test/lib/test_emitter.py +++ b/_test/lib/test_emitter.py @@ -1,7 +1,8 @@ from __future__ import absolute_import from __future__ import print_function -import ruamel.yaml as yaml +import ruamel.yaml +from ruamel.yaml import YAML def _compare_events(events1, events2): @@ -20,8 +21,8 @@ def _compare_events(events1, events2): def test_emitter_on_data(data_filename, canonical_filename, verbose=False): with open(data_filename, 'rb') as fp0: - events = list(yaml.parse(fp0)) - output = yaml.emit(events) + events = list(YAML().parse(fp0)) + output = YAML().emit(events) if verbose: print('OUTPUT:') print(output) @@ -34,9 +35,9 @@ test_emitter_on_data.unittest = ['.data', '.canonical'] def test_emitter_on_canonical(canonical_filename, verbose=False): with open(canonical_filename, 'rb') as fp0: - events = list(yaml.parse(fp0)) + events = list(YAML().parse(fp0)) for canonical in [False, True]: - output = yaml.emit(events, canonical=canonical) + output = YAML().emit(events, canonical=canonical) if verbose: print('OUTPUT (canonical=%s):' % canonical) print(output) @@ -50,7 +51,7 @@ test_emitter_on_canonical.unittest = ['.canonical'] def test_emitter_styles(data_filename, canonical_filename, verbose=False): for filename in [data_filename, canonical_filename]: with open(filename, 'rb') as fp0: - events = list(yaml.parse(fp0)) + events = list(YAML().parse(fp0)) for flow_style in [False, True]: for style in ['|', '>', '"', "'", ""]: styled_events = [] @@ -68,23 +69,23 @@ def test_emitter_styles(data_filename, canonical_filename, verbose=False): event.anchor, event.tag, event.implicit, flow_style=flow_style ) styled_events.append(event) - output = yaml.emit(styled_events) + output = YAML().emit(styled_events) if verbose: print( 'OUTPUT (filename=%r, flow_style=%r, style=%r)' % (filename, flow_style, style) ) print(output) - new_events = list(yaml.parse(output)) + new_events = list(YAML().parse(output)) _compare_events(events, new_events) test_emitter_styles.unittest = ['.data', '.canonical'] -class EventsLoader(yaml.Loader): +class EventsLoader(ruamel.yaml.Loader): def construct_event(self, node): - if isinstance(node, yaml.ScalarNode): + if isinstance(node, ruamel.yaml.ScalarNode): mapping = {} else: mapping = self.construct_mapping(node) @@ -116,12 +117,12 @@ EventsLoader.add_constructor(None, EventsLoader.construct_event) def test_emitter_events(events_filename, verbose=False): with open(events_filename, 'rb') as fp0: - events = list(yaml.load(fp0, Loader=EventsLoader)) - output = yaml.emit(events) + events = list(YAML().load(fp0, Loader=EventsLoader)) + output = YAML().emit(events) if verbose: print('OUTPUT:') print(output) - new_events = list(yaml.parse(output)) + new_events = list(YAML().parse(output)) _compare_events(events, new_events) diff --git a/_test/lib/test_resolver.py b/_test/lib/test_resolver.py index 24373a7..b2b0839 100644 --- a/_test/lib/test_resolver.py +++ b/_test/lib/test_resolver.py @@ -1,5 +1,6 @@ -import ruamel.yaml as yaml +import ruamel.yaml +yaml = ruamel.yaml.YAML() import pprint diff --git a/_test/lib/test_structure.py b/_test/lib/test_structure.py index 470d267..8de24a3 100644 --- a/_test/lib/test_structure.py +++ b/_test/lib/test_structure.py @@ -84,9 +84,9 @@ def test_parser(data_filename, canonical_filename, verbose=False): events2 = None try: with open(data_filename, 'rb') as fp0: - events1 = list(ruamel.yaml.parse(fp0)) + events1 = list(ruamel.yaml.YAML().parse(fp0)) with open(canonical_filename, 'rb') as fp0: - events2 = list(ruamel.yaml.canonical_parse(fp0)) + events2 = list(ruamel.yaml.YAML().canonical_parse(fp0)) _compare_events(events1, events2) finally: if verbose: @@ -104,9 +104,9 @@ def test_parser_on_canonical(canonical_filename, verbose=False): events2 = None try: with open(canonical_filename, 'rb') as fp0: - events1 = list(ruamel.yaml.parse(fp0)) + events1 = list(ruamel.yaml.YAML().parse(fp0)) with open(canonical_filename, 'rb') as fp0: - events2 = list(ruamel.yaml.canonical_parse(fp0)) + events2 = list(ruamel.yaml.YAML().canonical_parse(fp0)) _compare_events(events1, events2, full=True) finally: if verbose: @@ -138,10 +138,11 @@ def test_composer(data_filename, canonical_filename, verbose=False): nodes1 = None nodes2 = None try: + yaml = ruamel.yaml.YAML() with open(data_filename, 'rb') as fp0: - nodes1 = list(ruamel.yaml.compose_all(fp0)) + nodes1 = list(yaml.compose_all(fp0)) with open(canonical_filename, 'rb') as fp0: - nodes2 = list(ruamel.yaml.canonical_compose_all(fp0)) + nodes2 = list(yaml.canonical_compose_all(fp0)) assert len(nodes1) == len(nodes2), (len(nodes1), len(nodes2)) for node1, node2 in zip(nodes1, nodes2): _compare_nodes(node1, node2) diff --git a/_test/lib/test_yaml_ext.py b/_test/lib/test_yaml_ext.py index 8cba7e5..a6fa287 100644 --- a/_test/lib/test_yaml_ext.py +++ b/_test/lib/test_yaml_ext.py @@ -110,7 +110,7 @@ def new_safe_dump(data, stream=None, **kwds): return old_dump(data, stream, ruamel.yaml.CSafeDumper, **kwds) -old_safe_dump_all = ruamel.yaml.safe_dump_all +# old_safe_dump_all = ruamel.yaml.safe_dump_all def new_safe_dump_all(documents, stream=None, **kwds): @@ -236,10 +236,12 @@ test_c_scanner.skip = ['.skip-ext'] def _compare_parsers(py_data, c_data, verbose): - py_events = list(ruamel.yaml.parse(py_data, Loader=ruamel.yaml.PyLoader)) + yaml = ruamel.yaml.YAML(typ='unsafe', pure=True) + py_events = list(yaml.parse(py_data, Loader=ruamel.yaml.PyLoader)) c_events = [] try: - for event in ruamel.yaml.parse(c_data, Loader=ruamel.yaml.CLoader): + yaml = ruamel.yaml.YAML(typ='unsafe', pure=False) + for event in yaml.parse(c_data, Loader=ruamel.yaml.CLoader): 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): @@ -284,12 +286,13 @@ test_c_parser.skip = ['.skip-ext'] def _compare_emitters(data, verbose): - events = list(ruamel.yaml.parse(data, Loader=ruamel.yaml.PyLoader)) - c_data = ruamel.yaml.emit(events, Dumper=ruamel.yaml.CDumper) + yaml = ruamel.yaml.YAML(typ='unsafe', pure=True) + events = list(yaml.parse(py_data, Loader=ruamel.yaml.PyLoader)) + c_data = yaml.emit(events, Dumper=ruamel.yaml.CDumper) if verbose: print(c_data) - py_events = list(ruamel.yaml.parse(c_data, Loader=ruamel.yaml.PyLoader)) - c_events = list(ruamel.yaml.parse(c_data, Loader=ruamel.yaml.CLoader)) + py_events = list(yaml.parse(c_data, Loader=ruamel.yaml.PyLoader)) + c_events = list(yaml.parse(c_data, Loader=ruamel.yaml.CLoader)) try: assert len(events) == len(py_events), (len(events), len(py_events)) assert len(events) == len(c_events), (len(events), len(c_events)) diff --git a/_test/roundtrip.py b/_test/roundtrip.py index 8b87380..fa8b08a 100644 --- a/_test/roundtrip.py +++ b/_test/roundtrip.py @@ -8,10 +8,12 @@ import textwrap import io from pathlib import Path +from typing import Any, Optional, Union + unset = object() -def dedent(data): +def dedent(data: str) -> str: try: position_of_first_newline = data.index('\n') for idx in range(position_of_first_newline): @@ -24,7 +26,9 @@ def dedent(data): return textwrap.dedent(data) -def round_trip_load(inp, preserve_quotes=None, version=None): +def round_trip_load( + inp: Any, preserve_quotes: Optional[bool] = None, version: Optional[Any] = None +) -> Any: import ruamel.yaml # NOQA dinp = dedent(inp) @@ -34,7 +38,9 @@ def round_trip_load(inp, preserve_quotes=None, version=None): return yaml.load(dinp) -def round_trip_load_all(inp, preserve_quotes=None, version=None): +def round_trip_load_all( + inp: Any, preserve_quotes: Optional[bool] = None, version: Optional[Any] = None +) -> Any: import ruamel.yaml # NOQA dinp = dedent(inp) @@ -45,18 +51,18 @@ def round_trip_load_all(inp, preserve_quotes=None, version=None): def round_trip_dump( - data, - stream=None, # *, - indent=None, - block_seq_indent=None, - default_flow_style=unset, - top_level_colon_align=None, - prefix_colon=None, - explicit_start=None, - explicit_end=None, - version=None, - allow_unicode=True, -): + data: Any, + stream: Any = None, # *, + indent: Optional[int] = None, + block_seq_indent: Optional[int] = None, + default_flow_style: Any = unset, + top_level_colon_align: Any = None, + prefix_colon: Any = None, + explicit_start: Optional[bool] = None, + explicit_end: Optional[bool] = None, + version: Optional[Any] = None, + allow_unicode: bool = True, +) -> Union[str, None]: import ruamel.yaml # NOQA yaml = ruamel.yaml.YAML() @@ -71,25 +77,25 @@ def round_trip_dump( yaml.allow_unicode = allow_unicode if stream is not None: yaml.dump(data, stream=stream) - return + return None buf = io.StringIO() yaml.dump(data, stream=buf) return buf.getvalue() def round_trip_dump_all( - data, - stream=None, # *, - indent=None, - block_seq_indent=None, - default_flow_style=unset, - top_level_colon_align=None, - prefix_colon=None, - explicit_start=None, - explicit_end=None, - version=None, - allow_unicode=None, -): + data: Any, + stream: Any = None, # *, + indent: Optional[int] = None, + block_seq_indent: Optional[int] = None, + default_flow_style: Any = unset, + top_level_colon_align: Any = None, + prefix_colon: Any = None, + explicit_start: Optional[bool] = None, + explicit_end: Optional[bool] = None, + version: Optional[Any] = None, + allow_unicode: bool = True, +) -> Union[str, None]: import ruamel.yaml # NOQA yaml = ruamel.yaml.YAML() @@ -104,13 +110,13 @@ def round_trip_dump_all( yaml.allow_unicode = allow_unicode if stream is not None: yaml.dump(data, stream=stream) - return + return None buf = io.StringIO() yaml.dump_all(data, stream=buf) return buf.getvalue() -def diff(inp, outp, file_name='stdin'): +def diff(inp: str, outp: str, file_name: str = 'stdin') -> None: import difflib inl = inp.splitlines(True) # True for keepends @@ -125,20 +131,21 @@ def diff(inp, outp, file_name='stdin'): 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, - dump_data=None, -): + inp: str, + outp: Optional[str] = None, + extra: Optional[str] = None, + intermediate: Any = None, + indent: Optional[int] = None, + block_seq_indent: Optional[int] = None, + default_flow_style: Any = unset, + top_level_colon_align: Any = None, + prefix_colon: Any = None, + preserve_quotes: Any = None, + explicit_start: Optional[bool] = None, + explicit_end: Optional[bool] = None, + version: Optional[Any] = None, + dump_data: Any = None, +) -> Any: """ inp: input string to parse outp: expected output (equals input if not specified) @@ -167,6 +174,7 @@ def round_trip( explicit_end=explicit_end, version=version, ) + assert isinstance(res, str) if res != doutp: diff(doutp, res, 'input string') print('\nroundtrip data:\n', res, sep="") @@ -187,19 +195,19 @@ def round_trip( def na_round_trip( - inp, - outp=None, - extra=None, - intermediate=None, - indent=None, - top_level_colon_align=None, - prefix_colon=None, - preserve_quotes=None, - explicit_start=None, - explicit_end=None, - version=None, - dump_data=None, -): + inp: str, + outp: Optional[str] = None, + extra: Optional[str] = None, + intermediate: Any = None, + indent: Optional[int] = None, + top_level_colon_align: Any = None, + prefix_colon: Any = None, + preserve_quotes: Any = None, + explicit_start: Optional[bool] = None, + explicit_end: Optional[bool] = None, + version: Optional[Any] = None, + dump_data: Any = None, +) -> Any: """ inp: input string to parse outp: expected output (equals input if not specified) @@ -233,20 +241,20 @@ def na_round_trip( return res -def YAML(**kw): +def YAML(**kw: Any) -> Any: import ruamel.yaml # NOQA class MyYAML(ruamel.yaml.YAML): """auto dedent string parameters on load""" - def load(self, stream): + def load(self, stream: Any) -> Any: if isinstance(stream, str): if stream and stream[0] == '\n': stream = stream[1:] stream = textwrap.dedent(stream) return ruamel.yaml.YAML.load(self, stream) - def load_all(self, stream): + def load_all(self, stream: Any) -> Any: if isinstance(stream, str): if stream and stream[0] == '\n': stream = stream[1:] @@ -254,7 +262,7 @@ def YAML(**kw): for d in ruamel.yaml.YAML.load_all(self, stream): yield d - def dump(self, data, **kw): + def dump(self, data: Any, **kw: Any) -> Any: # type: ignore from ruamel.yaml.compat import StringIO, BytesIO # NOQA assert ('stream' in kw) ^ ('compare' in kw) @@ -270,11 +278,11 @@ def YAML(**kw): res = st.getvalue() print(res) if unordered_lines: - res = sorted(res.splitlines()) - expected = sorted(expected.splitlines()) + res = sorted(res.splitlines()) # type: ignore + expected = sorted(expected.splitlines()) # type: ignore assert res == expected - def round_trip(self, stream, **kw): + def round_trip(self, stream: Any, **kw: Any) -> None: from ruamel.yaml.compat import StringIO, BytesIO # NOQA assert isinstance(stream, str) @@ -291,7 +299,7 @@ def YAML(**kw): diff(outp, res, 'input string') assert res == outp - def round_trip_all(self, stream, **kw): + def round_trip_all(self, stream: Any, **kw: Any) -> None: from ruamel.yaml.compat import StringIO, BytesIO # NOQA assert isinstance(stream, str) @@ -311,7 +319,13 @@ def YAML(**kw): return MyYAML(**kw) -def save_and_run(program, base_dir=None, output=None, file_name=None, optimized=False): +def save_and_run( + program: str, + base_dir: Optional[Any] = None, + output: Optional[Any] = None, + file_name: Optional[Any] = None, + optimized: bool = False, +) -> int: """ safe and run a python program, thereby circumventing any restrictions on module level imports @@ -322,7 +336,7 @@ def save_and_run(program, base_dir=None, output=None, file_name=None, optimized= base_dir = Path(str(base_dir)) if file_name is None: file_name = 'safe_and_run_tmp.py' - file_name = base_dir / file_name + file_name = base_dir / file_name # type: ignore file_name.write_text(dedent(program)) try: @@ -335,9 +349,9 @@ def save_and_run(program, base_dir=None, output=None, file_name=None, optimized= res = check_output(cmd, stderr=STDOUT, universal_newlines=True, cwd=str(base_dir)) if output is not None: if '__pypy__' in sys.builtin_module_names: - res = res.splitlines(True) - res = [line for line in res if 'no version info' not in line] - res = ''.join(res) + res1 = res.splitlines(True) + res2 = [line for line in res1 if 'no version info' not in line] + res = ''.join(res2) print('result: ', res, end='') print('expected:', output, end='') assert res == output diff --git a/_test/test_a_dedent.py b/_test/test_a_dedent.py index 447bdde..e13a54b 100644 --- a/_test/test_a_dedent.py +++ b/_test/test_a_dedent.py @@ -4,7 +4,7 @@ from roundtrip import dedent class TestDedent: - def test_start_newline(self): + def test_start_newline(self) -> None: # fmt: off x = dedent(""" 123 @@ -13,7 +13,7 @@ class TestDedent: # fmt: on assert x == '123\n 456\n' - def test_start_space_newline(self): + def test_start_space_newline(self) -> None: # special construct to prevent stripping of following whitespace # fmt: off x = dedent(" " """ @@ -22,7 +22,7 @@ class TestDedent: # fmt: on assert x == '123\n' - def test_start_no_newline(self): + def test_start_no_newline(self) -> None: # special construct to prevent stripping of following whitespac x = dedent("""\ 123 @@ -30,17 +30,17 @@ class TestDedent: """) assert x == '123\n 456\n' - def test_preserve_no_newline_at_end(self): + def test_preserve_no_newline_at_end(self) -> None: x = dedent(""" 123""") assert x == '123' - def test_preserve_no_newline_at_all(self): + def test_preserve_no_newline_at_all(self) -> None: x = dedent("""\ 123""") assert x == '123' - def test_multiple_dedent(self): + def test_multiple_dedent(self) -> None: x = dedent( dedent(""" 123 diff --git a/_test/test_add_xxx.py b/_test/test_add_xxx.py index 8beac65..5f12ece 100644 --- a/_test/test_add_xxx.py +++ b/_test/test_add_xxx.py @@ -1,31 +1,32 @@ # coding: utf-8 import re -import pytest # NOQA +import pytest # type: ignore # NOQA from roundtrip import dedent, round_trip_dump # NOQA +from typing import Any # from PyYAML docs -class Dice(tuple): - def __new__(cls, a, b): +class Dice(tuple): # type: ignore + def __new__(cls, a: int, b: int) -> "Dice": return tuple.__new__(cls, [a, b]) - def __repr__(self): + def __repr__(self) -> str: return 'Dice(%s,%s)' % self -def dice_constructor(loader, node): +def dice_constructor(loader: Any, node: Any) -> Dice: value = loader.construct_scalar(node) a, b = map(int, value.split('d')) return Dice(a, b) -def dice_representer(dumper, data): +def dice_representer(dumper: Any, data: Any) -> Any: return dumper.represent_scalar('!dice', '{}d{}'.format(*data)) -def test_dice_constructor(): +def test_dice_constructor() -> None: import ruamel.yaml # NOQA yaml = ruamel.yaml.YAML(typ='unsafe', pure=True) @@ -34,7 +35,7 @@ def test_dice_constructor(): assert str(data) == "{'initial hit points': Dice(8,4)}" -def test_dice_constructor_with_loader(): +def test_dice_constructor_with_loader() -> None: import ruamel.yaml # NOQA yaml = ruamel.yaml.YAML(typ='unsafe', pure=True) @@ -43,7 +44,7 @@ def test_dice_constructor_with_loader(): assert str(data) == "{'initial hit points': Dice(8,4)}" -def test_dice_representer(): +def test_dice_representer() -> None: import ruamel.yaml # NOQA yaml = ruamel.yaml.YAML(typ='unsafe', pure=True) @@ -55,7 +56,7 @@ def test_dice_representer(): assert buf.getvalue() == 'gold: !dice 10d6\n' -def test_dice_implicit_resolver(): +def test_dice_implicit_resolver() -> None: import ruamel.yaml # NOQA yaml = ruamel.yaml.YAML(typ='unsafe', pure=True) @@ -68,26 +69,26 @@ def test_dice_implicit_resolver(): assert yaml.load('damage: 5d10') == dict(damage=Dice(5, 10)) -class Obj1(dict): - def __init__(self, suffix): +class Obj1(dict): # type: ignore + def __init__(self, suffix: Any) -> None: self._suffix = suffix self._node = None - def add_node(self, n): + def add_node(self, n: Any) -> None: self._node = n - def __repr__(self): + def __repr__(self) -> str: return 'Obj1(%s->%s)' % (self._suffix, self.items()) - def dump(self): + def dump(self) -> str: return repr(self._node) -class YAMLObj1(object): +class YAMLObj1: yaml_tag = '!obj:' @classmethod - def from_yaml(cls, loader, suffix, node): + def from_yaml(cls, loader: Any, suffix: Any, node: Any) -> Any: import ruamel.yaml # NOQA obj1 = Obj1(suffix) @@ -98,11 +99,11 @@ class YAMLObj1(object): return obj1 @classmethod - def to_yaml(cls, dumper, data): + def to_yaml(cls, dumper: Any, data: Any) -> Any: return dumper.represent_scalar(cls.yaml_tag + data._suffix, data.dump()) -def test_yaml_obj(): +def test_yaml_obj() -> None: import ruamel.yaml # NOQA yaml = ruamel.yaml.YAML(typ='unsafe', pure=True) @@ -115,7 +116,7 @@ def test_yaml_obj(): assert buf.getvalue() == """!obj:x.2 "{'a': 1}"\n""" -def test_yaml_obj_with_loader_and_dumper(): +def test_yaml_obj_with_loader_and_dumper() -> None: import ruamel.yaml # NOQA yaml = ruamel.yaml.YAML(typ='unsafe', pure=True) @@ -137,25 +138,25 @@ def test_yaml_obj_with_loader_and_dumper(): # Issue 127 reported by Tommy Wang -def test_issue_127(): +def test_issue_127() -> None: import ruamel.yaml # NOQA class Ref(ruamel.yaml.YAMLObject): - yaml_constructor = ruamel.yaml.RoundTripConstructor - yaml_representer = ruamel.yaml.RoundTripRepresenter + yaml_constructor = ruamel.yaml.RoundTripConstructor # type: ignore + yaml_representer = ruamel.yaml.RoundTripRepresenter # type: ignore yaml_tag = '!Ref' - def __init__(self, logical_id): + def __init__(self, logical_id: Any) -> None: self.logical_id = logical_id @classmethod - def from_yaml(cls, loader, node): + def from_yaml(cls, loader: Any, node: Any) -> Any: return cls(loader.construct_scalar(node)) @classmethod - def to_yaml(cls, dumper, data): + def to_yaml(cls, dumper: Any, data: Any) -> Any: if isinstance(data.logical_id, ruamel.yaml.scalarstring.ScalarString): - style = data.logical_id.style # ruamel.yaml>0.15.8 + style = data.logical_id.style # type: ignore # ruamel.yaml>0.15.8 else: style = None return dumper.represent_scalar(cls.yaml_tag, data.logical_id, style=style) diff --git a/_test/test_anchor.py b/_test/test_anchor.py index 3c83886..da0f1ef 100644 --- a/_test/test_anchor.py +++ b/_test/test_anchor.py @@ -4,26 +4,26 @@ testing of anchors and the aliases referring to them """ -import pytest -from textwrap import dedent +import pytest # type: ignore # NOQA import platform from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump, YAML # NOQA +from typing import Any -def load(s): +def load(s: str) -> Any: return round_trip_load(dedent(s)) -def compare(d, s): +def compare(d: Any, s: str) -> None: assert round_trip_dump(d) == dedent(s) class TestAnchorsAliases: - def test_anchor_id_renumber(self): + def test_anchor_id_renumber(self) -> None: from ruamel.yaml.serializer import Serializer - assert Serializer.ANCHOR_TEMPLATE == 'id%03d' + assert Serializer.ANCHOR_TEMPLATE == 'id{:03d}' data = load(""" a: &id002 b: 1 @@ -40,7 +40,7 @@ class TestAnchorsAliases: """, ) - def test_template_matcher(self): + def test_template_matcher(self) -> None: """test if id matches the anchor template""" from ruamel.yaml.serializer import templated_id @@ -53,13 +53,13 @@ class TestAnchorsAliases: assert not templated_id('id000') assert not templated_id('x000') - # def test_re_matcher(self): + # def test_re_matcher(self) -> None: # import re # assert re.compile('id(?!000)\\d{3,}').match('id001') # assert not re.compile('id(?!000\\d*)\\d{3,}').match('id000') # assert re.compile('id(?!000$)\\d{3,}').match('id0001') - def test_anchor_assigned(self): + def test_anchor_assigned(self) -> None: from ruamel.yaml.comments import CommentedMap data = load(""" @@ -80,7 +80,7 @@ class TestAnchorsAliases: assert e.yaml_anchor().value == 'etemplate' assert e.yaml_anchor().always_dump is False - def test_anchor_id_retained(self): + def test_anchor_id_retained(self) -> None: data = load(""" a: &id002 b: 1 @@ -105,10 +105,10 @@ class TestAnchorsAliases: """, ) - @pytest.mark.skipif( + @pytest.mark.skipif( # type: ignore platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' ) - def test_alias_before_anchor(self): + def test_alias_before_anchor(self) -> None: from ruamel.yaml.composer import ComposerError with pytest.raises(ComposerError): @@ -120,7 +120,7 @@ class TestAnchorsAliases: """) data = data - def test_anchor_on_sequence(self): + def test_anchor_on_sequence(self) -> None: # as reported by Bjorn Stabell # https://bitbucket.org/ruamel/yaml/issue/7/anchor-names-not-preserved from ruamel.yaml.comments import CommentedSeq @@ -165,7 +165,7 @@ class TestAnchorsAliases: label: center/huge """) - def test_merge_00(self): + def test_merge_00(self) -> None: data = load(self.merge_yaml) d = data[4] ok = True @@ -181,7 +181,7 @@ class TestAnchorsAliases: print('key', k, d.get(k), data[o].get(k)) assert ok - def test_merge_accessible(self): + def test_merge_accessible(self) -> None: from ruamel.yaml.comments import CommentedMap, merge_attrib data = load(""" @@ -196,11 +196,11 @@ class TestAnchorsAliases: assert isinstance(d, CommentedMap) assert hasattr(d, merge_attrib) - def test_merge_01(self): + def test_merge_01(self) -> None: data = load(self.merge_yaml) compare(data, self.merge_yaml) - def test_merge_nested(self): + def test_merge_nested(self) -> None: yaml = """ a: <<: &content @@ -212,7 +212,7 @@ class TestAnchorsAliases: """ data = round_trip(yaml) # NOQA - def test_merge_nested_with_sequence(self): + def test_merge_nested_with_sequence(self) -> None: yaml = """ a: <<: &content @@ -225,7 +225,7 @@ class TestAnchorsAliases: """ data = round_trip(yaml) # NOQA - def test_add_anchor(self): + def test_add_anchor(self) -> None: from ruamel.yaml.comments import CommentedMap data = CommentedMap() @@ -246,7 +246,7 @@ class TestAnchorsAliases: ) # this is an error in PyYAML - def test_reused_anchor(self): + def test_reused_anchor(self) -> None: from ruamel.yaml.error import ReusedAnchorWarning yaml = """ @@ -260,7 +260,7 @@ class TestAnchorsAliases: with pytest.warns(ReusedAnchorWarning): data = round_trip(yaml) # NOQA - def test_issue_130(self): + def test_issue_130(self) -> None: # issue 130 reported by Devid Fee import ruamel.yaml @@ -285,7 +285,7 @@ class TestAnchorsAliases: data = yaml.load(ys) assert data['services']['shell']['components']['server']['port'] == 8000 - def test_issue_130a(self): + def test_issue_130a(self) -> None: # issue 130 reported by Devid Fee import ruamel.yaml @@ -331,8 +331,8 @@ class TestMergeKeysValues: # in the following d always has "expanded" the merges - def test_merge_for(self): - from ruamel.yaml import YAML + def test_merge_for(self) -> None: + from ruamel.yaml import YAML # type: ignore d = YAML(typ='safe', pure=True).load(self.yaml_str) data = round_trip_load(self.yaml_str) @@ -342,8 +342,8 @@ class TestMergeKeysValues: print(count, x) assert count == len(d[2]) - def test_merge_keys(self): - from ruamel.yaml import YAML + def test_merge_keys(self) -> None: + from ruamel.yaml import YAML # type: ignore d = YAML(typ='safe', pure=True).load(self.yaml_str) data = round_trip_load(self.yaml_str) @@ -353,8 +353,8 @@ class TestMergeKeysValues: print(count, x) assert count == len(d[2]) - def test_merge_values(self): - from ruamel.yaml import YAML + def test_merge_values(self) -> None: + from ruamel.yaml import YAML # type: ignore d = YAML(typ='safe', pure=True).load(self.yaml_str) data = round_trip_load(self.yaml_str) @@ -364,8 +364,8 @@ class TestMergeKeysValues: print(count, x) assert count == len(d[2]) - def test_merge_items(self): - from ruamel.yaml import YAML + def test_merge_items(self) -> None: + from ruamel.yaml import YAML # type: ignore d = YAML(typ='safe', pure=True).load(self.yaml_str) data = round_trip_load(self.yaml_str) @@ -375,8 +375,8 @@ class TestMergeKeysValues: print(count, x) assert count == len(d[2]) - def test_len_items_delete(self): - from ruamel.yaml import YAML + def test_len_items_delete(self) -> None: + from ruamel.yaml import YAML # type: ignore d = YAML(typ='safe', pure=True).load(self.yaml_str) data = round_trip_load(self.yaml_str) @@ -395,8 +395,8 @@ class TestMergeKeysValues: ref -= 1 assert len(x) == ref - def test_issue_196_cast_of_dict(self, capsys): - from ruamel.yaml import YAML + def test_issue_196_cast_of_dict(self, capsys: Any) -> None: + from ruamel.yaml import YAML # type: ignore yaml = YAML() mapping = yaml.load("""\ @@ -433,15 +433,15 @@ class TestMergeKeysValues: assert 'a' in dict(mapping) assert 'a' in dict(mapping.items()) - def test_values_of_merged(self): - from ruamel.yaml import YAML + def test_values_of_merged(self) -> None: + from ruamel.yaml import YAML # type: ignore yaml = YAML() data = yaml.load(dedent(self.yaml_str)) assert list(data[2].values()) == [1, 6, 'x2', 'x3', 'y4'] - def test_issue_213_copy_of_merge(self): - from ruamel.yaml import YAML + def test_issue_213_copy_of_merge(self) -> None: + from ruamel.yaml import YAML # type: ignore yaml = YAML() d = yaml.load("""\ @@ -461,9 +461,9 @@ class TestMergeKeysValues: class TestDuplicateKeyThroughAnchor: - def test_duplicate_key_00(self): + def test_duplicate_key_00(self) -> None: from ruamel.yaml import version_info - from ruamel.yaml import YAML + from ruamel.yaml import YAML # type: ignore from ruamel.yaml.constructor import DuplicateKeyFutureWarning, DuplicateKeyError s = dedent("""\ @@ -486,7 +486,7 @@ class TestDuplicateKeyThroughAnchor: with pytest.raises(DuplicateKeyError): YAML(typ='rt').load(s) - def test_duplicate_key_01(self): + def test_duplicate_key_01(self) -> None: # so issue https://stackoverflow.com/a/52852106/1307905 from ruamel.yaml import version_info from ruamel.yaml.constructor import DuplicateKeyError @@ -511,7 +511,7 @@ class TestDuplicateKeyThroughAnchor: class TestFullCharSetAnchors: - def test_master_of_orion(self): + def test_master_of_orion(self) -> None: # https://bitbucket.org/ruamel/yaml/issues/72/not-allowed-in-anchor-names # submitted by Shalon Wood yaml_str = """ @@ -522,7 +522,7 @@ class TestFullCharSetAnchors: """ data = load(yaml_str) # NOQA - def test_roundtrip_00(self): + def test_roundtrip_00(self) -> None: yaml_str = """ - &dotted.words.here a: 1 @@ -531,7 +531,7 @@ class TestFullCharSetAnchors: """ data = round_trip(yaml_str) # NOQA - def test_roundtrip_01(self): + def test_roundtrip_01(self) -> None: yaml_str = """ - &dotted.words.here[a, b] - *dotted.words.here diff --git a/_test/test_api_change.py b/_test/test_api_change.py index 22250b8..8961273 100644 --- a/_test/test_api_change.py +++ b/_test/test_api_change.py @@ -6,12 +6,14 @@ testing of anchors and the aliases referring to them import sys import textwrap -import pytest +import pytest # type: ignore from pathlib import Path +from typing import Any + class TestNewAPI: - def test_duplicate_keys_00(self): + def test_duplicate_keys_00(self) -> None: from ruamel.yaml import YAML from ruamel.yaml.constructor import DuplicateKeyError @@ -19,7 +21,7 @@ class TestNewAPI: with pytest.raises(DuplicateKeyError): yaml.load('{a: 1, a: 2}') - def test_duplicate_keys_01(self): + def test_duplicate_keys_01(self) -> None: from ruamel.yaml import YAML from ruamel.yaml.constructor import DuplicateKeyError @@ -27,7 +29,7 @@ class TestNewAPI: with pytest.raises(DuplicateKeyError): yaml.load('{a: 1, a: 2}') - def test_duplicate_keys_02(self): + def test_duplicate_keys_02(self) -> None: from ruamel.yaml import YAML from ruamel.yaml.constructor import DuplicateKeyError @@ -35,7 +37,7 @@ class TestNewAPI: with pytest.raises(DuplicateKeyError): yaml.load('{a: 1, a: 2}') - def test_issue_135(self): + def test_issue_135(self) -> None: # reported by Andrzej Ostrowski from ruamel.yaml import YAML @@ -44,7 +46,7 @@ class TestNewAPI: # originally on 2.7: with pytest.raises(TypeError): yaml.dump(data, sys.stdout) - def test_issue_135_temporary_workaround(self): + def test_issue_135_temporary_workaround(self) -> None: # never raised error from ruamel.yaml import YAML @@ -54,7 +56,7 @@ class TestNewAPI: class TestWrite: - def test_dump_path(self, tmpdir): + def test_dump_path(self, tmpdir: Any) -> None: from ruamel.yaml import YAML fn = Path(str(tmpdir)) / 'test.yaml' @@ -65,7 +67,7 @@ class TestWrite: yaml.dump(data, fn) assert fn.read_text() == 'a: 1\nb: 2\n' - def test_dump_file(self, tmpdir): + def test_dump_file(self, tmpdir: Any) -> None: from ruamel.yaml import YAML fn = Path(str(tmpdir)) / 'test.yaml' @@ -77,7 +79,7 @@ class TestWrite: yaml.dump(data, fp) assert fn.read_text() == 'a: 1\nb: 2\n' - def test_dump_missing_stream(self): + def test_dump_missing_stream(self) -> None: from ruamel.yaml import YAML yaml = YAML() @@ -87,7 +89,7 @@ class TestWrite: with pytest.raises(TypeError): yaml.dump(data) - def test_dump_too_many_args(self, tmpdir): + def test_dump_too_many_args(self, tmpdir: Any) -> None: from ruamel.yaml import YAML fn = Path(str(tmpdir)) / 'test.yaml' @@ -96,12 +98,12 @@ class TestWrite: data['a'] = 1 data['b'] = 2 with pytest.raises(TypeError): - yaml.dump(data, fn, True) + yaml.dump(data, fn, True) # type: ignore - def test_transform(self, tmpdir): + def test_transform(self, tmpdir: Any) -> None: from ruamel.yaml import YAML - def tr(s): + def tr(s: str) -> str: return s.replace(' ', ' ') fn = Path(str(tmpdir)) / 'test.yaml' @@ -112,7 +114,7 @@ class TestWrite: yaml.dump(data, fn, transform=tr) assert fn.read_text() == 'a: 1\nb: 2\n' - def test_print(self, capsys): + def test_print(self, capsys: Any) -> None: from ruamel.yaml import YAML yaml = YAML() @@ -125,7 +127,7 @@ class TestWrite: class TestRead: - def test_multi_load(self): + def test_multi_load(self) -> None: # make sure reader, scanner, parser get reset from ruamel.yaml import YAML @@ -133,7 +135,7 @@ class TestRead: yaml.load('a: 1') yaml.load('a: 1') # did not work in 0.15.4 - def test_parse(self): + def test_parse(self) -> None: # ensure `parse` method is functional and can parse "unsafe" yaml from ruamel.yaml import YAML from ruamel.yaml.constructor import ConstructorError @@ -150,7 +152,7 @@ class TestRead: class TestLoadAll: - def test_multi_document_load(self, tmpdir): + def test_multi_document_load(self, tmpdir: Any) -> None: """this went wrong on 3.7 because of StopIteration, PR 37 and Issue 211""" from ruamel.yaml import YAML @@ -169,7 +171,7 @@ class TestLoadAll: class TestDuplSet: - def test_dupl_set_00(self): + def test_dupl_set_00(self) -> None: # round-trip-loader should except from ruamel.yaml import YAML from ruamel.yaml.constructor import DuplicateKeyError @@ -190,7 +192,7 @@ class TestDuplSet: class TestDumpLoadUnicode: # test triggered by SamH on stackoverflow (https://stackoverflow.com/q/45281596/1307905) # and answer by randomir (https://stackoverflow.com/a/45281922/1307905) - def test_write_unicode(self, tmpdir): + def test_write_unicode(self, tmpdir: Any) -> None: from ruamel.yaml import YAML yaml = YAML() @@ -199,7 +201,7 @@ class TestDumpLoadUnicode: yaml.dump(text_dict, open(file_name, 'w')) assert open(file_name, 'rb').read().decode('utf-8') == 'text: HELLO_WORLD©\n' - def test_read_unicode(self, tmpdir): + def test_read_unicode(self, tmpdir: Any) -> None: from ruamel.yaml import YAML yaml = YAML() @@ -211,7 +213,7 @@ class TestDumpLoadUnicode: class TestFlowStyle: - def test_flow_style(self, capsys): + def test_flow_style(self, capsys: Any) -> None: # https://stackoverflow.com/questions/45791712/ from ruamel.yaml import YAML @@ -226,8 +228,8 @@ class TestFlowStyle: class TestOldAPI: - @pytest.mark.skipif(sys.version_info >= (3, 0), reason='ok on Py3') - def test_duplicate_keys_02(self): + @pytest.mark.skipif(sys.version_info >= (3, 0), reason='ok on Py3') # type: ignore + def test_duplicate_keys_02(self) -> None: # Issue 165 unicode keys in error/warning from ruamel.yaml import safe_load from ruamel.yaml.constructor import DuplicateKeyError diff --git a/_test/test_class_register.py b/_test/test_class_register.py index d996269..fdd0275 100644 --- a/_test/test_class_register.py +++ b/_test/test_class_register.py @@ -4,33 +4,36 @@ testing of YAML.register_class and @yaml_object """ +from typing import Any +from ruamel.yaml.comments import TaggedScalar, CommentedMap # NOQA + from roundtrip import YAML -class User0(object): - def __init__(self, name, age): +class User0: + def __init__(self, name: str, age: int) -> None: self.name = name self.age = age -class User1(object): +class User1: yaml_tag = '!user' - def __init__(self, name, age): + def __init__(self, name: str, age: int) -> None: self.name = name self.age = age @classmethod - def to_yaml(cls, representer, node): + def to_yaml(cls, representer: Any, node: Any) -> Any: return representer.represent_scalar(cls.yaml_tag, '{.name}-{.age}'.format(node, node)) @classmethod - def from_yaml(cls, constructor, node): + def from_yaml(cls, constructor: Any, node: Any) -> Any: return cls(*node.value.split('-')) -class TestRegisterClass(object): - def test_register_0_rt(self): +class TestRegisterClass: + def test_register_0_rt(self) -> None: yaml = YAML() yaml.register_class(User0) ys = """ @@ -41,7 +44,7 @@ class TestRegisterClass(object): d = yaml.load(ys) yaml.dump(d, compare=ys, unordered_lines=True) - def test_register_0_safe(self): + def test_register_0_safe(self) -> None: # default_flow_style = None yaml = YAML(typ='safe') yaml.register_class(User0) @@ -51,7 +54,7 @@ class TestRegisterClass(object): d = yaml.load(ys) yaml.dump(d, compare=ys) - def test_register_0_unsafe(self): + def test_register_0_unsafe(self) -> None: # default_flow_style = None yaml = YAML(typ='unsafe') yaml.register_class(User0) @@ -61,7 +64,7 @@ class TestRegisterClass(object): d = yaml.load(ys) yaml.dump(d, compare=ys) - def test_register_1_rt(self): + def test_register_1_rt(self) -> None: yaml = YAML() yaml.register_class(User1) ys = """ @@ -70,7 +73,7 @@ class TestRegisterClass(object): d = yaml.load(ys) yaml.dump(d, compare=ys) - def test_register_1_safe(self): + def test_register_1_safe(self) -> None: yaml = YAML(typ='safe') yaml.register_class(User1) ys = """ @@ -79,7 +82,7 @@ class TestRegisterClass(object): d = yaml.load(ys) yaml.dump(d, compare=ys) - def test_register_1_unsafe(self): + def test_register_1_unsafe(self) -> None: yaml = YAML(typ='unsafe') yaml.register_class(User1) ys = """ @@ -89,15 +92,15 @@ class TestRegisterClass(object): yaml.dump(d, compare=ys) -class TestDecorator(object): - def test_decorator_implicit(self): +class TestDecorator: + def test_decorator_implicit(self) -> None: from ruamel.yaml import yaml_object yml = YAML() @yaml_object(yml) - class User2(object): - def __init__(self, name, age): + class User2: + def __init__(self, name: str, age: int) -> None: self.name = name self.age = age @@ -109,27 +112,27 @@ class TestDecorator(object): d = yml.load(ys) yml.dump(d, compare=ys, unordered_lines=True) - def test_decorator_explicit(self): + def test_decorator_explicit(self) -> None: from ruamel.yaml import yaml_object yml = YAML() @yaml_object(yml) - class User3(object): + class User3: yaml_tag = '!USER' - def __init__(self, name, age): + def __init__(self, name: str, age: int) -> None: self.name = name self.age = age @classmethod - def to_yaml(cls, representer, node): + def to_yaml(cls, representer: Any, node: Any) -> Any: return representer.represent_scalar( cls.yaml_tag, '{.name}-{.age}'.format(node, node) ) @classmethod - def from_yaml(cls, constructor, node): + def from_yaml(cls, constructor: Any, node: Any) -> Any: return cls(*node.value.split('-')) ys = """ diff --git a/_test/test_collections.py b/_test/test_collections.py index 40af9db..d6e88ef 100644 --- a/_test/test_collections.py +++ b/_test/test_collections.py @@ -7,14 +7,14 @@ This is now so integrated in Python that it can be mapped to !!omap """ -import pytest # NOQA +import pytest # type: ignore # NOQA from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NOQA class TestOrderedDict: - def test_ordereddict(self): + def test_ordereddict(self) -> None: from collections import OrderedDict assert round_trip_dump(OrderedDict()) == '!!omap []\n' diff --git a/_test/test_comment_manipulation.py b/_test/test_comment_manipulation.py index 6d706f2..979b386 100644 --- a/_test/test_comment_manipulation.py +++ b/_test/test_comment_manipulation.py @@ -1,28 +1,29 @@ # coding: utf-8 -import pytest # NOQA +import pytest # type: ignore # NOQA from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NOQA +from typing import Any -def load(s): +def load(s: str) -> Any: return round_trip_load(dedent(s)) -def compare(data, s, **kw): +def compare(data: Any, s: str, **kw: Any) -> None: assert round_trip_dump(data, **kw) == dedent(s) -def compare_eol(data, s): +def compare_eol(data: Any, s: str) -> None: assert 'EOL' in s ds = dedent(s).replace('EOL', '').replace('\n', '|\n') - assert round_trip_dump(data).replace('\n', '|\n') == ds + assert round_trip_dump(data).replace('\n', '|\n') == ds # type: ignore class TestCommentsManipulation: # list - def test_seq_set_comment_on_existing_explicit_column(self): + def test_seq_set_comment_on_existing_explicit_column(self) -> None: data = load(""" - a # comment 1 - b @@ -36,7 +37,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def test_seq_overwrite_comment_on_existing_explicit_column(self): + def test_seq_overwrite_comment_on_existing_explicit_column(self) -> None: data = load(""" - a # comment 1 - b @@ -50,7 +51,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def test_seq_first_comment_explicit_column(self): + def test_seq_first_comment_explicit_column(self) -> None: data = load(""" - a - b @@ -64,7 +65,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def test_seq_set_comment_on_existing_column_prev(self): + def test_seq_set_comment_on_existing_column_prev(self) -> None: data = load(""" - a # comment 1 - b @@ -80,14 +81,14 @@ class TestCommentsManipulation: """ compare(data, exp) - def test_seq_set_comment_on_existing_column_next(self): + def test_seq_set_comment_on_existing_column_next(self) -> None: data = load(""" - a # comment 1 - b - c - d # comment 3 """) - print(data._yaml_comment) + print(data.ca) # print(type(data._yaml_comment._items[0][0].start_mark)) # ruamel.yaml.error.Mark # print(type(data._yaml_comment._items[0][0].start_mark)) @@ -100,7 +101,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def test_seq_set_comment_on_existing_column_further_away(self): + def test_seq_set_comment_on_existing_column_further_away(self) -> None: """ no comment line before or after, take the latest before the new position @@ -113,7 +114,7 @@ class TestCommentsManipulation: - e - f # comment 3 """) - print(data._yaml_comment) + print(data.ca) # print(type(data._yaml_comment._items[0][0].start_mark)) # ruamel.yaml.error.Mark # print(type(data._yaml_comment._items[0][0].start_mark)) @@ -128,7 +129,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def test_seq_set_comment_on_existing_explicit_column_with_hash(self): + def test_seq_set_comment_on_existing_explicit_column_with_hash(self) -> None: data = load(""" - a # comment 1 - b @@ -144,7 +145,7 @@ class TestCommentsManipulation: # dict - def test_dict_set_comment_on_existing_explicit_column(self): + def test_dict_set_comment_on_existing_explicit_column(self) -> None: data = load(""" a: 1 # comment 1 b: 2 @@ -162,7 +163,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def test_dict_overwrite_comment_on_existing_explicit_column(self): + def test_dict_overwrite_comment_on_existing_explicit_column(self) -> None: data = load(""" a: 1 # comment 1 b: 2 @@ -180,7 +181,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def test_map_set_comment_on_existing_column_prev(self): + def test_map_set_comment_on_existing_column_prev(self) -> None: data = load(""" a: 1 # comment 1 b: 2 @@ -198,7 +199,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def test_map_set_comment_on_existing_column_next(self): + def test_map_set_comment_on_existing_column_next(self) -> None: data = load(""" a: 1 # comment 1 b: 2 @@ -216,7 +217,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def test_map_set_comment_on_existing_column_further_away(self): + def test_map_set_comment_on_existing_column_further_away(self) -> None: """ no comment line before or after, take the latest before the new position @@ -239,7 +240,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def test_before_top_map_rt(self): + def test_before_top_map_rt(self) -> None: data = load(""" a: 1 b: 2 @@ -253,7 +254,7 @@ class TestCommentsManipulation: """ compare(data, exp.format(comment='#')) - def test_before_top_map_replace(self): + def test_before_top_map_replace(self) -> None: data = load(""" # abc # def @@ -269,7 +270,7 @@ class TestCommentsManipulation: """ compare(data, exp.format(comment='#')) - def test_before_top_map_from_scratch(self): + def test_before_top_map_from_scratch(self) -> None: from ruamel.yaml.comments import CommentedMap data = CommentedMap() @@ -286,7 +287,7 @@ class TestCommentsManipulation: """ compare(data, exp.format(comment='#')) - def test_before_top_seq_rt(self): + def test_before_top_seq_rt(self) -> None: data = load(""" - a - b @@ -301,7 +302,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def test_before_top_seq_rt_replace(self): + def test_before_top_seq_rt_replace(self) -> None: s = """ # this # that @@ -319,7 +320,7 @@ class TestCommentsManipulation: """ compare(data, exp.format(comment='#')) - def test_before_top_seq_from_scratch(self): + def test_before_top_seq_from_scratch(self) -> None: from ruamel.yaml.comments import CommentedSeq data = CommentedSeq() @@ -336,7 +337,7 @@ class TestCommentsManipulation: compare(data, exp.format(comment='#')) # nested variants - def test_before_nested_map_rt(self): + def test_before_nested_map_rt(self) -> None: data = load(""" a: 1 b: @@ -354,7 +355,7 @@ class TestCommentsManipulation: """ compare(data, exp.format(comment='#')) - def test_before_nested_map_rt_indent(self): + def test_before_nested_map_rt_indent(self) -> None: data = load(""" a: 1 b: @@ -373,7 +374,7 @@ class TestCommentsManipulation: compare(data, exp.format(comment='#')) print(data['b'].ca) - def test_before_nested_map_from_scratch(self): + def test_before_nested_map_from_scratch(self) -> None: from ruamel.yaml.comments import CommentedMap data = CommentedMap() @@ -393,7 +394,7 @@ class TestCommentsManipulation: """ compare(data, exp.format(comment='#')) - def test_before_nested_seq_from_scratch(self): + def test_before_nested_seq_from_scratch(self) -> None: from ruamel.yaml.comments import CommentedMap, CommentedSeq data = CommentedMap() @@ -413,7 +414,7 @@ class TestCommentsManipulation: """ compare(data, exp.format(comment='#')) - def test_before_nested_seq_from_scratch_block_seq_indent(self): + def test_before_nested_seq_from_scratch_block_seq_indent(self) -> None: from ruamel.yaml.comments import CommentedMap, CommentedSeq data = CommentedMap() @@ -433,7 +434,7 @@ class TestCommentsManipulation: """ compare(data, exp.format(comment='#'), indent=4, block_seq_indent=2) - def test_map_set_comment_before_and_after_non_first_key_00(self): + def test_map_set_comment_before_and_after_non_first_key_00(self) -> None: # http://stackoverflow.com/a/40705671/1307905 data = load(""" xyz: @@ -462,7 +463,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def Xtest_map_set_comment_before_and_after_non_first_key_01(self): + def Xtest_map_set_comment_before_and_after_non_first_key_01(self) -> None: data = load(""" xyz: a: 1 # comment 1 @@ -494,7 +495,7 @@ class TestCommentsManipulation: # EOL is no longer necessary # fixed together with issue # 216 - def test_map_set_comment_before_and_after_non_first_key_01(self): + def test_map_set_comment_before_and_after_non_first_key_01(self) -> None: data = load(""" xyz: a: 1 # comment 1 @@ -523,7 +524,7 @@ class TestCommentsManipulation: """ compare(data, exp) - def Xtest_map_set_comment_before_and_after_non_first_key_02(self): + def Xtest_map_set_comment_before_and_after_non_first_key_02(self) -> None: data = load(""" xyz: a: 1 # comment 1 @@ -555,7 +556,7 @@ class TestCommentsManipulation: """ compare_eol(data, exp) - def test_map_set_comment_before_and_after_non_first_key_02(self): + def test_map_set_comment_before_and_after_non_first_key_02(self) -> None: data = load(""" xyz: a: 1 # comment 1 diff --git a/_test/test_comments.py b/_test/test_comments.py index dbf035d..64b8cd2 100644 --- a/_test/test_comments.py +++ b/_test/test_comments.py @@ -10,14 +10,14 @@ roundtrip changes """ -import pytest +import pytest # type: ignore # NOQA import sys from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump class TestComments: - def test_no_end_of_file_eol(self): + def test_no_end_of_file_eol(self) -> None: """not excluding comments caused some problems if at the end of the file without a newline. First error, then included \0 """ x = """\ @@ -26,7 +26,7 @@ class TestComments: with pytest.raises(AssertionError): round_trip(x, extra='a\n') - def test_no_comments(self): + def test_no_comments(self) -> None: round_trip(""" - europe: 10 - usa: @@ -34,7 +34,7 @@ class TestComments: - california: 9 """) - def test_round_trip_ordering(self): + def test_round_trip_ordering(self) -> None: round_trip(""" a: 1 b: 2 @@ -46,7 +46,7 @@ class TestComments: f: 6 """) - def test_complex(self): + def test_complex(self) -> None: round_trip(""" - europe: 10 # top - usa: @@ -54,7 +54,7 @@ class TestComments: - california: 9 # o """) - def test_dropped(self): + def test_dropped(self) -> None: s = """\ # comment scalar @@ -62,7 +62,7 @@ class TestComments: """ round_trip(s, 'scalar\n...\n') - def test_main_mapping_begin_end(self): + def test_main_mapping_begin_end(self) -> None: round_trip(""" # C start a # C start b @@ -73,7 +73,7 @@ class TestComments: # C end b """) - def test_reindent(self): + def test_reindent(self) -> None: x = """\ a: b: # comment 1 @@ -87,7 +87,7 @@ class TestComments: c: 1 # comment 2 """) - def test_main_mapping_begin_end_items_post(self): + def test_main_mapping_begin_end_items_post(self) -> None: round_trip(""" # C start a # C start b @@ -98,7 +98,7 @@ class TestComments: # C end b """) - def test_main_sequence_begin_end(self): + def test_main_sequence_begin_end(self) -> None: round_trip(""" # C start a # C start b @@ -109,7 +109,7 @@ class TestComments: # C end b """) - def test_main_sequence_begin_end_items_post(self): + def test_main_sequence_begin_end_items_post(self) -> None: round_trip(""" # C start a # C start b @@ -120,7 +120,7 @@ class TestComments: # C end b """) - def test_main_mapping_begin_end_complex(self): + def test_main_mapping_begin_end_complex(self) -> None: round_trip(""" # C start a # C start b @@ -133,7 +133,7 @@ class TestComments: # C end b """) - def test_09(self): # 2.9 from the examples in the spec + def test_09(self) -> None: # 2.9 from the examples in the spec s = """\ hr: # 1998 hr ranking - Mark McGwire @@ -145,7 +145,7 @@ class TestComments: """ round_trip(s, indent=4, block_seq_indent=2) - def test_09a(self): + def test_09a(self) -> None: round_trip(""" hr: # 1998 hr ranking - Mark McGwire @@ -156,7 +156,7 @@ class TestComments: - Ken Griffey """) - def test_simple_map_middle_comment(self): + def test_simple_map_middle_comment(self) -> None: round_trip(""" abc: 1 # C 3a @@ -164,7 +164,7 @@ class TestComments: ghi: 2 """) - def test_map_in_map_0(self): + def test_map_in_map_0(self) -> None: round_trip(""" map1: # comment 1 # comment 2 @@ -172,7 +172,7 @@ class TestComments: key1: val1 """) - def test_map_in_map_1(self): + def test_map_in_map_1(self) -> None: # comment is moved from value to key round_trip(""" map1: @@ -181,7 +181,7 @@ class TestComments: key1: val1 """) - def test_application_arguments(self): + def test_application_arguments(self) -> None: # application configur round_trip(""" args: @@ -194,7 +194,7 @@ class TestComments: wait: 10 """) - def test_substitute(self): + def test_substitute(self) -> None: x = """ args: username: anthon # name @@ -211,7 +211,7 @@ class TestComments: x = x.replace(': secret ', ': deleted password') assert round_trip_dump(data) == dedent(x) - def test_set_comment(self): + def test_set_comment(self) -> None: round_trip(""" !!set # the beginning @@ -222,7 +222,7 @@ class TestComments: # this is the end """) - def test_omap_comment_roundtrip(self): + def test_omap_comment_roundtrip(self) -> None: round_trip(""" !!omap - a: 1 @@ -231,7 +231,7 @@ class TestComments: - d: 4 """) - def test_omap_comment_roundtrip_pre_comment(self): + def test_omap_comment_roundtrip_pre_comment(self) -> None: round_trip(""" !!omap - a: 1 @@ -241,7 +241,7 @@ class TestComments: - d: 4 """) - def test_non_ascii(self): + def test_non_ascii(self) -> None: round_trip(""" verbosity: 1 # 0 is minimal output, -1 none base_url: http://gopher.net @@ -263,7 +263,7 @@ class TestComments: Italy: Rome """) - def test_dump_utf8(self): + def test_dump_utf8(self) -> None: import ruamel.yaml # NOQA x = dedent("""\ @@ -278,7 +278,7 @@ class TestComments: ) assert y == x - def test_dump_unicode_utf8(self): + def test_dump_unicode_utf8(self) -> None: import ruamel.yaml # NOQA x = dedent("""\ @@ -293,7 +293,7 @@ class TestComments: ) assert y == x - def test_mlget_00(self): + def test_mlget_00(self) -> None: x = """\ a: - b: @@ -314,7 +314,7 @@ class TestInsertPopList: need to move the values to subsequent keys on insert""" @property - def ins(self): + def ins(self) -> str: return """\ ab: - a # a @@ -327,7 +327,7 @@ class TestInsertPopList: - 2 """ - def test_insert_0(self): + def test_insert_0(self) -> None: d = round_trip_load(self.ins) d['ab'].insert(0, 'xyz') y = round_trip_dump(d, indent=2) @@ -344,7 +344,7 @@ class TestInsertPopList: - 2 """) - def test_insert_1(self): + def test_insert_1(self) -> None: d = round_trip_load(self.ins) d['ab'].insert(4, 'xyz') y = round_trip_dump(d, indent=2) @@ -361,7 +361,7 @@ class TestInsertPopList: - 2 """) - def test_insert_2(self): + def test_insert_2(self) -> None: d = round_trip_load(self.ins) d['ab'].insert(1, 'xyz') y = round_trip_dump(d, indent=2) @@ -378,7 +378,7 @@ class TestInsertPopList: - 2 """) - def test_pop_0(self): + def test_pop_0(self) -> None: d = round_trip_load(self.ins) d['ab'].pop(0) y = round_trip_dump(d, indent=2) @@ -394,7 +394,7 @@ class TestInsertPopList: - 2 """) - def test_pop_1(self): + def test_pop_1(self) -> None: d = round_trip_load(self.ins) d['ab'].pop(1) y = round_trip_dump(d, indent=2) @@ -410,7 +410,7 @@ class TestInsertPopList: - 2 """) - def test_pop_2(self): + def test_pop_2(self) -> None: d = round_trip_load(self.ins) d['ab'].pop(2) y = round_trip_dump(d, indent=2) @@ -426,7 +426,7 @@ class TestInsertPopList: - 2 """) - def test_pop_3(self): + def test_pop_3(self) -> None: d = round_trip_load(self.ins) d['ab'].pop(3) y = round_trip_dump(d, indent=2) @@ -446,14 +446,14 @@ class TestInsertPopList: # http://stackoverflow.com/a/36970608/1307905 class TestInsertInMapping: @property - def ins(self): + def ins(self) -> str: return """\ 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_1(self): + def test_insert_at_pos_1(self) -> None: d = round_trip_load(self.ins) d.insert(1, 'last name', 'Vandelay', comment='new key') y = round_trip_dump(d) @@ -465,7 +465,7 @@ class TestInsertInMapping: about: Art Vandelay is a fictional character that George invents... """) - def test_insert_at_pos_0(self): + def test_insert_at_pos_0(self) -> None: d = round_trip_load(self.ins) d.insert(0, 'last name', 'Vandelay', comment='new key') y = round_trip_dump(d) @@ -477,7 +477,7 @@ class TestInsertInMapping: about: Art Vandelay is a fictional character that George invents... """) - def test_insert_at_pos_3(self): + def test_insert_at_pos_3(self) -> None: # much more simple if done with appending. d = round_trip_load(self.ins) d.insert(3, 'last name', 'Vandelay', comment='new key') @@ -492,7 +492,7 @@ class TestInsertInMapping: class TestCommentedMapMerge: - def test_in_operator(self): + def test_in_operator(self) -> None: data = round_trip_load(""" x: &base a: 1 @@ -508,7 +508,7 @@ class TestCommentedMapMerge: assert data['y']['a'] == 1 assert 'a' in data['y'] - def test_issue_60(self): + def test_issue_60(self) -> None: data = round_trip_load(""" x: &base a: 1 @@ -519,7 +519,7 @@ class TestCommentedMapMerge: assert data['y']['a'] == 1 assert str(data['y']) == """ordereddict([('a', 1)])""" - def test_issue_60_1(self): + def test_issue_60_1(self) -> None: data = round_trip_load(""" x: &base a: 1 @@ -534,7 +534,7 @@ class TestCommentedMapMerge: class TestEmptyLines: # prompted by issue 46 from Alex Harvey - def test_issue_46(self): + def test_issue_46(self) -> None: yaml_str = dedent("""\ --- # Please add key/value pairs in alphabetical order @@ -549,7 +549,7 @@ class TestEmptyLines: y = round_trip_dump(d, explicit_start=True) assert yaml_str == y - def test_multispace_map(self): + def test_multispace_map(self) -> None: round_trip(""" a: 1x @@ -564,8 +564,8 @@ class TestEmptyLines: """) - @pytest.mark.xfail(strict=True) - def test_multispace_map_initial(self): + @pytest.mark.xfail(strict=True) # type: ignore + def test_multispace_map_initial(self) -> None: round_trip(""" a: 1x @@ -581,7 +581,7 @@ class TestEmptyLines: """) - def test_embedded_map(self): + def test_embedded_map(self) -> None: round_trip(""" - a: 1y b: 2y @@ -589,7 +589,7 @@ class TestEmptyLines: c: 3y """) - def test_toplevel_seq(self): + def test_toplevel_seq(self) -> None: round_trip("""\ - 1 @@ -598,7 +598,7 @@ class TestEmptyLines: - 3 """) - def test_embedded_seq(self): + def test_embedded_seq(self) -> None: round_trip(""" a: b: @@ -610,7 +610,7 @@ class TestEmptyLines: - 3 """) - def test_line_with_only_spaces(self): + def test_line_with_only_spaces(self) -> None: # issue 54 yaml_str = "---\n\na: 'x'\n \nb: y\n" d = round_trip_load(yaml_str, preserve_quotes=True) @@ -621,7 +621,7 @@ class TestEmptyLines: print(line + '$') assert stripped == y - def test_some_eol_spaces(self): + def test_some_eol_spaces(self) -> None: # spaces after tokens and on empty lines yaml_str = '--- \n \na: "x" \n \nb: y \n' d = round_trip_load(yaml_str, preserve_quotes=True) @@ -632,7 +632,7 @@ class TestEmptyLines: print(line + '$') assert stripped == y - def test_issue_54_not_ok(self): + def test_issue_54_not_ok(self) -> None: yaml_str = dedent("""\ toplevel: @@ -642,10 +642,11 @@ class TestEmptyLines: d = round_trip_load(yaml_str) print(d.ca) y = round_trip_dump(d, indent=4) + assert isinstance(y, str) print(y.replace('\n', '$\n')) assert yaml_str == y - def test_issue_54_ok(self): + def test_issue_54_ok(self) -> None: yaml_str = dedent("""\ toplevel: # some comment @@ -655,7 +656,7 @@ class TestEmptyLines: y = round_trip_dump(d, indent=4) assert yaml_str == y - def test_issue_93(self): + def test_issue_93(self) -> None: round_trip("""\ a: b: @@ -664,7 +665,7 @@ class TestEmptyLines: - c2: catfish # a2 """) - def test_issue_93_00(self): + def test_issue_93_00(self) -> None: round_trip("""\ a: - - c1: cat # a1 @@ -672,14 +673,14 @@ class TestEmptyLines: - c2: catfish # a2 """) - def test_issue_93_01(self): + def test_issue_93_01(self) -> None: round_trip("""\ - - c1: cat # a1 # my comment on catfish - c2: catfish # a2 """) - def test_issue_93_02(self): + def test_issue_93_02(self) -> None: # never failed as there is no indent round_trip("""\ - c1: cat @@ -687,7 +688,7 @@ class TestEmptyLines: - c2: catfish """) - def test_issue_96(self): + def test_issue_96(self) -> None: # inserted extra line on trailing spaces round_trip("""\ a: @@ -701,8 +702,8 @@ class TestEmptyLines: class TestUnicodeComments: - @pytest.mark.skipif(sys.version_info < (2, 7), reason='wide unicode') - def test_issue_55(self): # reported by Haraguroicha Hsu + @pytest.mark.skipif(sys.version_info < (2, 7), reason='wide unicode') # type: ignore + def test_issue_55(self) -> None: # reported by Haraguroicha Hsu round_trip("""\ name: TEST description: test using @@ -722,7 +723,7 @@ class TestUnicodeComments: class TestEmptyValueBeforeComments: - def test_issue_25a(self): + def test_issue_25a(self) -> None: round_trip("""\ - a: b c: d @@ -730,7 +731,7 @@ class TestEmptyValueBeforeComments: - e: f """) - def test_issue_25a1(self): + def test_issue_25a1(self) -> None: round_trip("""\ - a: b c: d @@ -738,13 +739,13 @@ class TestEmptyValueBeforeComments: e: f """) - def test_issue_25b(self): + def test_issue_25b(self) -> None: round_trip("""\ var1: #empty var2: something #notempty """) - def test_issue_25c(self): + def test_issue_25c(self) -> None: round_trip("""\ params: a: 1 # comment a @@ -752,7 +753,7 @@ class TestEmptyValueBeforeComments: c: 3 # comment c """) - def test_issue_25c1(self): + def test_issue_25c1(self) -> None: round_trip("""\ params: a: 1 # comment a @@ -761,14 +762,14 @@ class TestEmptyValueBeforeComments: c: 3 # comment c """) - def test_issue_25_00(self): + def test_issue_25_00(self) -> None: round_trip("""\ params: a: 1 # comment a b: # comment b """) - def test_issue_25_01(self): + def test_issue_25_01(self) -> None: round_trip("""\ a: # comment 1 # comment 2 @@ -776,14 +777,14 @@ class TestEmptyValueBeforeComments: c: 1 # comment 4 """) - def test_issue_25_02(self): + def test_issue_25_02(self) -> None: round_trip("""\ a: # comment 1 # comment 2 - b: 2 # comment 3 """) - def test_issue_25_03(self): + def test_issue_25_03(self) -> None: s = """\ a: # comment 1 # comment 2 @@ -791,14 +792,14 @@ class TestEmptyValueBeforeComments: """ round_trip(s, indent=4, block_seq_indent=2) - def test_issue_25_04(self): + def test_issue_25_04(self) -> None: round_trip("""\ a: # comment 1 # comment 2 b: 1 # comment 3 """) - def test_flow_seq_within_seq(self): + def test_flow_seq_within_seq(self) -> None: round_trip("""\ # comment 1 - a @@ -813,7 +814,7 @@ class TestEmptyValueBeforeComments: - [] """) - def test_comment_after_block_scalar_indicator(self): + def test_comment_after_block_scalar_indicator(self) -> None: round_trip("""\ a: | # abc test 1 @@ -834,7 +835,7 @@ a: | class TestBlockScalarWithComments: # issue 99 reported by Colm O'Connor - def test_scalar_with_comments(self): + def test_scalar_with_comments(self) -> None: import ruamel.yaml # NOQA for x in [ diff --git a/_test/test_contextmanager.py b/_test/test_contextmanager.py index bdc8b78..e6256d3 100644 --- a/_test/test_contextmanager.py +++ b/_test/test_contextmanager.py @@ -5,8 +5,9 @@ testing of anchors and the aliases referring to them """ import sys -import pytest +import pytest # type: ignore +from typing import Any single_doc = """\ - a: 1 @@ -31,33 +32,33 @@ multi_doc = """\ multi_doc_data = [['abc', 'xyz'], single_data] -def get_yaml(): +def get_yaml() -> Any: from ruamel.yaml import YAML return YAML() class TestOldStyle: - def test_single_load(self): + def test_single_load(self) -> None: d = get_yaml().load(single_doc) print(d) print(type(d[0])) assert d == single_data - def test_single_load_no_arg(self): + def test_single_load_no_arg(self) -> None: with pytest.raises(TypeError): assert get_yaml().load() == single_data - def test_multi_load(self): + def test_multi_load(self) -> None: data = list(get_yaml().load_all(multi_doc)) assert data == multi_doc_data - def test_single_dump(self, capsys): + def test_single_dump(self, capsys: Any) -> None: get_yaml().dump(single_data, sys.stdout) out, err = capsys.readouterr() assert out == single_doc - def test_multi_dump(self, capsys): + def test_multi_dump(self, capsys: Any) -> None: yaml = get_yaml() yaml.explicit_start = True yaml.dump_all(multi_doc_data, sys.stdout) @@ -66,7 +67,7 @@ class TestOldStyle: class TestContextManager: - def test_single_dump(self, capsys): + def test_single_dump(self, capsys: Any) -> None: from ruamel.yaml import YAML with YAML(output=sys.stdout) as yaml: @@ -75,7 +76,7 @@ class TestContextManager: print(err) assert out == single_doc - def test_multi_dump(self, capsys): + def test_multi_dump(self, capsys: Any) -> None: from ruamel.yaml import YAML with YAML(output=sys.stdout) as yaml: @@ -103,7 +104,7 @@ class TestContextManager: # for idx, data in enumerate(yaml.load()): # assert data == multi_doc_data[0] - def test_roundtrip(self, capsys): + def test_roundtrip(self, capsys: Any) -> None: from ruamel.yaml import YAML with YAML(output=sys.stdout) as yaml: diff --git a/_test/test_copy.py b/_test/test_copy.py index 4931d2a..cf402a4 100644 --- a/_test/test_copy.py +++ b/_test/test_copy.py @@ -6,13 +6,13 @@ Testing copy and deepcopy, instigated by Issue 84 (Peter Amstutz) import copy -import pytest # NOQA +import pytest # type: ignore # NOQA from roundtrip import dedent, round_trip_load, round_trip_dump class TestDeepCopy: - def test_preserve_flow_style_simple(self): + def test_preserve_flow_style_simple(self) -> None: x = dedent("""\ {foo: bar, baz: quux} """) @@ -24,7 +24,7 @@ class TestDeepCopy: assert y == x assert data.fa.flow_style() == data_copy.fa.flow_style() - def test_deepcopy_flow_style_nested_dict(self): + def test_deepcopy_flow_style_nested_dict(self) -> None: x = dedent("""\ a: {foo: bar, baz: quux} """) @@ -46,7 +46,7 @@ class TestDeepCopy: baz: quux """) - def test_deepcopy_flow_style_nested_list(self): + def test_deepcopy_flow_style_nested_list(self) -> None: x = dedent("""\ a: [1, 2, 3] """) @@ -71,7 +71,7 @@ class TestDeepCopy: class TestCopy: - def test_copy_flow_style_nested_dict(self): + def test_copy_flow_style_nested_dict(self) -> None: x = dedent("""\ a: {foo: bar, baz: quux} """) @@ -93,7 +93,7 @@ class TestCopy: baz: quux """) - def test_copy_flow_style_nested_list(self): + def test_copy_flow_style_nested_list(self) -> None: x = dedent("""\ a: [1, 2, 3] """) diff --git a/_test/test_cyaml.py b/_test/test_cyaml.py index 593d171..056093b 100644 --- a/_test/test_cyaml.py +++ b/_test/test_cyaml.py @@ -2,17 +2,17 @@ import sys import platform -import pytest +import pytest # type: ignore # NOQA from textwrap import dedent NO_CLIB_VER = (3, 10) -@pytest.mark.skipif( +@pytest.mark.skipif( # type: ignore platform.python_implementation() in ['Jython', 'PyPy'], reason='Jython throws RepresenterError' ) -def test_load_cyaml(): +def test_load_cyaml() -> None: print("???????????????????????", platform.python_implementation()) import ruamel.yaml @@ -24,10 +24,10 @@ def test_load_cyaml(): yaml.load('abc: 1') -@pytest.mark.skipif(sys.version_info >= NO_CLIB_VER +@pytest.mark.skipif(sys.version_info >= NO_CLIB_VER # type: ignore or platform.python_implementation() in ['Jython', 'PyPy'], reason='no _PyGC_FINALIZED') -def test_dump_cyaml(): +def test_dump_cyaml() -> None: import ruamel.yaml if sys.version_info >= NO_CLIB_VER: @@ -41,10 +41,10 @@ def test_dump_cyaml(): assert buf.getvalue() == 'a: 1\nb: 2\n' -@pytest.mark.skipif( +@pytest.mark.skipif( # type: ignore platform.python_implementation() in ['Jython', 'PyPy'], reason='not avialable' ) -def test_load_cyaml_1_2(): +def test_load_cyaml_1_2() -> None: # issue 155 import ruamel.yaml @@ -60,10 +60,10 @@ def test_load_cyaml_1_2(): yaml.load(inp) -@pytest.mark.skipif( +@pytest.mark.skipif( # type: ignore platform.python_implementation() in ['Jython', 'PyPy'], reason='not available' ) -def test_dump_cyaml_1_2(): +def test_dump_cyaml_1_2() -> None: # issue 155 import ruamel.yaml from ruamel.yaml.compat import StringIO diff --git a/_test/test_datetime.py b/_test/test_datetime.py index 7321816..bc86e74 100644 --- a/_test/test_datetime.py +++ b/_test/test_datetime.py @@ -20,13 +20,13 @@ Please note that a fraction can only be included if not equal to 0 """ import copy -import pytest # NOQA +import pytest # type: ignore # NOQA from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NOQA class TestDateTime: - def test_date_only(self): + def test_date_only(self) -> None: inp = """ - 2011-10-02 """ @@ -35,7 +35,7 @@ class TestDateTime: """ round_trip(inp, exp) - def test_zero_fraction(self): + def test_zero_fraction(self) -> None: inp = """ - 2011-10-02 16:45:00.0 """ @@ -44,7 +44,7 @@ class TestDateTime: """ round_trip(inp, exp) - def test_long_fraction(self): + def test_long_fraction(self) -> None: inp = """ - 2011-10-02 16:45:00.1234 # expand with zeros - 2011-10-02 16:45:00.123456 @@ -61,7 +61,7 @@ class TestDateTime: """ round_trip(inp, exp) - def test_canonical(self): + def test_canonical(self) -> None: inp = """ - 2011-10-02T16:45:00.1Z """ @@ -70,7 +70,7 @@ class TestDateTime: """ round_trip(inp, exp) - def test_spaced_timezone(self): + def test_spaced_timezone(self) -> None: inp = """ - 2011-10-02T11:45:00 -5 """ @@ -79,7 +79,7 @@ class TestDateTime: """ round_trip(inp, exp) - def test_normal_timezone(self): + def test_normal_timezone(self) -> None: round_trip(""" - 2011-10-02T11:45:00-5 - 2011-10-02 11:45:00-5 @@ -87,7 +87,7 @@ class TestDateTime: - 2011-10-02 11:45:00-05:00 """) - def test_no_timezone(self): + def test_no_timezone(self) -> None: inp = """ - 2011-10-02 6:45:00 """ @@ -96,7 +96,7 @@ class TestDateTime: """ round_trip(inp, exp) - def test_explicit_T(self): + def test_explicit_T(self) -> None: inp = """ - 2011-10-02T16:45:00 """ @@ -105,7 +105,7 @@ class TestDateTime: """ round_trip(inp, exp) - def test_explicit_t(self): # to upper + def test_explicit_t(self) -> None: # to upper inp = """ - 2011-10-02t16:45:00 """ @@ -114,7 +114,7 @@ class TestDateTime: """ round_trip(inp, exp) - def test_no_T_multi_space(self): + def test_no_T_multi_space(self) -> None: inp = """ - 2011-10-02 16:45:00 """ @@ -123,22 +123,22 @@ class TestDateTime: """ round_trip(inp, exp) - def test_iso(self): + def test_iso(self) -> None: round_trip(""" - 2011-10-02T15:45:00+01:00 """) - def test_zero_tz(self): + def test_zero_tz(self) -> None: round_trip(""" - 2011-10-02T15:45:00+0 """) - def test_issue_45(self): + def test_issue_45(self) -> None: round_trip(""" dt: 2016-08-19T22:45:47Z """) - def test_deepcopy_datestring(self): + def test_deepcopy_datestring(self) -> None: # reported by Quuxplusone, http://stackoverflow.com/a/41577841/1307905 x = dedent("""\ foo: 2016-10-12T12:34:56 @@ -146,7 +146,7 @@ class TestDateTime: data = copy.deepcopy(round_trip_load(x)) assert round_trip_dump(data) == x - def test_fraction_overflow(self): + def test_fraction_overflow(self) -> None: # reported (indirectly) by LuÃs Ferreira # https://sourceforge.net/p/ruamel-yaml/tickets/414/ inp = dedent("""\ diff --git a/_test/test_deprecation.py b/_test/test_deprecation.py index b267e66..390c26c 100644 --- a/_test/test_deprecation.py +++ b/_test/test_deprecation.py @@ -1,11 +1,11 @@ # coding: utf-8 import sys -import pytest # NOQA +import pytest # type:ignore # NOQA -@pytest.mark.skipif(sys.version_info < (3, 7) or sys.version_info >= (3, 9), +@pytest.mark.skipif(sys.version_info < (3, 7) or sys.version_info >= (3, 9), # type: ignore reason='collections not available?') -def test_collections_deprecation(): +def test_collections_deprecation() -> None: with pytest.warns(DeprecationWarning): - from collections import Hashable # NOQA + from collections import Hashable # type: ignore # NOQA diff --git a/_test/test_documents.py b/_test/test_documents.py index 5119f06..7c6e2e6 100644 --- a/_test/test_documents.py +++ b/_test/test_documents.py @@ -1,12 +1,12 @@ # coding: utf-8 -import pytest # NOQA +import pytest # type: ignore # NOQA from roundtrip import round_trip, round_trip_load_all, round_trip_dump_all class TestDocument: - def test_single_doc_begin_end(self): + def test_single_doc_begin_end(self) -> None: inp = """\ --- - a @@ -15,7 +15,7 @@ class TestDocument: """ round_trip(inp, explicit_start=True, explicit_end=True) - def test_multi_doc_begin_end(self): + def test_multi_doc_begin_end(self) -> None: inp = """\ --- - a @@ -29,7 +29,7 @@ class TestDocument: out = round_trip_dump_all(docs, explicit_start=True, explicit_end=True) assert out == '---\n- a\n...\n---\n- b\n...\n' - def test_multi_doc_no_start(self): + def test_multi_doc_no_start(self) -> None: inp = """\ - a ... @@ -40,7 +40,7 @@ class TestDocument: docs = list(round_trip_load_all(inp)) assert docs == [['a'], ['b']] - def test_multi_doc_no_end(self): + def test_multi_doc_no_end(self) -> None: inp = """\ - a --- @@ -49,7 +49,7 @@ class TestDocument: docs = list(round_trip_load_all(inp)) assert docs == [['a'], ['b']] - def test_multi_doc_ends_only(self): + def test_multi_doc_ends_only(self) -> None: # this is ok in 1.2 inp = """\ - a @@ -60,7 +60,7 @@ class TestDocument: docs = list(round_trip_load_all(inp, version=(1, 2))) assert docs == [['a'], ['b']] - def test_multi_doc_ends_only_1_1(self): + def test_multi_doc_ends_only_1_1(self) -> None: from ruamel import yaml # this is not ok in 1.1 diff --git a/_test/test_fail.py b/_test/test_fail.py index 2f90112..7fbbd07 100644 --- a/_test/test_fail.py +++ b/_test/test_fail.py @@ -6,14 +6,14 @@ # on fix of ruamel.yaml, move the marked test to the appropriate test (without mark) # and remove remove the xyz_no_fail -import pytest +import pytest # type: ignore from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump class TestCommentFailures: - @pytest.mark.xfail(strict=True) - def test_set_comment_before_tag(self): + @pytest.mark.xfail(strict=True) # type: ignore + def test_set_comment_before_tag(self) -> None: # no comments before tags round_trip(""" # the beginning @@ -26,7 +26,7 @@ class TestCommentFailures: # this is the end """) - def test_set_comment_before_tag_no_fail(self): + def test_set_comment_before_tag_no_fail(self) -> None: # no comments before tags inp = """ # the beginning @@ -48,15 +48,15 @@ class TestCommentFailures: # this is the end """) - @pytest.mark.xfail(strict=True) - def test_comment_dash_line(self): + @pytest.mark.xfail(strict=True) # type: ignore + def test_comment_dash_line(self) -> None: round_trip(""" - # abc a: 1 b: 2 """) - def test_comment_dash_line_fail(self): + def test_comment_dash_line_fail(self) -> None: x = """ - # abc a: 1 @@ -72,8 +72,8 @@ class TestCommentFailures: class TestIndentFailures: - @pytest.mark.xfail(strict=True) - def test_indent_not_retained(self): + @pytest.mark.xfail(strict=True) # type: ignore + def test_indent_not_retained(self) -> None: round_trip(""" verbosity: 1 # 0 is minimal output, -1 none base_url: http://gopher.net @@ -97,7 +97,7 @@ class TestIndentFailures: - too cold """) - def test_indent_not_retained_no_fail(self): + def test_indent_not_retained_no_fail(self) -> None: inp = """ verbosity: 1 # 0 is minimal output, -1 none base_url: http://gopher.net @@ -143,7 +143,7 @@ class TestIndentFailures: - too cold """) - def Xtest_indent_top_level_no_fail(self): + def Xtest_indent_top_level_no_fail(self) -> None: inp = """ - a: - b @@ -152,8 +152,8 @@ class TestIndentFailures: class TestTagFailures: - @pytest.mark.xfail(strict=True) - def test_standard_short_tag(self): + @pytest.mark.xfail(strict=True) # type: ignore + def test_standard_short_tag(self) -> None: round_trip("""\ !!map name: Anthon @@ -161,7 +161,7 @@ class TestTagFailures: language: python """) - def test_standard_short_tag_no_fail(self): + def test_standard_short_tag_no_fail(self) -> None: inp = """ !!map name: Anthon @@ -177,13 +177,13 @@ class TestTagFailures: class TestFlowValues: - def test_flow_value_with_colon(self): + def test_flow_value_with_colon(self) -> None: inp = """\ {a: bcd:efg} """ round_trip(inp) - def test_flow_value_with_colon_quoted(self): + def test_flow_value_with_colon_quoted(self) -> None: inp = """\ {a: 'bcd:efg'} """ @@ -191,13 +191,13 @@ class TestFlowValues: class TestMappingKey: - def test_simple_mapping_key(self): + def test_simple_mapping_key(self) -> None: inp = """\ {a: 1, b: 2}: hello world """ round_trip(inp, preserve_quotes=True, dump_data=False) - def test_set_simple_mapping_key(self): + def test_set_simple_mapping_key(self) -> None: from ruamel.yaml.comments import CommentedKeyMap d = {CommentedKeyMap([('a', 1), ('b', 2)]): 'hello world'} @@ -206,7 +206,7 @@ class TestMappingKey: """) assert round_trip_dump(d) == exp - def test_change_key_simple_mapping_key(self): + def test_change_key_simple_mapping_key(self) -> None: from ruamel.yaml.comments import CommentedKeyMap inp = """\ @@ -219,7 +219,7 @@ class TestMappingKey: """) assert round_trip_dump(d) == exp - def test_change_value_simple_mapping_key(self): + def test_change_value_simple_mapping_key(self) -> None: from ruamel.yaml.comments import CommentedKeyMap inp = """\ diff --git a/_test/test_float.py b/_test/test_float.py index 8257208..582ccf0 100644 --- a/_test/test_float.py +++ b/_test/test_float.py @@ -1,6 +1,6 @@ # coding: utf-8 -import pytest # NOQA +import pytest # type: ignore # NOQA from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NOQA @@ -8,7 +8,7 @@ from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NO class TestFloat: - def test_round_trip_non_exp(self): + def test_round_trip_non_exp(self) -> None: data = round_trip("""\ - 1.0 - 1.00 @@ -22,6 +22,8 @@ class TestFloat: - .5 - +.5 - -.5 + - !!float '42' + - !!float '-42' """) print(data) assert 0.999 < data[0] < 1.001 @@ -36,8 +38,10 @@ class TestFloat: assert .49 < data[9] < .51 assert .49 < data[10] < .51 assert -.51 < data[11] < -.49 + assert 41.99 < data[12] < 42.01 + assert 41.99 < -data[13] < 42.01 - def test_round_trip_zeros_0(self): + def test_round_trip_zeros_0(self) -> None: data = round_trip("""\ - 0. - +0. @@ -53,12 +57,13 @@ class TestFloat: for d in data: assert -0.00001 < d < 0.00001 - def Xtest_round_trip_non_exp_trailing_dot(self): + def test_round_trip_exp_trailing_dot(self) -> None: data = round_trip("""\ + - 3.e4 """) print(data) - def test_yaml_1_1_no_dot(self): + def test_yaml_1_1_no_dot(self) -> None: from ruamel.yaml.error import MantissaNoDotYAML1_1Warning with pytest.warns(MantissaNoDotYAML1_1Warning): @@ -69,8 +74,8 @@ class TestFloat: """) -class TestCalculations(object): - def test_mul_00(self): +class TestCalculations: + def test_mul_00(self) -> None: # issue 149 reported by jan.brezina@tul.cz d = round_trip_load("""\ - 0.1 diff --git a/_test/test_flowsequencekey.py b/_test/test_flowsequencekey.py index 96bee67..be70699 100644 --- a/_test/test_flowsequencekey.py +++ b/_test/test_flowsequencekey.py @@ -11,7 +11,7 @@ from roundtrip import round_trip # , dedent, round_trip_load, round_trip_dump class TestFlowStyleSequenceKey: - def test_so_39595807(self): + def test_so_39595807(self) -> None: inp = """\ %YAML 1.2 --- diff --git a/_test/test_indentation.py b/_test/test_indentation.py index 6e0fce2..1f16cb2 100644 --- a/_test/test_indentation.py +++ b/_test/test_indentation.py @@ -1,23 +1,24 @@ # coding: utf-8 -import pytest # NOQA +from typing import Any +import pytest # type: ignore # NOQA from roundtrip import round_trip, round_trip_load, round_trip_dump, dedent, YAML -def rt(s): - +def rt(s: str) -> str: res = round_trip_dump(round_trip_load(s)) + assert res is not None return res.strip() + '\n' class TestIndent: - def test_roundtrip_inline_list(self): + def test_roundtrip_inline_list(self) -> None: s = 'a: [a, b, c]\n' output = rt(s) assert s == output - def test_roundtrip_mapping_of_inline_lists(self): + def test_roundtrip_mapping_of_inline_lists(self) -> None: s = dedent("""\ a: [a, b, c] j: [k, l, m] @@ -25,7 +26,7 @@ class TestIndent: output = rt(s) assert s == output - def test_roundtrip_mapping_of_inline_lists_comments(self): + def test_roundtrip_mapping_of_inline_lists_comments(self) -> None: s = dedent("""\ # comment A a: [a, b, c] @@ -35,7 +36,7 @@ class TestIndent: output = rt(s) assert s == output - def test_roundtrip_mapping_of_inline_sequence_eol_comments(self): + def test_roundtrip_mapping_of_inline_sequence_eol_comments(self) -> None: s = dedent("""\ # comment A a: [a, b, c] # comment B @@ -45,7 +46,7 @@ class TestIndent: assert s == output # first test by explicitly setting flow style - def test_added_inline_list(self): + def test_added_inline_list(self) -> None: s1 = dedent(""" a: - b @@ -62,7 +63,7 @@ class TestIndent: # ############ flow mappings - def test_roundtrip_flow_mapping(self): + def test_roundtrip_flow_mapping(self) -> None: s = dedent("""\ - {a: 1, b: hallo} - {j: fka, k: 42} @@ -71,7 +72,7 @@ class TestIndent: output = round_trip_dump(data) assert s == output - def test_roundtrip_sequence_of_inline_mappings_eol_comments(self): + def test_roundtrip_sequence_of_inline_mappings_eol_comments(self) -> None: s = dedent("""\ # comment A - {a: 1, b: hallo} # comment B @@ -80,14 +81,14 @@ class TestIndent: output = rt(s) assert s == output - def test_indent_top_level(self): + def test_indent_top_level(self) -> None: inp = """ - a: - b """ round_trip(inp, indent=4) - def test_set_indent_5_block_list_indent_1(self): + def test_set_indent_5_block_list_indent_1(self) -> None: inp = """ a: - b: c @@ -97,7 +98,7 @@ class TestIndent: """ round_trip(inp, indent=5, block_seq_indent=1) - def test_set_indent_4_block_list_indent_2(self): + def test_set_indent_4_block_list_indent_2(self) -> None: inp = """ a: - b: c @@ -107,7 +108,7 @@ class TestIndent: """ round_trip(inp, indent=4, block_seq_indent=2) - def test_set_indent_3_block_list_indent_0(self): + def test_set_indent_3_block_list_indent_0(self) -> None: inp = """ a: - b: c @@ -117,7 +118,7 @@ class TestIndent: """ round_trip(inp, indent=3, block_seq_indent=0) - def Xtest_set_indent_3_block_list_indent_2(self): + def Xtest_set_indent_3_block_list_indent_2(self) -> None: inp = """ a: - @@ -131,7 +132,7 @@ class TestIndent: """ round_trip(inp, indent=3, block_seq_indent=2) - def test_set_indent_3_block_list_indent_2(self): + def test_set_indent_3_block_list_indent_2(self) -> None: inp = """ a: - b: c @@ -141,7 +142,7 @@ class TestIndent: """ round_trip(inp, indent=3, block_seq_indent=2) - def Xtest_set_indent_2_block_list_indent_2(self): + def Xtest_set_indent_2_block_list_indent_2(self) -> None: inp = """ a: - @@ -156,7 +157,7 @@ class TestIndent: round_trip(inp, 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): + def test_set_indent_2_block_list_indent_2(self) -> None: inp = """ a: - b: c @@ -167,7 +168,7 @@ class TestIndent: round_trip(inp, indent=2, block_seq_indent=2) # have to set indent! - def test_roundtrip_four_space_indents(self): + def test_roundtrip_four_space_indents(self) -> None: # fmt: off s = ( 'a:\n' @@ -177,7 +178,7 @@ class TestIndent: # fmt: on round_trip(s, indent=4) - def test_roundtrip_four_space_indents_no_fail(self): + def test_roundtrip_four_space_indents_no_fail(self) -> None: inp = """ a: - foo @@ -192,7 +193,7 @@ class TestIndent: class TestYpkgIndent: - def test_00(self): + def test_00(self) -> None: inp = """ name : nano version : 2.3.2 @@ -214,7 +215,7 @@ class TestYpkgIndent: ) -def guess(s): +def guess(s: str) -> Any: from ruamel.yaml.util import load_yaml_guess_indent x, y, z = load_yaml_guess_indent(dedent(s)) @@ -222,21 +223,21 @@ def guess(s): class TestGuessIndent: - def test_guess_20(self): + def test_guess_20(self) -> None: inp = """\ a: - 1 """ assert guess(inp) == (2, 0) - def test_guess_42(self): + def test_guess_42(self) -> None: inp = """\ a: - 1 """ assert guess(inp) == (4, 2) - def test_guess_42a(self): + def test_guess_42a(self) -> None: # block seq indent prevails over nested key indent level inp = """\ b: @@ -245,7 +246,7 @@ class TestGuessIndent: """ assert guess(inp) == (4, 2) - def test_guess_3None(self): + def test_guess_3None(self) -> None: inp = """\ b: a: 1 @@ -256,7 +257,7 @@ class TestGuessIndent: class TestSeparateMapSeqIndents: # using uncommon 6 indent with 3 push in as 2 push in automatically # gets you 4 indent even if not set - def test_00(self): + def test_00(self) -> None: # old style yaml = YAML() yaml.indent = 6 @@ -268,7 +269,7 @@ class TestSeparateMapSeqIndents: """ yaml.round_trip(inp) - def test_01(self): + def test_01(self) -> None: yaml = YAML() yaml.indent(sequence=6) yaml.indent(offset=3) @@ -279,7 +280,7 @@ class TestSeparateMapSeqIndents: """ yaml.round_trip(inp) - def test_02(self): + def test_02(self) -> None: yaml = YAML() yaml.indent(mapping=5, sequence=6, offset=3) inp = """ @@ -290,7 +291,7 @@ class TestSeparateMapSeqIndents: """ yaml.round_trip(inp) - def test_03(self): + def test_03(self) -> None: inp = """ a: b: @@ -300,7 +301,7 @@ class TestSeparateMapSeqIndents: """ round_trip(inp, indent=4) - def test_04(self): + def test_04(self) -> None: yaml = YAML() yaml.indent(mapping=5, sequence=6) inp = """ @@ -312,7 +313,7 @@ class TestSeparateMapSeqIndents: """ yaml.round_trip(inp) - def test_issue_51(self): + def test_issue_51(self) -> None: yaml = YAML() # yaml.map_indent = 2 # the default yaml.indent(sequence=4, offset=2) diff --git a/_test/test_int.py b/_test/test_int.py index aa300df..92fb92a 100644 --- a/_test/test_int.py +++ b/_test/test_int.py @@ -1,6 +1,6 @@ # coding: utf-8 -import pytest # NOQA +import pytest # type: ignore # NOQA from roundtrip import dedent, round_trip_load, round_trip_dump @@ -8,7 +8,7 @@ from roundtrip import dedent, round_trip_load, round_trip_dump class TestBinHexOct: - def test_calculate(self): + def test_calculate(self) -> None: # make sure type, leading zero(s) and underscore are preserved s = dedent("""\ - 42 diff --git a/_test/test_issues.py b/_test/test_issues.py index 736dccb..7106453 100644 --- a/_test/test_issues.py +++ b/_test/test_issues.py @@ -1,6 +1,8 @@ # coding: utf-8 -import pytest # NOQA +from typing import Any + +import pytest # type: ignore # NOQA from roundtrip import ( @@ -15,7 +17,7 @@ from roundtrip import ( class TestIssues: - def test_issue_61(self): + def test_issue_61(self) -> None: s = dedent(""" def1: &ANCHOR1 key1: value1 @@ -29,54 +31,54 @@ class TestIssues: assert str(data['comb']) == str(data['def']) assert str(data['comb']) == "ordereddict([('key', 'value'), ('key1', 'value1')])" - def test_issue_82(self, tmpdir): - program_src = r''' - from ruamel import yaml - import re - - class SINumber(yaml.YAMLObject): - PREFIXES = {'k': 1e3, 'M': 1e6, 'G': 1e9} - yaml_loader = yaml.Loader - yaml_dumper = yaml.Dumper - yaml_tag = '!si' - yaml_implicit_pattern = re.compile( - r'^(?P<value>[0-9]+(?:\.[0-9]+)?)(?P<prefix>[kMG])$') - - @classmethod - def from_yaml(cls, loader, node): - return cls(node.value) - - @classmethod - def to_yaml(cls, dumper, data): - return dumper.represent_scalar(cls.yaml_tag, str(data)) - - def __init__(self, *args): - m = self.yaml_implicit_pattern.match(args[0]) - self.value = float(m.groupdict()['value']) - self.prefix = m.groupdict()['prefix'] - - def __str__(self): - return str(self.value)+self.prefix - - def __int__(self): - return int(self.value*self.PREFIXES[self.prefix]) - - # This fails: - yaml.add_implicit_resolver(SINumber.yaml_tag, SINumber.yaml_implicit_pattern) - - ret = yaml.load(""" - [1,2,3, !si 10k, 100G] - """, Loader=yaml.Loader) - for idx, l in enumerate([1, 2, 3, 10000, 100000000000]): - assert int(ret[idx]) == l - ''' - assert save_and_run(dedent(program_src), tmpdir) == 0 - - def test_issue_82rt(self, tmpdir): +# def test_issue_82(self, tmpdir): +# program_src = r''' +# from ruamel import yaml +# import re +# +# class SINumber(yaml.YAMLObject): +# PREFIXES = {'k': 1e3, 'M': 1e6, 'G': 1e9} +# yaml_loader = yaml.Loader +# yaml_dumper = yaml.Dumper +# yaml_tag = '!si' +# yaml_implicit_pattern = re.compile( +# r'^(?P<value>[0-9]+(?:\.[0-9]+)?)(?P<prefix>[kMG])$') +# +# @classmethod +# def from_yaml(cls, loader, node): +# return cls(node.value) +# +# @classmethod +# def to_yaml(cls, dumper, data): +# return dumper.represent_scalar(cls.yaml_tag, str(data)) +# +# def __init__(self, *args): +# m = self.yaml_implicit_pattern.match(args[0]) +# self.value = float(m.groupdict()['value']) +# self.prefix = m.groupdict()['prefix'] +# +# def __str__(self) -> None: +# return str(self.value)+self.prefix +# +# def __int__(self) -> None: +# return int(self.value*self.PREFIXES[self.prefix]) +# +# # This fails: +# yaml.add_implicit_resolver(SINumber.yaml_tag, SINumber.yaml_implicit_pattern) +# +# ret = yaml.load(""" +# [1,2,3, !si 10k, 100G] +# """, Loader=yaml.Loader) +# for idx, l in enumerate([1, 2, 3, 10000, 100000000000]): +# assert int(ret[idx]) == l +# ''' +# assert save_and_run(dedent(program_src), tmpdir) == 0 + + def test_issue_82rt(self, tmpdir: Any) -> None: yaml_str = '[1, 2, 3, !si 10k, 100G]\n' x = round_trip(yaml_str, preserve_quotes=True) # NOQA - def test_issue_102(self): + def test_issue_102(self) -> None: yaml_str = dedent(""" var1: #empty var2: something #notempty @@ -86,8 +88,8 @@ class TestIssues: """) x = round_trip(yaml_str, preserve_quotes=True) # NOQA - def test_issue_150(self): - from ruamel.yaml import YAML + def test_issue_150(self) -> None: + from ruamel.yaml import YAML # type: ignore inp = """\ base: &base_key @@ -103,7 +105,7 @@ class TestIssues: child = data['child'] assert 'second' in dict(**child) - def test_issue_160(self): + def test_issue_160(self) -> None: from ruamel.yaml.compat import StringIO s = dedent("""\ root: @@ -127,7 +129,7 @@ class TestIssues: """) assert buf.getvalue() == exp - def test_issue_161(self): + def test_issue_161(self) -> None: yaml_str = dedent("""\ mapping-A: key-A:{} @@ -137,7 +139,7 @@ class TestIssues: s = yaml_str.format(comment) res = round_trip(s) # NOQA - def test_issue_161a(self): + def test_issue_161a(self) -> None: yaml_str = dedent("""\ mapping-A: key-A:{} @@ -147,7 +149,7 @@ class TestIssues: s = yaml_str.format(comment) res = round_trip(s) # NOQA - def test_issue_163(self): + def test_issue_163(self) -> None: s = dedent("""\ some-list: # List comment @@ -163,19 +165,19 @@ class TestIssues: json_str2 = '{"abc":[{"a":"1", "uses":0}]}' - def test_issue_172(self): + def test_issue_172(self) -> None: x = round_trip_load(TestIssues.json_str2) # NOQA x = round_trip_load(TestIssues.json_str) # NOQA - def test_issue_176(self): + def test_issue_176(self) -> None: # basic request by Stuart Berg - from ruamel.yaml import YAML + from ruamel.yaml import YAML # type: ignore yaml = YAML() seq = yaml.load('[1,2,3]') seq[:] = [1, 2, 3, 4] - def test_issue_176_preserve_comments_on_extended_slice_assignment(self): + def test_issue_176_preserve_comments_on_extended_slice_assignment(self) -> None: yaml_str = dedent("""\ - a - b # comment @@ -190,7 +192,7 @@ class TestIssues: res = round_trip_dump(seq) assert res == yaml_str.replace(' b ', ' B ').replace(' d\n', ' D\n') - def test_issue_176_test_slicing(self): + def test_issue_176_test_slicing(self) -> None: mss = round_trip_load('[0, 1, 2, 3, 4]') assert len(mss) == 5 assert mss[2:2] == [] @@ -240,7 +242,7 @@ class TestIssues: del m[:] assert m == [] - def test_issue_184(self): + def test_issue_184(self) -> None: yaml_str = dedent("""\ test::test: # test @@ -252,20 +254,20 @@ class TestIssues: d.yaml_add_eol_comment('test1', 'bar') assert round_trip_dump(d) == yaml_str + 'bar: foo # test1\n' - def test_issue_219(self): + def test_issue_219(self) -> None: yaml_str = dedent("""\ [StackName: AWS::StackName] """) d = round_trip_load(yaml_str) # NOQA - def test_issue_219a(self): + def test_issue_219a(self) -> None: yaml_str = dedent("""\ [StackName: AWS::StackName] """) d = round_trip_load(yaml_str) # NOQA - def test_issue_220(self, tmpdir): + def test_issue_220(self, tmpdir: Any) -> None: program_src = r''' from ruamel.yaml import YAML @@ -280,14 +282,14 @@ class TestIssues: ''' assert save_and_run(dedent(program_src), tmpdir, optimized=True) == 0 - def test_issue_221_add(self): + def test_issue_221_add(self) -> None: from ruamel.yaml.comments import CommentedSeq a = CommentedSeq([1, 2, 3]) a + [4, 5] - def test_issue_221_sort(self): - from ruamel.yaml import YAML + def test_issue_221_sort(self) -> None: + from ruamel.yaml import YAML # type: ignore from ruamel.yaml.compat import StringIO yaml = YAML() @@ -311,8 +313,8 @@ class TestIssues: """) assert buf.getvalue() == exp - def test_issue_221_sort_reverse(self): - from ruamel.yaml import YAML + def test_issue_221_sort_reverse(self) -> None: + from ruamel.yaml import YAML # type: ignore from ruamel.yaml.compat import StringIO yaml = YAML() @@ -336,8 +338,8 @@ class TestIssues: """) assert buf.getvalue() == exp - def test_issue_221_sort_key(self): - from ruamel.yaml import YAML + def test_issue_221_sort_key(self) -> None: + from ruamel.yaml import YAML # type: ignore from ruamel.yaml.compat import StringIO yaml = YAML() @@ -361,8 +363,8 @@ class TestIssues: """) assert buf.getvalue() == exp - def test_issue_221_sort_key_reverse(self): - from ruamel.yaml import YAML + def test_issue_221_sort_key_reverse(self) -> None: + from ruamel.yaml import YAML # type: ignore from ruamel.yaml.compat import StringIO yaml = YAML() @@ -386,7 +388,7 @@ class TestIssues: """) assert buf.getvalue() == exp - def test_issue_222(self): + def test_issue_222(self) -> None: import ruamel.yaml from ruamel.yaml.compat import StringIO @@ -395,13 +397,13 @@ class TestIssues: yaml.dump(['012923'], buf) assert buf.getvalue() == "['012923']\n" - def test_issue_223(self): + def test_issue_223(self) -> None: import ruamel.yaml yaml = ruamel.yaml.YAML(typ='safe') yaml.load('phone: 0123456789') - def test_issue_232(self): + def test_issue_232(self) -> None: import ruamel.yaml yaml = YAML(typ='safe', pure=True) @@ -411,24 +413,24 @@ class TestIssues: with pytest.raises(ruamel.yaml.parser.ParserError): yaml.load('{]') - def test_issue_233(self): - from ruamel.yaml import YAML + def test_issue_233(self) -> None: + from ruamel.yaml import YAML # type: ignore import json yaml = YAML() data = yaml.load('{}') json_str = json.dumps(data) # NOQA - def test_issue_233a(self): - from ruamel.yaml import YAML + def test_issue_233a(self) -> None: + from ruamel.yaml import YAML # type: ignore import json yaml = YAML() data = yaml.load('[]') json_str = json.dumps(data) # NOQA - def test_issue_234(self): - from ruamel.yaml import YAML + def test_issue_234(self) -> None: + from ruamel.yaml import YAML # type: ignore inp = dedent("""\ - key: key1 @@ -444,7 +446,7 @@ class TestIssues: print(repr(fold)) assert '\a' not in fold - def test_issue_236(self): + def test_issue_236(self) -> None: inp = """ conf: xx: {a: "b", c: []} @@ -452,7 +454,7 @@ class TestIssues: """ d = round_trip(inp, preserve_quotes=True) # NOQA - def test_issue_238(self, tmpdir): + def test_issue_238(self, tmpdir: Any) -> None: program_src = r""" import ruamel.yaml from ruamel.yaml.compat import StringIO @@ -484,7 +486,7 @@ class TestIssues: """ assert save_and_run(dedent(program_src), tmpdir) == 0 - def test_issue_239(self): + def test_issue_239(self) -> None: inp = """ first_name: Art occupation: Architect @@ -504,14 +506,14 @@ class TestIssues: """ d = YAML().round_trip_all(inp) # NOQA - def test_issue_242(self): + def test_issue_242(self) -> None: from ruamel.yaml.comments import CommentedMap d0 = CommentedMap([('a', 'b')]) assert d0['a'] == 'b' - def test_issue_245(self): - from ruamel.yaml import YAML + def test_issue_245(self) -> None: + from ruamel.yaml import YAML # type: ignore inp = """ d: yes """ @@ -528,7 +530,7 @@ class TestIssues: print(typ, yaml.parser, yaml.resolver) assert d['d'] is True - def test_issue_249(self): + def test_issue_249(self) -> None: yaml = YAML() inp = dedent("""\ # comment @@ -545,7 +547,7 @@ class TestIssues: """) yaml.round_trip(inp, outp=exp) # NOQA - def test_issue_250(self): + def test_issue_250(self) -> None: inp = """ # 1. - - 1 @@ -557,8 +559,8 @@ class TestIssues: d = round_trip(inp) # NOQA # @pytest.mark.xfail(strict=True, reason='bla bla', raises=AssertionError) - def test_issue_279(self): - from ruamel.yaml import YAML + def test_issue_279(self) -> None: + from ruamel.yaml import YAML # type: ignore from ruamel.yaml.compat import StringIO yaml = YAML() @@ -576,8 +578,8 @@ class TestIssues: print(buf.getvalue()) assert buf.getvalue() == inp - def test_issue_280(self): - from ruamel.yaml import YAML + def test_issue_280(self) -> None: + from ruamel.yaml import YAML # type: ignore from ruamel.yaml.representer import RepresenterError from collections import namedtuple from sys import stdout @@ -587,7 +589,7 @@ class TestIssues: with pytest.raises(RepresenterError, match='cannot represent'): yaml.dump({'t': t}, stdout) - def test_issue_282(self): + def test_issue_282(self) -> None: # update from list of tuples caused AttributeError import ruamel.yaml yaml_data = ruamel.yaml.comments.CommentedMap([('a', 'apple'), ('b', 'banana')]) @@ -596,7 +598,7 @@ class TestIssues: assert 'c' in yaml_data.keys() assert 'c' in yaml_data._ok - def test_issue_284(self): + def test_issue_284(self) -> None: import ruamel.yaml inp = dedent("""\ plain key: in-line value @@ -614,8 +616,8 @@ class TestIssues: with pytest.raises(ruamel.yaml.parser.ParserError, match='expected <block end>'): d = yaml.load(inp) - def test_issue_285(self): - from ruamel.yaml import YAML + def test_issue_285(self) -> None: + from ruamel.yaml import YAML # type: ignore yaml = YAML() inp = dedent("""\ @@ -632,8 +634,8 @@ class TestIssues: assert not a[1] assert not a[3] - def test_issue_286(self): - from ruamel.yaml import YAML + def test_issue_286(self) -> None: + from ruamel.yaml import YAML # type: ignore from ruamel.yaml.compat import StringIO yaml = YAML() @@ -648,10 +650,10 @@ class TestIssues: yaml.dump(a, buf) assert buf.getvalue().endswith('xxx\nnew_key: new_value\n') - def test_issue_288(self): + def test_issue_288(self) -> None: import sys from ruamel.yaml.compat import StringIO - from ruamel.yaml import YAML + from ruamel.yaml import YAML # type: ignore yamldoc = dedent("""\ --- @@ -679,10 +681,10 @@ class TestIssues: yaml.dump(data, buf) assert buf.getvalue() == yamldoc - def test_issue_288a(self): + def test_issue_288a(self) -> None: import sys from ruamel.yaml.compat import StringIO - from ruamel.yaml import YAML + from ruamel.yaml import YAML # type: ignore yamldoc = dedent("""\ --- @@ -710,10 +712,10 @@ class TestIssues: yaml.dump(data, buf) assert buf.getvalue() == yamldoc - def test_issue_290(self): + def test_issue_290(self) -> None: import sys from ruamel.yaml.compat import StringIO - from ruamel.yaml import YAML + from ruamel.yaml import YAML # type: ignore yamldoc = dedent("""\ --- @@ -746,10 +748,10 @@ class TestIssues: yaml.dump(data, buf) assert buf.getvalue() == yamldoc - def test_issue_290a(self): + def test_issue_290a(self) -> None: import sys from ruamel.yaml.compat import StringIO - from ruamel.yaml import YAML + from ruamel.yaml import YAML # type: ignore yamldoc = dedent("""\ --- @@ -783,7 +785,7 @@ class TestIssues: assert buf.getvalue() == yamldoc # @pytest.mark.xfail(strict=True, reason='should fail pre 0.15.100', raises=AssertionError) - def test_issue_295(self): + def test_issue_295(self) -> None: # deepcopy also makes a copy of the start and end mark, and these did not # have any comparison beyond their ID, which of course changed, breaking # some old merge_comment code @@ -808,8 +810,8 @@ class TestIssues: dc = copy.deepcopy(data) assert round_trip_dump(dc) == inp - def test_issue_300(self): - from ruamel.yaml import YAML + def test_issue_300(self) -> None: + from ruamel.yaml import YAML # type: ignore inp = dedent(""" %YAML 1.2 @@ -819,7 +821,7 @@ class TestIssues: """) YAML().load(inp) - def test_issue_300a(self): + def test_issue_300a(self) -> None: import ruamel.yaml inp = dedent(""" @@ -833,7 +835,7 @@ class TestIssues: match='while scanning a directive'): yaml.load(inp) - def test_issue_304(self): + def test_issue_304(self) -> None: inp = """ %YAML 1.2 %TAG ! tag:example.com,2019: @@ -843,7 +845,7 @@ class TestIssues: """ d = na_round_trip(inp) # NOQA - def test_issue_305(self): + def test_issue_305(self) -> None: inp = """ %YAML 1.2 --- @@ -852,7 +854,7 @@ class TestIssues: """ d = na_round_trip(inp) # NOQA - def test_issue_307(self): + def test_issue_307(self) -> None: inp = """ %YAML 1.2 %TAG ! tag:example.com,2019/path# @@ -863,7 +865,7 @@ class TestIssues: d = na_round_trip(inp) # NOQA # @pytest.mark.xfail(strict=True, reason='bla bla', raises=AssertionError) -# def test_issue_ xxx(self): +# def test_issue_ xxx(self) -> None: # inp = """ # """ # d = round_trip(inp) # NOQA diff --git a/_test/test_json_numbers.py b/_test/test_json_numbers.py index d89453c..08f39d0 100644 --- a/_test/test_json_numbers.py +++ b/_test/test_json_numbers.py @@ -1,11 +1,13 @@ # coding: utf-8 -import pytest # NOQA +import pytest # type: ignore # NOQA import json +from typing import Any -def load(s, typ=float): + +def load(s: str, typ: Any = float) -> float: import ruamel.yaml yaml = ruamel.yaml.YAML() @@ -16,7 +18,7 @@ def load(s, typ=float): assert isinstance(res['low'], typ) ret_val = yaml.load(x) print(ret_val) - return ret_val['low'] + return ret_val['low'] # type: ignore class TestJSONNumbers: @@ -26,7 +28,7 @@ class TestJSONNumbers: # -? [1-9] ( \. [0-9]* [1-9] )? ( e [-+] [1-9] [0-9]* )? # # which is not a superset of the JSON numbers - def test_json_number_float(self): + def test_json_number_float(self) -> None: for x in ( y.split('#')[0].strip() for y in """ @@ -43,7 +45,7 @@ class TestJSONNumbers: res = load(x) assert isinstance(res, float) - def test_json_number_int(self): + def test_json_number_int(self) -> None: for x in ( y.split('#')[0].strip() for y in """ diff --git a/_test/test_line_col.py b/_test/test_line_col.py index febe9c2..5ba125e 100644 --- a/_test/test_line_col.py +++ b/_test/test_line_col.py @@ -1,16 +1,18 @@ # coding: utf-8 -import pytest # NOQA +import pytest # type: ignore # NOQA from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NOQA +from typing import Any -def load(s): + +def load(s: str) -> Any: return round_trip_load(dedent(s)) class TestLineCol: - def test_item_00(self): + def test_item_00(self) -> None: data = load(""" - a - e @@ -20,7 +22,7 @@ class TestLineCol: assert data[2].lc.line == 2 assert data[2].lc.col == 2 - def test_item_01(self): + def test_item_01(self) -> None: data = load(""" - a - e @@ -30,7 +32,7 @@ class TestLineCol: assert data[2].lc.line == 2 assert data[2].lc.col == 2 - def test_item_02(self): + def test_item_02(self) -> None: data = load(""" - a - e @@ -40,7 +42,7 @@ class TestLineCol: assert data[2].lc.line == 2 assert data[2].lc.col == 2 - def test_item_03(self): + def test_item_03(self) -> None: data = load(""" - a - e @@ -52,7 +54,7 @@ class TestLineCol: assert data[2].lc.line == 2 assert data[2].lc.col == 2 - def test_item_04(self): + def test_item_04(self) -> None: data = load(""" # testing line and column based on SO # http://stackoverflow.com/questions/13319067/ @@ -66,7 +68,7 @@ class TestLineCol: assert data[1].lc.line == 4 assert data[1].lc.col == 2 - def test_pos_mapping(self): + def test_pos_mapping(self) -> None: data = load(""" a: 1 b: 2 @@ -78,7 +80,7 @@ class TestLineCol: assert data.lc.key('klm') == (4, 0) assert data.lc.value('klm') == (4, 5) - def test_pos_sequence(self): + def test_pos_sequence(self) -> None: data = load(""" - a - b diff --git a/_test/test_literal.py b/_test/test_literal.py index 7192207..0cf34bc 100644 --- a/_test/test_literal.py +++ b/_test/test_literal.py @@ -1,6 +1,6 @@ # coding: utf-8 -import pytest # NOQA +import pytest # type: ignore # NOQA from roundtrip import YAML # does an automatic dedent on load @@ -27,7 +27,7 @@ YAML 1.2 is again clear about root literal level scalar after directive in examp class TestNoIndent: - def test_root_literal_scalar_indent_example_9_5(self): + def test_root_literal_scalar_indent_example_9_5(self) -> None: yaml = YAML() s = '%!PS-Adobe-2.0' inp = """ @@ -38,7 +38,7 @@ class TestNoIndent: print(d) assert d == s + '\n' - def test_root_literal_scalar_no_indent(self): + def test_root_literal_scalar_no_indent(self) -> None: yaml = YAML() s = 'testing123' inp = """ @@ -49,7 +49,7 @@ class TestNoIndent: print(d) assert d == s + '\n' - def test_root_literal_scalar_no_indent_1_1(self): + def test_root_literal_scalar_no_indent_1_1(self) -> None: yaml = YAML() s = 'testing123' inp = """ @@ -61,9 +61,9 @@ class TestNoIndent: print(d) assert d == s + '\n' - def test_root_literal_scalar_no_indent_1_1_old_style(self): + def test_root_literal_scalar_no_indent_1_1_old_style(self) -> None: from textwrap import dedent - from ruamel.yaml import YAML + from ruamel.yaml import YAML # type: ignore yaml = YAML(typ='safe', pure=True) s = 'testing123' @@ -76,7 +76,7 @@ class TestNoIndent: print(d) assert d == s + '\n' - def test_root_literal_scalar_no_indent_1_1_no_raise(self): + def test_root_literal_scalar_no_indent_1_1_no_raise(self) -> None: # from ruamel.yaml.parser import ParserError yaml = YAML() @@ -91,7 +91,7 @@ class TestNoIndent: """ yaml.load(inp.format(s)) - def test_root_literal_scalar_indent_offset_one(self): + def test_root_literal_scalar_indent_offset_one(self) -> None: yaml = YAML() s = 'testing123' inp = """ @@ -102,7 +102,7 @@ class TestNoIndent: print(d) assert d == s + '\n' - def test_root_literal_scalar_indent_offset_four(self): + def test_root_literal_scalar_indent_offset_four(self) -> None: yaml = YAML() s = 'testing123' inp = """ @@ -113,7 +113,7 @@ class TestNoIndent: print(d) assert d == s + '\n' - def test_root_literal_scalar_indent_offset_two_leading_space(self): + def test_root_literal_scalar_indent_offset_two_leading_space(self) -> None: yaml = YAML() s = ' testing123' inp = """ @@ -125,7 +125,7 @@ class TestNoIndent: print(d) assert d == (s + '\n') * 2 - def test_root_literal_scalar_no_indent_special(self): + def test_root_literal_scalar_no_indent_special(self) -> None: yaml = YAML() s = '%!PS-Adobe-2.0' inp = """ @@ -136,7 +136,7 @@ class TestNoIndent: print(d) assert d == s + '\n' - def test_root_folding_scalar_indent(self): + def test_root_folding_scalar_indent(self) -> None: yaml = YAML() s = '%!PS-Adobe-2.0' inp = """ @@ -147,7 +147,7 @@ class TestNoIndent: print(d) assert d == s + '\n' - def test_root_folding_scalar_no_indent(self): + def test_root_folding_scalar_no_indent(self) -> None: yaml = YAML() s = 'testing123' inp = """ @@ -158,7 +158,7 @@ class TestNoIndent: print(d) assert d == s + '\n' - def test_root_folding_scalar_no_indent_special(self): + def test_root_folding_scalar_no_indent_special(self) -> None: yaml = YAML() s = '%!PS-Adobe-2.0' inp = """ @@ -169,7 +169,7 @@ class TestNoIndent: print(d) assert d == s + '\n' - def test_root_literal_multi_doc(self): + def test_root_literal_multi_doc(self) -> None: yaml = YAML(typ='safe', pure=True) s1 = 'abc' s2 = 'klm' @@ -183,7 +183,7 @@ class TestNoIndent: print('d1:', d1) assert ['abc', 'klm\n'][idx] == d1 - def test_root_literal_doc_indent_directives_end(self): + def test_root_literal_doc_indent_directives_end(self) -> None: yaml = YAML() yaml.explicit_start = True inp = """ @@ -194,7 +194,7 @@ class TestNoIndent: """ yaml.round_trip(inp) - def test_root_literal_doc_indent_document_end(self): + def test_root_literal_doc_indent_document_end(self) -> None: yaml = YAML() yaml.explicit_start = True inp = """ @@ -205,7 +205,7 @@ class TestNoIndent: """ yaml.round_trip(inp) - def test_root_literal_doc_indent_marker(self): + def test_root_literal_doc_indent_marker(self) -> None: yaml = YAML() yaml.explicit_start = True inp = """ @@ -217,7 +217,7 @@ class TestNoIndent: print(type(d), repr(d)) yaml.round_trip(inp) - def test_nested_literal_doc_indent_marker(self): + def test_nested_literal_doc_indent_marker(self) -> None: yaml = YAML() yaml.explicit_start = True inp = """ @@ -232,7 +232,7 @@ class TestNoIndent: class Test_RoundTripLiteral: - def test_rt_root_literal_scalar_no_indent(self): + def test_rt_root_literal_scalar_no_indent(self) -> None: yaml = YAML() yaml.explicit_start = True s = 'testing123' @@ -244,7 +244,7 @@ class Test_RoundTripLiteral: d = yaml.load(ys) yaml.dump(d, compare=ys) - def test_rt_root_literal_scalar_indent(self): + def test_rt_root_literal_scalar_indent(self) -> None: yaml = YAML() yaml.explicit_start = True yaml.indent = 4 @@ -257,7 +257,7 @@ class Test_RoundTripLiteral: d = yaml.load(ys) yaml.dump(d, compare=ys) - def test_rt_root_plain_scalar_no_indent(self): + def test_rt_root_plain_scalar_no_indent(self) -> None: yaml = YAML() yaml.explicit_start = True yaml.indent = 0 @@ -270,7 +270,7 @@ class Test_RoundTripLiteral: d = yaml.load(ys) yaml.dump(d, compare=ys) - def test_rt_root_plain_scalar_expl_indent(self): + def test_rt_root_plain_scalar_expl_indent(self) -> None: yaml = YAML() yaml.explicit_start = True yaml.indent = 4 @@ -283,7 +283,7 @@ class Test_RoundTripLiteral: d = yaml.load(ys) yaml.dump(d, compare=ys) - def test_rt_root_sq_scalar_expl_indent(self): + def test_rt_root_sq_scalar_expl_indent(self) -> None: yaml = YAML() yaml.explicit_start = True yaml.indent = 4 @@ -296,7 +296,7 @@ class Test_RoundTripLiteral: d = yaml.load(ys) yaml.dump(d, compare=ys) - def test_rt_root_dq_scalar_expl_indent(self): + def test_rt_root_dq_scalar_expl_indent(self) -> None: # if yaml.indent is the default (None) # then write after the directive indicator yaml = YAML() @@ -311,7 +311,7 @@ class Test_RoundTripLiteral: d = yaml.load(ys) yaml.dump(d, compare=ys) - def test_rt_root_literal_scalar_no_indent_no_eol(self): + def test_rt_root_literal_scalar_no_indent_no_eol(self) -> None: yaml = YAML() yaml.explicit_start = True s = 'testing123' @@ -323,7 +323,7 @@ class Test_RoundTripLiteral: d = yaml.load(ys) yaml.dump(d, compare=ys) - def test_rt_non_root_literal_scalar(self): + def test_rt_non_root_literal_scalar(self) -> None: yaml = YAML() s = 'testing123' ys = """ diff --git a/_test/test_none.py b/_test/test_none.py index 42aef4c..e11de17 100644 --- a/_test/test_none.py +++ b/_test/test_none.py @@ -1,39 +1,39 @@ # coding: utf-8 -import pytest # NOQA +import pytest # type: ignore # NOQA from roundtrip import round_trip_load, round_trip_dump class TestNone: - def test_dump00(self): + def test_dump00(self) -> None: data = None s = round_trip_dump(data) assert s == 'null\n...\n' d = round_trip_load(s) assert d == data - def test_dump01(self): + def test_dump01(self) -> None: data = None s = round_trip_dump(data, explicit_end=True) assert s == 'null\n...\n' d = round_trip_load(s) assert d == data - def test_dump02(self): + def test_dump02(self) -> None: data = None s = round_trip_dump(data, explicit_end=False) assert s == 'null\n...\n' d = round_trip_load(s) assert d == data - def test_dump03(self): + def test_dump03(self) -> None: data = None s = round_trip_dump(data, explicit_start=True) assert s == '---\n...\n' d = round_trip_load(s) assert d == data - def test_dump04(self): + def test_dump04(self) -> None: data = None s = 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 573f0bd..24eb768 100644 --- a/_test/test_numpy.py +++ b/_test/test_numpy.py @@ -1,22 +1,24 @@ # coding: utf-8 -try: - import numpy -except: # NOQA - numpy = None +# try: +# import numpy +# except: # NOQA +# numpy = None -def Xtest_numpy(): - import ruamel.yaml - - if numpy is None: - return - data = numpy.arange(10) - print('data', type(data), data) - - yaml_str = ruamel.yaml.dump(data) - datb = ruamel.yaml.load(yaml_str) - print('datb', type(datb), datb) - - print('\nYAML', yaml_str) - assert data == datb +# def Xtest_numpy() -> None: +# import ruamel.yaml +# +# if numpy is None: +# return +# data = numpy.arange(10) +# print('data', type(data), data) +# +# buf = io.BytesIO() +# ruamel.yaml.dump(data) # needs updating to use buffer +# yaml_str = buf.getvalue().decode('utf-8') +# datb = ruamel.yaml.load(yaml_str) +# print('datb', type(datb), datb) +# +# print('\nYAML', yaml_str) +# assert data == datb diff --git a/_test/test_program_config.py b/_test/test_program_config.py index 821ca15..6c5cad8 100644 --- a/_test/test_program_config.py +++ b/_test/test_program_config.py @@ -1,13 +1,13 @@ # coding: utf-8 -import pytest # NOQA +import pytest # type: ignore # NOQA # import ruamel.yaml from roundtrip import round_trip class TestProgramConfig: - def test_application_arguments(self): + def test_application_arguments(self) -> None: # application configur round_trip(""" args: @@ -20,7 +20,7 @@ class TestProgramConfig: wait: 10 """) - def test_single(self): + def test_single(self) -> None: # application configuration round_trip(""" # default arguments for the program @@ -39,7 +39,7 @@ class TestProgramConfig: # no more argument info to pass """) - def test_multi(self): + def test_multi(self) -> None: # application configuration round_trip(""" # default arguments for the program diff --git a/_test/test_spec_examples.py b/_test/test_spec_examples.py index cead787..7faa4bf 100644 --- a/_test/test_spec_examples.py +++ b/_test/test_spec_examples.py @@ -1,10 +1,10 @@ # coding: utf-8 from roundtrip import YAML -import pytest # NOQA +import pytest # type: ignore # NOQA -def test_example_2_1(): +def test_example_2_1() -> None: yaml = YAML() yaml.round_trip(""" - Mark McGwire @@ -13,8 +13,8 @@ def test_example_2_1(): """) -@pytest.mark.xfail(strict=True) -def test_example_2_2(): +@pytest.mark.xfail(strict=True) # type: ignore +def test_example_2_2() -> None: yaml = YAML() yaml.mapping_value_align = True yaml.round_trip(""" @@ -24,7 +24,7 @@ def test_example_2_2(): """) -def test_example_2_3(): +def test_example_2_3() -> None: yaml = YAML() yaml.indent(sequence=4, offset=2) yaml.round_trip(""" @@ -39,8 +39,8 @@ def test_example_2_3(): """) -@pytest.mark.xfail(strict=True) -def test_example_2_4(): +@pytest.mark.xfail(strict=True) # type: ignore +def test_example_2_4() -> None: yaml = YAML() yaml.mapping_value_align = True yaml.round_trip(""" @@ -55,8 +55,8 @@ def test_example_2_4(): """) -@pytest.mark.xfail(strict=True) -def test_example_2_5(): +@pytest.mark.xfail(strict=True) # type: ignore +def test_example_2_5() -> None: yaml = YAML() yaml.flow_sequence_element_align = True yaml.round_trip(""" @@ -66,8 +66,8 @@ def test_example_2_5(): """) -@pytest.mark.xfail(strict=True) -def test_example_2_6(): +@pytest.mark.xfail(strict=True) # type: ignore +def test_example_2_6() -> None: yaml = YAML() # yaml.flow_mapping_final_comma = False yaml.flow_mapping_one_element_per_line = True @@ -80,8 +80,8 @@ def test_example_2_6(): """) -@pytest.mark.xfail(strict=True) -def test_example_2_7(): +@pytest.mark.xfail(strict=True) # type: ignore +def test_example_2_7() -> None: yaml = YAML() yaml.round_trip_all(""" # Ranking of 1998 home runs @@ -97,7 +97,7 @@ def test_example_2_7(): """) -def test_example_2_8(): +def test_example_2_8() -> None: yaml = YAML() yaml.explicit_start = True yaml.explicit_end = True @@ -115,7 +115,7 @@ def test_example_2_8(): """) -def test_example_2_9(): +def test_example_2_9() -> None: yaml = YAML() yaml.explicit_start = True yaml.indent(sequence=4, offset=2) @@ -131,8 +131,8 @@ def test_example_2_9(): """) -@pytest.mark.xfail(strict=True) -def test_example_2_10(): +@pytest.mark.xfail(strict=True) # type: ignore +def test_example_2_10() -> None: yaml = YAML() yaml.explicit_start = True yaml.indent(sequence=4, offset=2) @@ -148,8 +148,8 @@ def test_example_2_10(): """) -@pytest.mark.xfail(strict=True) -def test_example_2_11(): +@pytest.mark.xfail(strict=True) # type: ignore +def test_example_2_11() -> None: yaml = YAML() yaml.round_trip(""" ? - Detroit Tigers @@ -164,8 +164,8 @@ def test_example_2_11(): """) -@pytest.mark.xfail(strict=True) -def test_example_2_12(): +@pytest.mark.xfail(strict=True) # type: ignore +def test_example_2_12() -> None: yaml = YAML() yaml.explicit_start = True yaml.round_trip(""" @@ -180,8 +180,8 @@ def test_example_2_12(): """) -@pytest.mark.xfail(strict=True) -def test_example_2_13(): +@pytest.mark.xfail(strict=True) # type: ignore +def test_example_2_13() -> None: yaml = YAML() yaml.round_trip(r""" # ASCII Art @@ -191,8 +191,8 @@ def test_example_2_13(): """) -@pytest.mark.xfail(strict=True) -def test_example_2_14(): +@pytest.mark.xfail(strict=True) # type: ignore +def test_example_2_14() -> None: yaml = YAML() yaml.explicit_start = True yaml.indent(root_scalar=2) # needs to be added @@ -204,8 +204,8 @@ def test_example_2_14(): """) -@pytest.mark.xfail(strict=True) -def test_example_2_15(): +@pytest.mark.xfail(strict=True) # type: ignore +def test_example_2_15() -> None: yaml = YAML() yaml.round_trip(""" > @@ -219,7 +219,7 @@ def test_example_2_15(): """) -def test_example_2_16(): +def test_example_2_16() -> None: yaml = YAML() yaml.round_trip(""" name: Mark McGwire @@ -232,10 +232,10 @@ def test_example_2_16(): """) -@pytest.mark.xfail( +@pytest.mark.xfail( # type: ignore strict=True, reason='cannot YAML dump escape sequences (\n) as hex and normal' ) -def test_example_2_17(): +def test_example_2_17() -> None: yaml = YAML() yaml.allow_unicode = False yaml.preserve_quotes = True @@ -250,8 +250,9 @@ def test_example_2_17(): """) -@pytest.mark.xfail(strict=True, reason='non-literal/folding multiline scalars not supported') -def test_example_2_18(): +@pytest.mark.xfail(strict=True, # type: ignore # NOQA + reason='non-literal/folding multiline scalars not supported') +def test_example_2_18() -> None: yaml = YAML() yaml.round_trip(""" plain: @@ -263,8 +264,8 @@ def test_example_2_18(): """) -@pytest.mark.xfail(strict=True, reason='leading + on decimal dropped') -def test_example_2_19(): +@pytest.mark.xfail(strict=True, reason='leading + on decimal dropped') # type: ignore +def test_example_2_19() -> None: yaml = YAML() yaml.round_trip(""" canonical: 12345 @@ -274,8 +275,8 @@ def test_example_2_19(): """) -@pytest.mark.xfail(strict=True, reason='case of NaN not preserved') -def test_example_2_20(): +@pytest.mark.xfail(strict=True, reason='case of NaN not preserved') # type: ignore +def test_example_2_20() -> None: yaml = YAML() yaml.round_trip(""" canonical: 1.23015e+3 @@ -286,7 +287,7 @@ def test_example_2_20(): """) -def Xtest_example_2_X(): +def Xtest_example_2_X() -> None: yaml = YAML() yaml.round_trip(""" """) diff --git a/_test/test_string.py b/_test/test_string.py index 7c10fd4..75890d2 100644 --- a/_test/test_string.py +++ b/_test/test_string.py @@ -13,7 +13,7 @@ and the chomping modifiers: """ -import pytest +import pytest # type: ignore import platform # from ruamel.yaml.compat import ordereddict @@ -21,20 +21,20 @@ from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NO class TestLiteralScalarString: - def test_basic_string(self): + def test_basic_string(self) -> None: round_trip(""" a: abcdefg """) - def test_quoted_integer_string(self): + def test_quoted_integer_string(self) -> None: round_trip(""" a: '12345' """) - @pytest.mark.skipif( + @pytest.mark.skipif( # type: ignore platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' ) - def test_preserve_string(self): + def test_preserve_string(self) -> None: inp = """ a: | abc @@ -42,10 +42,10 @@ class TestLiteralScalarString: """ round_trip(inp, intermediate=dict(a='abc\ndef\n')) - @pytest.mark.skipif( + @pytest.mark.skipif( # type: ignore platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' ) - def test_preserve_string_strip(self): + def test_preserve_string_strip(self) -> None: s = """ a: |- abc @@ -54,10 +54,10 @@ class TestLiteralScalarString: """ round_trip(s, intermediate=dict(a='abc\ndef')) - @pytest.mark.skipif( + @pytest.mark.skipif( # type: ignore platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' ) - def test_preserve_string_keep(self): + def test_preserve_string_keep(self) -> None: # with pytest.raises(AssertionError) as excinfo: inp = """ a: |+ @@ -69,10 +69,10 @@ class TestLiteralScalarString: """ round_trip(inp, intermediate=dict(a='ghi\njkl\n\n\n', b='x')) - @pytest.mark.skipif( + @pytest.mark.skipif( # type: ignore platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' ) - def test_preserve_string_keep_at_end(self): + def test_preserve_string_keep_at_end(self) -> None: # at EOF you have to specify the ... to get proper "closure" # of the multiline scalar inp = """ @@ -84,7 +84,7 @@ class TestLiteralScalarString: """ round_trip(inp, intermediate=dict(a='ghi\njkl\n\n')) - def test_fold_string(self): + def test_fold_string(self) -> None: inp = """ a: > abc @@ -93,7 +93,7 @@ class TestLiteralScalarString: """ round_trip(inp) - def test_fold_string_strip(self): + def test_fold_string_strip(self) -> None: inp = """ a: >- abc @@ -102,7 +102,7 @@ class TestLiteralScalarString: """ round_trip(inp) - def test_fold_string_keep(self): + def test_fold_string_keep(self) -> None: with pytest.raises(AssertionError) as excinfo: # NOQA inp = """ a: >+ @@ -114,19 +114,19 @@ class TestLiteralScalarString: class TestQuotedScalarString: - def test_single_quoted_string(self): + def test_single_quoted_string(self) -> None: inp = """ a: 'abc' """ round_trip(inp, preserve_quotes=True) - def test_double_quoted_string(self): + def test_double_quoted_string(self) -> None: inp = """ a: "abc" """ round_trip(inp, preserve_quotes=True) - def test_non_preserved_double_quoted_string(self): + def test_non_preserved_double_quoted_string(self) -> None: inp = """ a: "abc" """ @@ -139,7 +139,7 @@ class TestQuotedScalarString: class TestReplace: """inspired by issue 110 from sandres23""" - def test_replace_preserved_scalar_string(self): + def test_replace_preserved_scalar_string(self) -> None: import ruamel s = dedent("""\ @@ -159,7 +159,7 @@ class TestReplace: foo """) - def test_replace_double_quoted_scalar_string(self): + def test_replace_double_quoted_scalar_string(self) -> None: import ruamel s = dedent("""\ @@ -172,7 +172,7 @@ class TestReplace: class TestWalkTree: - def test_basic(self): + def test_basic(self) -> None: from ruamel.yaml.comments import CommentedMap from ruamel.yaml.scalarstring import walk_tree @@ -188,7 +188,7 @@ class TestWalkTree: """ assert round_trip_dump(data) == dedent(exp) - def test_map(self): + def test_map(self) -> None: from ruamel.yaml.compat import ordereddict from ruamel.yaml.comments import CommentedMap from ruamel.yaml.scalarstring import walk_tree, preserve_literal diff --git a/_test/test_tag.py b/_test/test_tag.py index 3fd1e05..bb20621 100644 --- a/_test/test_tag.py +++ b/_test/test_tag.py @@ -1,20 +1,21 @@ # coding: utf-8 -import pytest # NOQA +import pytest # type: ignore # NOQA +from typing import Any from roundtrip import round_trip, round_trip_load, YAML -def register_xxx(**kw): +def register_xxx(**kw: Any) -> None: from ruamel import yaml class XXX(yaml.comments.CommentedMap): @staticmethod - def yaml_dump(dumper, data): + def yaml_dump(dumper: Any, data: Any) -> Any: return dumper.represent_mapping('!xxx', data) @classmethod - def yaml_load(cls, constructor, node): + def yaml_load(cls, constructor: Any, node: Any) -> Any: data = cls() yield data constructor.construct_mapping(node, data) @@ -24,7 +25,7 @@ def register_xxx(**kw): class TestIndentFailures: - def test_tag(self): + def test_tag(self) -> None: round_trip("""\ !!python/object:__main__.Developer name: Anthon @@ -32,7 +33,7 @@ class TestIndentFailures: language: python """) - def test_full_tag(self): + def test_full_tag(self) -> None: round_trip("""\ !!tag:yaml.org,2002:python/object:__main__.Developer name: Anthon @@ -40,7 +41,7 @@ class TestIndentFailures: language: python """) - def test_standard_tag(self): + def test_standard_tag(self) -> None: round_trip("""\ !!tag:yaml.org,2002:python/object:map name: Anthon @@ -48,7 +49,7 @@ class TestIndentFailures: language: python """) - def test_Y1(self): + def test_Y1(self) -> None: round_trip("""\ !yyy name: Anthon @@ -56,7 +57,7 @@ class TestIndentFailures: language: python """) - def test_Y2(self): + def test_Y2(self) -> None: round_trip("""\ !!yyy name: Anthon @@ -66,7 +67,7 @@ class TestIndentFailures: class TestRoundTripCustom: - def test_X1(self): + def test_X1(self) -> None: register_xxx() round_trip("""\ !xxx @@ -75,8 +76,8 @@ class TestRoundTripCustom: language: python """) - @pytest.mark.xfail(strict=True) - def test_X_pre_tag_comment(self): + @pytest.mark.xfail(strict=True) # type: ignore + def test_X_pre_tag_comment(self) -> None: register_xxx() round_trip("""\ - @@ -87,8 +88,8 @@ class TestRoundTripCustom: language: python """) - @pytest.mark.xfail(strict=True) - def test_X_post_tag_comment(self): + @pytest.mark.xfail(strict=True) # type: ignore + def test_X_post_tag_comment(self) -> None: register_xxx() round_trip("""\ - !xxx @@ -98,7 +99,7 @@ class TestRoundTripCustom: language: python """) - def test_scalar_00(self): + def test_scalar_00(self) -> None: # https://stackoverflow.com/a/45967047/1307905 round_trip("""\ Outputs: @@ -110,24 +111,35 @@ class TestRoundTripCustom: class TestIssue201: - def test_encoded_unicode_tag(self): + def test_encoded_unicode_tag(self) -> None: round_trip_load(""" s: !!python/%75nicode 'abc' """) class TestImplicitTaggedNodes: - def test_scalar(self): - round_trip("""\ - - !Scalar abcdefg + def test_scalar(self) -> None: + data = round_trip("""\ + - !SString abcdefg + - !SFloat 1.0 + - !SInt 1961 + - !SBool true + - !SLit | + glitter in the dark near the Tanhäuser gate """) - - def test_mapping(self): + # tagged scalers have string or string types as value + assert data[0].count('d') == 1 + assert data[1].count('1') == 1 + assert data[2].count('1') == 2 + assert data[3].count('u') == 1 + assert data[4].count('a') == 4 + + def test_mapping(self) -> None: round_trip("""\ - !Mapping {a: 1, b: 2} """) - def test_sequence(self): + def test_sequence(self) -> None: yaml = YAML() yaml.brace_single_entry_mapping_in_flow_sequence = True yaml.mapping_value_align = True @@ -135,7 +147,7 @@ class TestImplicitTaggedNodes: - !Sequence [a, {b: 1}, {c: {d: 3}}] """) - def test_sequence2(self): + def test_sequence2(self) -> None: yaml = YAML() yaml.mapping_value_align = True yaml.round_trip(""" diff --git a/_test/test_version.py b/_test/test_version.py index e110eed..b60b1dd 100644 --- a/_test/test_version.py +++ b/_test/test_version.py @@ -1,11 +1,12 @@ # coding: utf-8 -import pytest # NOQA +import pytest # type: ignore # NOQA +from typing import Any, Optional from roundtrip import dedent, round_trip, round_trip_load -def load(s, version=None): +def load(s: str, version: Optional[Any] = None) -> Any: import ruamel.yaml # NOQA yaml = ruamel.yaml.YAML() @@ -14,7 +15,7 @@ def load(s, version=None): class TestVersions: - def test_explicit_1_2(self): + def test_explicit_1_2(self) -> None: r = load("""\ %YAML 1.2 --- @@ -38,7 +39,7 @@ class TestVersions: assert r[7] == 'no' assert r[8] is True - def test_explicit_1_1(self): + def test_explicit_1_1(self) -> None: r = load("""\ %YAML 1.1 --- @@ -62,7 +63,7 @@ class TestVersions: assert r[7] is False assert r[8] is True - def test_implicit_1_2(self): + def test_implicit_1_2(self) -> None: r = load("""\ - 12:34:56 - 12:34:56.78 @@ -86,7 +87,7 @@ class TestVersions: assert r[8] == 'no' assert r[9] is True - def test_load_version_1_1(self): + def test_load_version_1_1(self) -> None: inp = """\ - 12:34:56 - 12:34:56.78 @@ -114,7 +115,7 @@ class TestVersions: class TestIssue62: # bitbucket issue 62, issue_62 - def test_00(self): + def test_00(self) -> None: import ruamel.yaml # NOQA s = dedent("""\ @@ -131,7 +132,7 @@ class TestIssue62: round_trip(s.format('%YAML 1.1\n---\n'), preserve_quotes=True) round_trip(s.format(""), preserve_quotes=True) - def test_00_single_comment(self): + def test_00_single_comment(self) -> None: import ruamel.yaml # NOQA s = dedent("""\ @@ -148,7 +149,7 @@ class TestIssue62: 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): + def test_01(self) -> None: import ruamel.yaml # NOQA s = dedent("""\ @@ -160,6 +161,6 @@ class TestIssue62: # note the flow seq on the --- line! round_trip(s.format('%YAML 1.2\n--- '), preserve_quotes=True, version='1.2') - def test_so_45681626(self): + def test_so_45681626(self) -> None: # was not properly parsing round_trip_load('{"in":{},"out":{}}') diff --git a/_test/test_yamlfile.py b/_test/test_yamlfile.py index f1de872..6f7aca7 100644 --- a/_test/test_yamlfile.py +++ b/_test/test_yamlfile.py @@ -6,20 +6,20 @@ various test cases for YAML files import sys import io -import pytest # NOQA +import pytest # type: ignore # NOQA import platform from roundtrip import round_trip, dedent, round_trip_load, round_trip_dump # NOQA class TestYAML: - def test_backslash(self): + def test_backslash(self) -> None: round_trip(""" handlers: static_files: applications/\\1/static/\\2 """) - def test_omap_out(self): + def test_omap_out(self) -> None: # ordereddict mapped to !!omap from ruamel.yaml.compat import ordereddict import ruamel.yaml # NOQA @@ -32,7 +32,7 @@ class TestYAML: - b: 2 """) - def test_omap_roundtrip(self): + def test_omap_roundtrip(self) -> None: round_trip(""" !!omap - a: 1 @@ -41,25 +41,26 @@ class TestYAML: - d: 4 """) - @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 = round_trip_dump(x, default_flow_style=False) - assert res == dedent(""" - !!omap - - a: 1 - - b: 2 - """) - - @pytest.mark.skipif( + # @pytest.mark.skipif(sys.version_info < (2, 7), + # reason='collections not available') + # def test_dump_collections_ordereddict(self) -> None: + # from collections import OrderedDict + # import ruamel.yaml # NOQA + + # # OrderedDict mapped to !!omap + # x = OrderedDict([('a', 1), ('b', 2)]) + # res = round_trip_dump(x, default_flow_style=False) + # assert res == dedent(""" + # !!omap + # - a: 1 + # - b: 2 + # """) + + @pytest.mark.skipif( # type: ignore sys.version_info >= (3, 0) or platform.python_implementation() != 'CPython', reason='ruamel.yaml not available', ) - def test_dump_ruamel_ordereddict(self): + def test_dump_ruamel_ordereddict(self) -> None: from ruamel.ordereddict import ordereddict import ruamel.yaml # NOQA @@ -72,7 +73,7 @@ class TestYAML: - b: 2 """) - def test_CommentedSet(self): + def test_CommentedSet(self) -> None: from ruamel.yaml.constructor import CommentedSet s = CommentedSet(['a', 'b', 'c']) @@ -84,7 +85,7 @@ class TestYAML: s.remove('e') assert s == CommentedSet(['a', 'c', 'd', 'f']) - def test_set_out(self): + def test_set_out(self) -> None: # preferable would be the shorter format without the ': null' import ruamel.yaml # NOQA @@ -102,7 +103,7 @@ class TestYAML: """) # ordering is not preserved in a set - def test_set_compact(self): + def test_set_compact(self) -> None: # this format is read and also should be written by default round_trip(""" !!set @@ -111,7 +112,7 @@ class TestYAML: ? c """) - def test_blank_line_after_comment(self): + def test_blank_line_after_comment(self) -> None: round_trip(""" # Comment with spaces after it. @@ -119,7 +120,7 @@ class TestYAML: a: 1 """) - def test_blank_line_between_seq_items(self): + def test_blank_line_between_seq_items(self) -> None: round_trip(""" # Seq with empty lines in between items. b: @@ -129,10 +130,10 @@ class TestYAML: - baz """) - @pytest.mark.skipif( + @pytest.mark.skipif( # type: ignore platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' ) - def test_blank_line_after_literal_chip(self): + def test_blank_line_after_literal_chip(self) -> None: s = """ c: - | @@ -153,10 +154,10 @@ class TestYAML: assert d['c'][0].split('it.')[1] == '\n' assert d['c'][1].split('line.')[1] == '\n' - @pytest.mark.skipif( + @pytest.mark.skipif( # type: ignore platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' ) - def test_blank_line_after_literal_keep(self): + def test_blank_line_after_literal_keep(self) -> None: """ have to insert an eof marker in YAML to test this""" s = """ c: @@ -179,10 +180,10 @@ class TestYAML: assert d['c'][0].split('it.')[1] == '\n\n' assert d['c'][1].split('line.')[1] == '\n\n\n' - @pytest.mark.skipif( + @pytest.mark.skipif( # type: ignore platform.python_implementation() == 'Jython', reason='Jython throws RepresenterError' ) - def test_blank_line_after_literal_strip(self): + def test_blank_line_after_literal_strip(self) -> None: s = """ c: - |- @@ -203,7 +204,7 @@ class TestYAML: assert d['c'][0].split('it.')[1] == "" assert d['c'][1].split('line.')[1] == "" - def test_load_all_perserve_quotes(self): + def test_load_all_perserve_quotes(self) -> None: import ruamel.yaml # NOQA yaml = ruamel.yaml.YAML() diff --git a/_test/test_yamlobject.py b/_test/test_yamlobject.py index 80fb213..3f488d3 100644 --- a/_test/test_yamlobject.py +++ b/_test/test_yamlobject.py @@ -1,12 +1,13 @@ # coding: utf-8 import sys -import pytest # NOQA +from typing import Any +import pytest # type: ignore # NOQA from roundtrip import save_and_run # NOQA -def test_monster(tmpdir): +def test_monster(tmpdir: Any) -> None: program_src = '''\ import ruamel.yaml from textwrap import dedent @@ -24,27 +25,33 @@ def test_monster(tmpdir): return "%s(name=%r, hp=%r, ac=%r, attacks=%r)" % ( self.__class__.__name__, self.name, self.hp, self.ac, self.attacks) - data = ruamel.yaml.load(dedent("""\\ + yaml = ruamel.yaml.YAML(typ='safe', pure='True') + yaml = ruamel.yaml.YAML() + data = yaml.load(dedent("""\\ --- !Monster name: Cave spider hp: [2,6] # 2d6 ac: 16 attacks: [BITE, HURT] - """), Loader=ruamel.yaml.Loader) + """)) # normal dump, keys will be sorted - assert ruamel.yaml.dump(data) == dedent("""\\ + from io import BytesIO + buf = BytesIO() + yaml.dump(data, buf) + print(buf.getvalue().decode('utf-8')) + assert buf.getvalue().decode('utf8') == dedent("""\\ !Monster + name: Cave spider + hp: [2, 6] # 2d6 ac: 16 attacks: [BITE, HURT] - hp: [2, 6] - name: Cave spider """) ''' assert save_and_run(program_src, tmpdir) == 0 -@pytest.mark.skipif(sys.version_info < (3, 0), reason='no __qualname__') -def test_qualified_name00(tmpdir): +@pytest.mark.skipif(sys.version_info < (3, 0), reason='no __qualname__') # type: ignore +def test_qualified_name00(tmpdir: Any) -> None: """issue 214""" program_src = """\ from ruamel.yaml import YAML @@ -67,8 +74,8 @@ def test_qualified_name00(tmpdir): assert save_and_run(program_src, tmpdir) == 0 -@pytest.mark.skipif(sys.version_info < (3, 0), reason='no __qualname__') -def test_qualified_name01(tmpdir): +@pytest.mark.skipif(sys.version_info < (3, 0), reason='no __qualname__') # type: ignore +def test_qualified_name01(tmpdir: Any) -> None: """issue 214""" from ruamel.yaml import YAML import ruamel.yaml.comments diff --git a/_test/test_z_check_debug_leftovers.py b/_test/test_z_check_debug_leftovers.py index f5be5df..7096a73 100644 --- a/_test/test_z_check_debug_leftovers.py +++ b/_test/test_z_check_debug_leftovers.py @@ -1,7 +1,8 @@ # coding: utf-8 import sys -import pytest # NOQA +from typing import Any +import pytest # type: ignore # NOQA from roundtrip import round_trip_load, round_trip_dump, dedent @@ -9,7 +10,7 @@ from roundtrip import round_trip_load, round_trip_dump, dedent 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): + def test_00(self, capsys: Any) -> None: s = dedent(""" a: 1 b: [] @@ -21,7 +22,7 @@ class TestLeftOverDebug: out, err = capsys.readouterr() assert out == s - def test_01(self, capsys): + def test_01(self, capsys: Any) -> None: s = dedent(""" - 1 - [] diff --git a/_test/test_z_data.py b/_test/test_z_data.py index 965eb3d..8a8ba21 100644 --- a/_test/test_z_data.py +++ b/_test/test_z_data.py @@ -2,19 +2,18 @@ import sys import os -import pytest # NOQA +import pytest # type: ignore # NOQA import warnings # NOQA +from typing import Any, Optional, List, Tuple from pathlib import Path -from ruamel.yaml.compat import _F - base_path = Path('data') # that is ruamel.yaml.data -class YAMLData(object): +class YAMLData: yaml_tag = '!YAML' - def __init__(self, s): + def __init__(self, s: Any) -> None: self._s = s # Conversion tables for input. E.g. "<TAB>" is replaced by "\t" @@ -28,9 +27,9 @@ class YAMLData(object): # fmt: on @property - def value(self): + def value(self) -> Any: if hasattr(self, '_p'): - return self._p + return self._p # type: ignore assert ' \n' not in self._s assert '\t\n' not in self._s self._p = self._s @@ -39,7 +38,7 @@ class YAMLData(object): self._p = self._p.replace(k, v) return self._p - def test_rewrite(self, s): + def test_rewrite(self, s: str) -> str: assert ' \n' not in s assert '\t\n' not in s for k, v in YAMLData.special.items(): @@ -48,7 +47,7 @@ class YAMLData(object): return s @classmethod - def from_yaml(cls, constructor, node): + def from_yaml(cls, constructor: Any, node: Any) -> 'YAMLData': from ruamel.yaml.nodes import MappingNode if isinstance(node, MappingNode): @@ -68,18 +67,18 @@ class Assert(YAMLData): yaml_tag = '!Assert' @property - def value(self): + def value(self) -> Any: from collections.abc import Mapping if hasattr(self, '_pa'): - return self._pa + return self._pa # type: ignore if isinstance(self._s, Mapping): - self._s['lines'] = self.test_rewrite(self._s['lines']) + self._s['lines'] = self.test_rewrite(self._s['lines']) # type: ignore self._pa = self._s return self._pa -def pytest_generate_tests(metafunc): +def pytest_generate_tests(metafunc: Any) -> None: test_yaml = [] paths = sorted(base_path.glob('**/*.yaml')) idlist = [] @@ -100,8 +99,8 @@ def pytest_generate_tests(metafunc): metafunc.parametrize(['yaml'], test_yaml, ids=idlist, scope='class') -class TestYAMLData(object): - def yaml(self, yaml_version=None): +class TestYAMLData: + def yaml(self, yaml_version: Optional[Any] = None) -> Any: from ruamel.yaml import YAML y = YAML() @@ -110,7 +109,7 @@ class TestYAMLData(object): y.version = yaml_version return y - def docs(self, path): + def docs(self, path: Path) -> List[Any]: from ruamel.yaml import YAML tyaml = YAML(typ='safe', pure=True) @@ -120,12 +119,14 @@ class TestYAMLData(object): tyaml.register_class(Assert) return list(tyaml.load_all(path)) - def yaml_load(self, value, yaml_version=None): + def yaml_load(self, value: Any, yaml_version: Optional[Any] = None) -> Tuple[Any, Any]: yaml = self.yaml(yaml_version=yaml_version) data = yaml.load(value) return yaml, data - def round_trip(self, input, output=None, yaml_version=None): + def round_trip( + self, input: Any, output: Optional[Any] = None, yaml_version: Optional[Any] = None + ) -> None: from ruamel.yaml.compat import StringIO yaml, data = self.yaml_load(input.value, yaml_version=yaml_version) @@ -133,9 +134,12 @@ class TestYAMLData(object): yaml.dump(data, buf) expected = input.value if output is None else output.value value = buf.getvalue() + print('>>>> rt output\n', value.replace(' ', '\u2423'), sep='') # 2423 open box assert value == expected - def load_assert(self, input, confirm, yaml_version=None): + def load_assert( + self, input: Any, confirm: Any, yaml_version: Optional[Any] = None + ) -> None: from collections.abc import Mapping d = self.yaml_load(input.value, yaml_version=yaml_version)[1] # NOQA @@ -154,14 +158,16 @@ class TestYAMLData(object): print(line) exec(line) - def run_python(self, python, data, tmpdir, input=None): + def run_python( + self, python: Any, data: Any, tmpdir: Any, input: Optional[Any] = None + ) -> None: from roundtrip import save_and_run if input is not None: (tmpdir / 'input.yaml').write_text(input.value, encoding='utf-8') assert save_and_run(python.value, base_dir=tmpdir, output=data.value) == 0 - def insert_comments(self, data, actions): + def insert_comments(self, data: Any, actions: Any) -> None: """this is to automatically insert based on: path (a.1.b), position (before, after, between), and @@ -180,7 +186,7 @@ class TestYAMLData(object): # this is executed by pytest the methods with names not starting with # test_ are helper methods - def test_yaml_data(self, yaml, tmpdir): + def test_yaml_data(self, yaml: Any, tmpdir: Any) -> None: from collections.abc import Mapping idx = 0 @@ -221,8 +227,8 @@ class TestYAMLData(object): typ = 'rt' print('type:', typ) if data is not None: - print('data:', data.value, end='') - print('output:', output.value if output is not None else output) + print('>>>> data:\n', data.value.replace(' ', '\u2423'), sep='', end='') + print('>>>> output:\n', output.value if output is not None else output, sep='') if typ == 'rt': self.round_trip(data, output, yaml_version=yaml_version) elif typ == 'python_run': @@ -231,14 +237,14 @@ class TestYAMLData(object): elif typ == 'load_assert': self.load_assert(data, confirm, yaml_version=yaml_version) elif typ == 'comment': - actions = [] + actions: List[Any] = [] self.insert_comments(data, actions) else: - _F('\n>>>>>> run type unknown: "{typ}" <<<<<<\n') + f'\n>>>>>> run type unknown: "{typ}" <<<<<<\n' raise AssertionError() -def check_python_version(match, current=None): +def check_python_version(match: Any, current: Optional[Any] = None) -> bool: """ version indication, return True if version matches. match should be something like 3.6+, or [2.7, 3.3] etc. Floats diff --git a/_test/test_z_olddata.py b/_test/test_z_olddata.py index 89b7053..ffe1572 100644 --- a/_test/test_z_olddata.py +++ b/_test/test_z_olddata.py @@ -2,31 +2,33 @@ import sys import os -import pytest # NOQA +import pytest # type: ignore # NOQA sys.path.insert(0, os.path.dirname(__file__) + '/lib') import warnings # NOQA +from typing import List, Any # NOQA -args = [] +args: List[Any] = [] -def test_data(): - import test_appliance # NOQA +def test_data() -> None: + import test_appliance # type: ignore # NOQA warnings.simplefilter('ignore', PendingDeprecationWarning) collections = [] - import test_yaml + import test_yaml # type: ignore collections.append(test_yaml) test_appliance.run(collections, args) + # @pytest.mark.skipif(not ruamel.yaml.__with_libyaml__, # reason="no libyaml") -def test_data_ext(): +def test_data_ext() -> None: collections = [] import ruamel.yaml # NOQA import test_appliance # NOQA @@ -34,7 +36,7 @@ def test_data_ext(): warnings.simplefilter('ignore', ruamel.yaml.error.UnsafeLoaderWarning) warnings.simplefilter('ignore', PendingDeprecationWarning) if ruamel.yaml.__with_libyaml__: - import test_yaml_ext + import test_yaml_ext # type: ignore collections.append(test_yaml_ext) test_appliance.run(collections, args) |