Debian Codegraph @

test/units/mock/yaml_helper.py

raw
1 from __future__ import annotations
2
3 import io
4 import yaml
5
6 from ansible.parsing.yaml.dumper import AnsibleDumper
7
8
9 class YamlTestUtils(object):
10 """Mixin class to combine with a unittest.TestCase subclass."""
11 def _loader(self, stream):
12 """Vault related tests will want to override this.
13
14 Vault cases should setup a AnsibleLoader that has the vault password."""
15
16 def _dump_stream(self, obj, stream, dumper=None):
17 """Dump to a py2-unicode or py3-string stream."""
18 return yaml.dump(obj, stream, Dumper=dumper)
19
20 def _dump_string(self, obj, dumper=None):
21 """Dump to a py2-unicode or py3-string"""
22 return yaml.dump(obj, Dumper=dumper)
23
24 def _dump_load_cycle(self, obj):
25 # Each pass though a dump or load revs the 'generation'
26 # obj to yaml string
27 string_from_object_dump = self._dump_string(obj, dumper=AnsibleDumper)
28
29 # wrap a stream/file like StringIO around that yaml
30 stream_from_object_dump = io.StringIO(string_from_object_dump)
31 loader = self._loader(stream_from_object_dump)
32 # load the yaml stream to create a new instance of the object (gen 2)
33 obj_2 = loader.get_data()
34
35 # dump the gen 2 objects directory to strings
36 string_from_object_dump_2 = self._dump_string(obj_2,
37 dumper=AnsibleDumper)
38
39 # The gen 1 and gen 2 yaml strings
40 self.assertEqual(string_from_object_dump, string_from_object_dump_2)
41 # the gen 1 (orig) and gen 2 py object
42 self.assertEqual(obj, obj_2)
43
44 # again! gen 3... load strings into py objects
45 stream_3 = io.StringIO(string_from_object_dump_2)
46 loader_3 = self._loader(stream_3)
47 obj_3 = loader_3.get_data()
48
49 string_from_object_dump_3 = self._dump_string(obj_3, dumper=AnsibleDumper)
50
51 self.assertEqual(obj, obj_3)
52 # should be transitive, but...
53 self.assertEqual(obj_2, obj_3)
54 self.assertEqual(string_from_object_dump, string_from_object_dump_3)