Debian Codegraph @

ansible_collections/cisco/meraki/tests/unit/mock/loader.py

raw
1 from __future__ import absolute_import, division, print_function
2
3
4 __metaclass__ = type
5
6 import os
7
8 from ansible.errors import AnsibleParserError
9 from ansible.module_utils._text import to_bytes, to_text
10 from ansible.parsing.dataloader import DataLoader
11
12
13 class DictDataLoader(DataLoader):
14 def __init__(self, file_mapping=None):
15 file_mapping = {} if file_mapping is None else file_mapping
16 assert isinstance(file_mapping, dict)
17
18 super(DictDataLoader, self).__init__()
19
20 self._file_mapping = file_mapping
21 self._build_known_directories()
22 self._vault_secrets = None
23
24 def load_from_file(self, path, cache=True, unsafe=False):
25 path = to_text(path)
26 if path in self._file_mapping:
27 return self.load(self._file_mapping[path], path)
28 return None
29
30 # TODO: the real _get_file_contents returns a bytestring, so we actually convert the
31 # unicode/text it's created with to utf-8
32 def _get_file_contents(self, file_name):
33 file_name = to_text(file_name)
34 if file_name in self._file_mapping:
35 return (to_bytes(self._file_mapping[file_name]), False)
36 else:
37 raise AnsibleParserError("file not found: %s" % file_name)
38
39 def path_exists(self, path):
40 path = to_text(path)
41 return path in self._file_mapping or path in self._known_directories
42
43 def is_file(self, path):
44 path = to_text(path)
45 return path in self._file_mapping
46
47 def is_directory(self, path):
48 path = to_text(path)
49 return path in self._known_directories
50
51 def list_directory(self, path):
52 ret = []
53 path = to_text(path)
54 for x in list(self._file_mapping.keys()) + self._known_directories:
55 if x.startswith(path):
56 if os.path.dirname(x) == path:
57 ret.append(os.path.basename(x))
58 return ret
59
60 def is_executable(self, path):
61 # FIXME: figure out a way to make paths return true for this
62 return False
63
64 def _add_known_directory(self, directory):
65 if directory not in self._known_directories:
66 self._known_directories.append(directory)
67
68 def _build_known_directories(self):
69 self._known_directories = []
70 for path in self._file_mapping:
71 dirname = os.path.dirname(path)
72 while dirname not in ("/", ""):
73 self._add_known_directory(dirname)
74 dirname = os.path.dirname(dirname)
75
76 def push(self, path, content):
77 rebuild_dirs = False
78 if path not in self._file_mapping:
79 rebuild_dirs = True
80
81 self._file_mapping[path] = content
82
83 if rebuild_dirs:
84 self._build_known_directories()
85
86 def pop(self, path):
87 if path in self._file_mapping:
88 del self._file_mapping[path]
89 self._build_known_directories()
90
91 def clear(self):
92 self._file_mapping = dict()
93 self._known_directories = []
94
95 def get_basedir(self):
96 return os.getcwd()
97
98 def set_vault_secrets(self, vault_secrets):
99 self._vault_secrets = vault_secrets