def test_netplan_get_filename_by_id(self): file_a = os.path.join(self.workdir.name, 'etc/netplan/a.yaml') file_b = os.path.join(self.workdir.name, 'etc/netplan/b.yaml') with open(file_a, 'w') as f: f.write('network:\n ethernets:\n id_a:\n dhcp4: true') with open(file_b, 'w') as f: f.write('network:\n ethernets:\n id_b:\n dhcp4: true\n id_a:\n dhcp4: true') # netdef:b can only be found in b.yaml basename = os.path.basename(utils.netplan_get_filename_by_id('id_b', self.workdir.name)) self.assertEqual(basename, 'b.yaml') # netdef:a is defined in a.yaml, overriden by b.yaml basename = os.path.basename(utils.netplan_get_filename_by_id('id_a', self.workdir.name)) self.assertEqual(basename, 'b.yaml')
def test_netplan_get_filename_by_id_invalid(self): file = os.path.join(self.workdir.name, 'etc/netplan/a.yaml') with open(file, 'w') as f: f.write('''network: tunnels: id_a: mode: sit local: 0.0.0.0 remote: 0.0.0.0 key: 0.0.0.0''') self.assertIsNone(utils.netplan_get_filename_by_id('some-id', self.workdir.name))
def split_tree_by_hint(self, set_tree) -> (str, dict): network = set_tree.get('network', {}) # A mapping of 'origin-hint' -> YAML tree (one subtree per netdef) subtrees = dict() for devtype in network: if devtype in GLOBAL_KEYS: continue # special handling of global keys down below for netdef in network.get(devtype, []): hint = FALLBACK_HINT filename = utils.netplan_get_filename_by_id( netdef, self.root_dir) if filename: hint = os.path.basename( filename)[:-5] # strip prefix and .yaml netdef_tree = { 'network': { devtype: { netdef: network.get(devtype).get(netdef) } } } # Merge all netdef trees which are going to be written to the same file/hint subtrees[hint] = self.merge(subtrees.get(hint, {}), netdef_tree) # Merge GLOBAL_KEYS into one of the available subtrees # Write to same file (if only one hint/subtree is available) # Write to FALLBACK_HINT if multiple hints/subtrees are available, as we do not know where it is supposed to go if any(network.get(key) for key in GLOBAL_KEYS): # Write to the same file, if we have only one file-hint or to FALLBACK_HINT otherwise hint = list(subtrees)[0] if len(subtrees) == 1 else FALLBACK_HINT for key in GLOBAL_KEYS: tree = {'network': {key: network.get(key)}} subtrees[hint] = self.merge(subtrees.get(hint, {}), tree) # return a list of (str:hint, dict:subtree) tuples return subtrees.items()
def test_netplan_get_filename_by_id_no_files(self): self.assertIsNone( utils.netplan_get_filename_by_id('some-id', self.workdir.name))