Debian Codegraph @

test/units/plugins/inventory/test_inventory.py

raw
1 # Copyright 2015 Abhijit Menon-Sen <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 import string
21 import textwrap
22
23 from unittest import mock
24
25 from ansible import constants as C
26 import unittest
27 from ansible.module_utils.common.text.converters import to_text
28 from units.mock.path import mock_unfrackpath_noop
29
30 from ansible.inventory.manager import InventoryManager, split_host_pattern
31
32 from units.mock.loader import DictDataLoader
33
34
35 class TestInventory(unittest.TestCase):
36
37 patterns = {
38 'a': ['a'],
39 'a, b': ['a', 'b'],
40 'a , b': ['a', 'b'],
41 ' a,b ,c[1:2] ': ['a', 'b', 'c[1:2]'],
42 '9a01:7f8:191:7701::9': ['9a01:7f8:191:7701::9'],
43 '9a01:7f8:191:7701::9,9a01:7f8:191:7701::9': ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9'],
44 '9a01:7f8:191:7701::9,9a01:7f8:191:7701::9,foo': ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9', 'foo'],
45 'foo[1:2]': ['foo[1:2]'],
46 'a::b': ['a::b'],
47 'a:b': ['a', 'b'],
48 ' a : b ': ['a', 'b'],
49 'foo:bar:baz[1:2]': ['foo', 'bar', 'baz[1:2]'],
50 'a,,b': ['a', 'b'],
51 'a, ,b,,c, ,': ['a', 'b', 'c'],
52 ',': [],
53 '': [],
54 }
55
56 pattern_lists = [
57 [['a'], ['a']],
58 [['a', 'b'], ['a', 'b']],
59 [['a, b'], ['a', 'b']],
60 [['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9,foo'],
61 ['9a01:7f8:191:7701::9', '9a01:7f8:191:7701::9', 'foo']]
62 ]
63
64 # pattern_string: [ ('base_pattern', (a,b)), ['x','y','z'] ]
65 # a,b are the bounds of the subscript; x..z are the results of the subscript
66 # when applied to string.ascii_letters.
67
68 subscripts = {
69 'a': [('a', None), list(string.ascii_letters)],
70 'a[0]': [('a', (0, None)), ['a']],
71 'a[1]': [('a', (1, None)), ['b']],
72 'a[2:3]': [('a', (2, 3)), ['c', 'd']],
73 'a[-1]': [('a', (-1, None)), ['Z']],
74 'a[-2]': [('a', (-2, None)), ['Y']],
75 'a[48:]': [('a', (48, -1)), ['W', 'X', 'Y', 'Z']],
76 'a[49:]': [('a', (49, -1)), ['X', 'Y', 'Z']],
77 'a[1:]': [('a', (1, -1)), list(string.ascii_letters[1:])],
78 }
79
80 ranges_to_expand = {
81 'a[1:2]': ['a1', 'a2'],
82 'a[1:10:2]': ['a1', 'a3', 'a5', 'a7', 'a9'],
83 'a[a:b]': ['aa', 'ab'],
84 'a[a:i:3]': ['aa', 'ad', 'ag'],
85 'a[a:b][c:d]': ['aac', 'aad', 'abc', 'abd'],
86 'a[0:1][2:3]': ['a02', 'a03', 'a12', 'a13'],
87 'a[a:b][2:3]': ['aa2', 'aa3', 'ab2', 'ab3'],
88 }
89
90 def setUp(self):
91 fake_loader = DictDataLoader({})
92
93 self.i = InventoryManager(loader=fake_loader, sources=[None])
94
95 def test_split_patterns(self):
96
97 for p in self.patterns:
98 r = self.patterns[p]
99 self.assertEqual(r, split_host_pattern(p))
100
101 for p, r in self.pattern_lists:
102 self.assertEqual(r, split_host_pattern(p))
103
104 def test_ranges(self):
105
106 for s in self.subscripts:
107 r = self.subscripts[s]
108 self.assertEqual(r[0], self.i._split_subscript(s))
109 self.assertEqual(
110 r[1],
111 self.i._apply_subscript(
112 list(string.ascii_letters),
113 r[0][1]
114 )
115 )
116
117
118 class TestInventoryPlugins(unittest.TestCase):
119
120 def test_empty_inventory(self):
121 inventory = self._get_inventory('')
122
123 self.assertIn('all', inventory.groups)
124 self.assertIn('ungrouped', inventory.groups)
125 self.assertFalse(inventory.groups['all'].get_hosts())
126 self.assertFalse(inventory.groups['ungrouped'].get_hosts())
127
128 def test_ini(self):
129 self._test_default_groups("""
130 host1
131 host2
132 host3
133 [servers]
134 host3
135 host4
136 host5
137 """)
138
139 def test_ini_explicit_ungrouped(self):
140 self._test_default_groups("""
141 [ungrouped]
142 host1
143 host2
144 host3
145 [servers]
146 host3
147 host4
148 host5
149 """)
150
151 def test_ini_variables_stringify(self):
152 values = ['string', 'no', 'No', 'false', 'FALSE', [], False, 0]
153
154 inventory_content = "host1 "
155 inventory_content += ' '.join(['var%s=%s' % (i, to_text(x)) for i, x in enumerate(values)])
156 inventory = self._get_inventory(inventory_content)
157
158 variables = inventory.get_host('host1').vars
159 for i in range(len(values)):
160 if isinstance(values[i], str):
161 self.assertIsInstance(variables['var%s' % i], str)
162 else:
163 self.assertIsInstance(variables['var%s' % i], type(values[i]))
164
165 @mock.patch('ansible.inventory.manager.unfrackpath', mock_unfrackpath_noop)
166 @mock.patch('os.path.exists', lambda x: True)
167 @mock.patch('os.access', lambda x, y: True)
168 def test_yaml_inventory(self, filename="test.yaml"):
169 inventory_content = {filename: textwrap.dedent("""\
170 ---
171 all:
172 hosts:
173 test1:
174 test2:
175 """)}
176 C.INVENTORY_ENABLED = ['yaml']
177 fake_loader = DictDataLoader(inventory_content)
178 im = InventoryManager(loader=fake_loader, sources=filename)
179 self.assertTrue(im._inventory.hosts)
180 self.assertIn('test1', im._inventory.hosts)
181 self.assertIn('test2', im._inventory.hosts)
182 self.assertIn(im._inventory.get_host('test1'), im._inventory.groups['all'].hosts)
183 self.assertIn(im._inventory.get_host('test2'), im._inventory.groups['all'].hosts)
184 self.assertEqual(len(im._inventory.groups['all'].hosts), 2)
185 self.assertIn(im._inventory.get_host('test1'), im._inventory.groups['ungrouped'].hosts)
186 self.assertIn(im._inventory.get_host('test2'), im._inventory.groups['ungrouped'].hosts)
187 self.assertEqual(len(im._inventory.groups['ungrouped'].hosts), 2)
188
189 def _get_inventory(self, inventory_content):
190
191 fake_loader = DictDataLoader({__file__: inventory_content})
192
193 return InventoryManager(loader=fake_loader, sources=[__file__])
194
195 def _test_default_groups(self, inventory_content):
196 inventory = self._get_inventory(inventory_content)
197
198 self.assertIn('all', inventory.groups)
199 self.assertIn('ungrouped', inventory.groups)
200 all_hosts = set(host.name for host in inventory.groups['all'].get_hosts())
201 self.assertEqual(set(['host1', 'host2', 'host3', 'host4', 'host5']), all_hosts)
202 ungrouped_hosts = set(host.name for host in inventory.groups['ungrouped'].get_hosts())
203 self.assertEqual(set(['host1', 'host2']), ungrouped_hosts)
204 servers_hosts = set(host.name for host in inventory.groups['servers'].get_hosts())
205 self.assertEqual(set(['host3', 'host4', 'host5']), servers_hosts)