def test_create_a_new_file(self): TEXT = 'foo' with namedTemporaryDir() as tmp_dir: test_file_path = os.path.join(tmp_dir, 'foo.txt') with utils.atomic_file_write(test_file_path, 'w') as f: f.write(TEXT) self.assertFalse(os.path.exists(test_file_path)) self._assert_file_contains(test_file_path, TEXT) # temporary file was removed self.assertEqual(len(os.listdir(tmp_dir)), 1)
def test_exception(self): TEXT = 'foo' with namedTemporaryDir() as tmp_dir: test_file_path = os.path.join(tmp_dir, 'foo.txt') with self.assertRaises(TestException): with utils.atomic_file_write(test_file_path, 'w') as f: f.write(TEXT) raise TestException() self.assertFalse(os.path.exists(test_file_path)) # temporary file was removed self.assertEqual(len(os.listdir(tmp_dir)), 0)
def test_edit_file(self): OLD_TEXT = 'foo' NEW_TEXT = 'bar' with namedTemporaryDir() as tmp_dir: test_file_path = os.path.join(tmp_dir, 'foo.txt') with open(test_file_path, 'w') as f: f.write(OLD_TEXT) with utils.atomic_file_write(test_file_path, 'w') as f: f.write(NEW_TEXT) self._assert_file_contains(test_file_path, OLD_TEXT) self._assert_file_contains(test_file_path, NEW_TEXT) # temporary file was removed self.assertEqual(len(os.listdir(tmp_dir)), 1)
def _set_ifcfg_param(iface, key, value): with utils.atomic_file_write(ifcfg.NET_CONF_PREF + iface, 'r+') as f: lines = f.readlines() lines = _mark_ifcfg_with_prefix(lines) line_index, current_value = _ifcfg_key_lookup(lines, key) if line_index is None: lines.append('{}={} # Set by VDSM\n'.format(key, value)) else: if current_value != value: lines[line_index] = ( '{}={} # Changed by VDSM, original: {}'.format( key, value, lines[line_index])) f.seek(0) f.writelines(lines)
def _set_ifcfg_param(iface, key, value): with utils.atomic_file_write(ifcfg.NET_CONF_PREF + iface, 'r+') as f: lines = f.readlines() if lines[0] != ACQUIRED_IFCFG_TAG: lines = ACQUIRED_IFCFG_PREFIX + lines configured = False for i, line in enumerate(lines): parsed_line = re.split('=| |\n', line) if parsed_line[0] == key and parsed_line[1] != value: lines[i] = '{}={} # Changed by VDSM, original: {}'.format( key, value, lines[i]) configured = True if not configured: lines.append('{}={} # Set by VDSM\n'.format(key, value)) f.seek(0) f.writelines(lines)
def _rollback_ifcfg_iface(iface, ifcfg_lines): with utils.atomic_file_write(ifcfg.NET_CONF_PREF + iface, 'w') as f: f.writelines(ifcfg_lines) ifcfg.ifup(iface)