summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorChristian Ehrhardt <christian.ehrhardt@canonical.com>2016-05-24 17:58:18 +0200
committerChristian Ehrhardt <christian.ehrhardt@canonical.com>2016-05-24 17:58:18 +0200
commit81156aa423309c72f17709eea994e7e06ebc431c (patch)
tree4ee78fb024c5f03a3c12e39e1adfc1b0cb84063b
parent14040a9c8df6e8406acb79fd653873bb05cb4d40 (diff)
parentea4bc2c603a9d964a918e01d00e39a851e979830 (diff)
downloadvyos-cloud-init-81156aa423309c72f17709eea994e7e06ebc431c.tar.gz
vyos-cloud-init-81156aa423309c72f17709eea994e7e06ebc431c.zip
rebased with upstream and reolved merge conflicts
-rw-r--r--cloudinit/config/cc_apt_configure.py2
-rw-r--r--cloudinit/config/cc_bootcmd.py4
-rw-r--r--cloudinit/config/cc_disk_setup.py2
-rw-r--r--cloudinit/config/cc_emit_upstart.py2
-rw-r--r--cloudinit/config/cc_fan.py2
-rw-r--r--cloudinit/config/cc_final_message.py2
-rw-r--r--cloudinit/config/cc_grub_dpkg.py2
-rw-r--r--cloudinit/config/cc_keys_to_console.py2
-rw-r--r--cloudinit/config/cc_lxd.py2
-rw-r--r--cloudinit/config/cc_mounts.py10
-rw-r--r--cloudinit/config/cc_phone_home.py6
-rw-r--r--cloudinit/config/cc_rightscale_userdata.py4
-rw-r--r--cloudinit/config/cc_runcmd.py2
-rw-r--r--cloudinit/config/cc_scripts_per_boot.py2
-rw-r--r--cloudinit/config/cc_scripts_per_instance.py2
-rw-r--r--cloudinit/config/cc_scripts_per_once.py2
-rw-r--r--cloudinit/config/cc_scripts_user.py2
-rw-r--r--cloudinit/config/cc_scripts_vendor.py2
-rw-r--r--cloudinit/config/cc_seed_random.py2
-rw-r--r--cloudinit/config/cc_set_passwords.py2
-rw-r--r--cloudinit/config/cc_snappy.py4
-rw-r--r--cloudinit/config/cc_ssh.py6
-rw-r--r--cloudinit/config/cc_ssh_import_id.py4
-rw-r--r--cloudinit/config/cc_ubuntu_init_switch.py4
-rw-r--r--cloudinit/distros/__init__.py4
-rw-r--r--cloudinit/distros/debian.py4
-rw-r--r--cloudinit/handlers/__init__.py6
-rw-r--r--cloudinit/handlers/cloud_config.py2
-rw-r--r--cloudinit/handlers/upstart_job.py2
-rw-r--r--cloudinit/helpers.py10
-rw-r--r--cloudinit/net/__init__.py18
-rw-r--r--cloudinit/net/network_state.py7
-rw-r--r--cloudinit/net/udev.py2
-rw-r--r--cloudinit/netinfo.py7
-rw-r--r--cloudinit/reporting/handlers.py10
-rw-r--r--cloudinit/sources/DataSourceAzure.py12
-rw-r--r--cloudinit/sources/DataSourceBigstep.py4
-rw-r--r--cloudinit/sources/DataSourceCloudSigma.py5
-rw-r--r--cloudinit/sources/DataSourceCloudStack.py5
-rw-r--r--cloudinit/sources/DataSourceDigitalOcean.py4
-rw-r--r--cloudinit/sources/DataSourceGCE.py4
-rw-r--r--cloudinit/sources/DataSourceNoCloud.py4
-rw-r--r--cloudinit/sources/DataSourceOVF.py25
-rw-r--r--cloudinit/sources/__init__.py3
-rw-r--r--cloudinit/sources/helpers/azure.py3
-rw-r--r--cloudinit/sources/helpers/openstack.py4
-rw-r--r--cloudinit/sources/helpers/vmware/imc/boot_proto.py50
-rw-r--r--cloudinit/sources/helpers/vmware/imc/config.py190
-rw-r--r--cloudinit/sources/helpers/vmware/imc/config_namespace.py50
-rw-r--r--cloudinit/sources/helpers/vmware/imc/config_nic.py2
-rw-r--r--cloudinit/sources/helpers/vmware/imc/config_source.py46
-rw-r--r--cloudinit/sources/helpers/vmware/imc/guestcust_error.py48
-rw-r--r--cloudinit/sources/helpers/vmware/imc/guestcust_event.py54
-rw-r--r--cloudinit/sources/helpers/vmware/imc/guestcust_state.py50
-rw-r--r--cloudinit/sources/helpers/vmware/imc/guestcust_util.py256
-rw-r--r--cloudinit/sources/helpers/vmware/imc/ipv4_mode.py2
-rw-r--r--cloudinit/sources/helpers/vmware/imc/nic_base.py6
-rw-r--r--cloudinit/stages.py4
-rw-r--r--cloudinit/url_helper.py5
-rw-r--r--cloudinit/user_data.py2
-rw-r--r--cloudinit/util.py18
-rw-r--r--doc/examples/cloud-config-boot-cmds.txt6
-rw-r--r--doc/examples/cloud-config-run-cmds.txt3
-rwxr-xr-xsetup.py12
-rw-r--r--test-requirements.txt11
-rw-r--r--tests/unittests/helpers.py2
-rw-r--r--tests/unittests/test_builtin_handlers.py4
-rw-r--r--tests/unittests/test_cli.py4
-rw-r--r--tests/unittests/test_data.py49
-rw-r--r--tests/unittests/test_datasource/test_altcloud.py48
-rw-r--r--tests/unittests/test_datasource/test_azure.py18
-rw-r--r--tests/unittests/test_datasource/test_azure_helper.py3
-rw-r--r--tests/unittests/test_datasource/test_cloudstack.py1
-rw-r--r--tests/unittests/test_datasource/test_configdrive.py8
-rw-r--r--tests/unittests/test_datasource/test_digitalocean.py2
-rw-r--r--tests/unittests/test_datasource/test_gce.py2
-rw-r--r--tests/unittests/test_datasource/test_maas.py4
-rw-r--r--tests/unittests/test_datasource/test_nocloud.py2
-rw-r--r--tests/unittests/test_datasource/test_openstack.py70
-rw-r--r--tests/unittests/test_datasource/test_smartos.py110
-rw-r--r--tests/unittests/test_distros/test_generic.py10
-rw-r--r--tests/unittests/test_distros/test_hostname.py12
-rw-r--r--tests/unittests/test_distros/test_hosts.py18
-rw-r--r--tests/unittests/test_distros/test_netconfig.py37
-rw-r--r--tests/unittests/test_distros/test_resolv.py21
-rw-r--r--tests/unittests/test_distros/test_sysconfig.py27
-rw-r--r--tests/unittests/test_distros/test_user_data_normalize.py74
-rw-r--r--tests/unittests/test_ec2_util.py36
-rw-r--r--tests/unittests/test_filters/test_launch_index.py2
-rw-r--r--tests/unittests/test_handler/test_handler_apt_configure.py2
-rw-r--r--tests/unittests/test_handler/test_handler_ca_certs.py14
-rw-r--r--tests/unittests/test_handler/test_handler_chef.py14
-rw-r--r--tests/unittests/test_handler/test_handler_growpart.py2
-rw-r--r--tests/unittests/test_handler/test_handler_locale.py2
-rw-r--r--tests/unittests/test_handler/test_handler_lxd.py22
-rw-r--r--tests/unittests/test_handler/test_handler_power_state.py2
-rw-r--r--tests/unittests/test_handler/test_handler_rsyslog.py2
-rw-r--r--tests/unittests/test_handler/test_handler_seed_random.py12
-rw-r--r--tests/unittests/test_handler/test_handler_set_hostname.py16
-rw-r--r--tests/unittests/test_handler/test_handler_snappy.py1
-rw-r--r--tests/unittests/test_handler/test_handler_timezone.py10
-rw-r--r--tests/unittests/test_handler/test_handler_write_files.py4
-rw-r--r--tests/unittests/test_handler/test_handler_yum_add_repo.py13
-rw-r--r--tests/unittests/test_merging.py18
-rw-r--r--tests/unittests/test_net.py5
-rw-r--r--tests/unittests/test_reporting.py2
-rw-r--r--tests/unittests/test_rh_subscription.py3
-rw-r--r--tests/unittests/test_runs/test_merge_run.py6
-rw-r--r--tests/unittests/test_runs/test_simple_run.py4
-rw-r--r--tests/unittests/test_templating.py8
-rw-r--r--tox.ini11
111 files changed, 890 insertions, 881 deletions
diff --git a/cloudinit/config/cc_apt_configure.py b/cloudinit/config/cc_apt_configure.py
index dd199471..8f22c446 100644
--- a/cloudinit/config/cc_apt_configure.py
+++ b/cloudinit/config/cc_apt_configure.py
@@ -272,7 +272,7 @@ def add_sources(srclist, template_params=None, aa_repo_match=None):
try:
contents = "%s\n" % (source)
util.write_file(ent['filename'], contents, omode="ab")
- except:
+ except Exception:
errorlist.append([source,
"failed write to file %s" % ent['filename']])
diff --git a/cloudinit/config/cc_bootcmd.py b/cloudinit/config/cc_bootcmd.py
index a295cc4e..b763a3c3 100644
--- a/cloudinit/config/cc_bootcmd.py
+++ b/cloudinit/config/cc_bootcmd.py
@@ -38,7 +38,7 @@ def handle(name, cfg, cloud, log, _args):
content = util.shellify(cfg["bootcmd"])
tmpf.write(util.encode_text(content))
tmpf.flush()
- except:
+ except Exception:
util.logexc(log, "Failed to shellify bootcmd")
raise
@@ -49,6 +49,6 @@ def handle(name, cfg, cloud, log, _args):
env['INSTANCE_ID'] = str(iid)
cmd = ['/bin/sh', tmpf.name]
util.subp(cmd, env=env, capture=False)
- except:
+ except Exception:
util.logexc(log, "Failed to run bootcmd module %s", name)
raise
diff --git a/cloudinit/config/cc_disk_setup.py b/cloudinit/config/cc_disk_setup.py
index bbaf9646..b642f1f8 100644
--- a/cloudinit/config/cc_disk_setup.py
+++ b/cloudinit/config/cc_disk_setup.py
@@ -198,7 +198,7 @@ def is_device_valid(name, partition=False):
d_type = ""
try:
d_type = device_type(name)
- except:
+ except Exception:
LOG.warn("Query against device %s failed" % name)
return False
diff --git a/cloudinit/config/cc_emit_upstart.py b/cloudinit/config/cc_emit_upstart.py
index 86ae97ab..06c53272 100644
--- a/cloudinit/config/cc_emit_upstart.py
+++ b/cloudinit/config/cc_emit_upstart.py
@@ -20,8 +20,8 @@
import os
-from cloudinit.settings import PER_ALWAYS
from cloudinit import log as logging
+from cloudinit.settings import PER_ALWAYS
from cloudinit import util
frequency = PER_ALWAYS
diff --git a/cloudinit/config/cc_fan.py b/cloudinit/config/cc_fan.py
index 39e3850e..545fee22 100644
--- a/cloudinit/config/cc_fan.py
+++ b/cloudinit/config/cc_fan.py
@@ -37,8 +37,8 @@ If cloud-init sees a 'fan' entry in cloud-config it will
"""
from cloudinit import log as logging
-from cloudinit import util
from cloudinit.settings import PER_INSTANCE
+from cloudinit import util
LOG = logging.getLogger(__name__)
diff --git a/cloudinit/config/cc_final_message.py b/cloudinit/config/cc_final_message.py
index 4a51476f..c9021eb1 100644
--- a/cloudinit/config/cc_final_message.py
+++ b/cloudinit/config/cc_final_message.py
@@ -66,7 +66,7 @@ def handle(_name, cfg, cloud, log, args):
try:
contents = "%s - %s - v. %s\n" % (uptime, ts, cver)
util.write_file(boot_fin_fn, contents)
- except:
+ except Exception:
util.logexc(log, "Failed to write boot finished file %s", boot_fin_fn)
if cloud.datasource.is_disconnected:
diff --git a/cloudinit/config/cc_grub_dpkg.py b/cloudinit/config/cc_grub_dpkg.py
index 3c2d9985..156722d9 100644
--- a/cloudinit/config/cc_grub_dpkg.py
+++ b/cloudinit/config/cc_grub_dpkg.py
@@ -69,5 +69,5 @@ def handle(name, cfg, _cloud, log, _args):
try:
util.subp(['debconf-set-selections'], dconf_sel)
- except:
+ except Exception:
util.logexc(log, "Failed to run debconf-set-selections for grub-dpkg")
diff --git a/cloudinit/config/cc_keys_to_console.py b/cloudinit/config/cc_keys_to_console.py
index aa844ee9..9a02f056 100644
--- a/cloudinit/config/cc_keys_to_console.py
+++ b/cloudinit/config/cc_keys_to_console.py
@@ -57,6 +57,6 @@ def handle(name, cfg, cloud, log, _args):
(stdout, _stderr) = util.subp(cmd)
util.multi_log("%s\n" % (stdout.strip()),
stderr=False, console=True)
- except:
+ except Exception:
log.warn("Writing keys to the system console failed!")
raise
diff --git a/cloudinit/config/cc_lxd.py b/cloudinit/config/cc_lxd.py
index bf735648..b1de8f84 100644
--- a/cloudinit/config/cc_lxd.py
+++ b/cloudinit/config/cc_lxd.py
@@ -111,7 +111,7 @@ def handle(name, cfg, cloud, log, args):
data = "\n".join(["set %s %s" % (k, v)
for k, v in debconf.items()]) + "\n"
util.subp(['debconf-communicate'], data)
- except:
+ except Exception:
util.logexc(log, "Failed to run '%s' for lxd with" % dconf_comm)
# Remove the existing configuration file (forces re-generation)
diff --git a/cloudinit/config/cc_mounts.py b/cloudinit/config/cc_mounts.py
index 4fe3ee21..2b981935 100644
--- a/cloudinit/config/cc_mounts.py
+++ b/cloudinit/config/cc_mounts.py
@@ -244,7 +244,7 @@ def handle_swapcfg(swapcfg):
LOG.debug("swap file %s already in use.", fname)
return fname
LOG.debug("swap file %s existed, but not in /proc/swaps", fname)
- except:
+ except Exception:
LOG.warn("swap file %s existed. Error reading /proc/swaps", fname)
return fname
@@ -379,7 +379,7 @@ def handle(_name, cfg, cloud, log, _args):
toks = WS.split(line)
if toks[3].find(comment) != -1:
continue
- except:
+ except Exception:
pass
fstab_lines.append(line)
@@ -390,16 +390,16 @@ def handle(_name, cfg, cloud, log, _args):
if needswap:
try:
util.subp(("swapon", "-a"))
- except:
+ except Exception:
util.logexc(log, "Activating swap via 'swapon -a' failed")
for d in dirs:
try:
util.ensure_dir(d)
- except:
+ except Exception:
util.logexc(log, "Failed to make '%s' config-mount", d)
try:
util.subp(("mount", "-a"))
- except:
+ except Exception:
util.logexc(log, "Activating mounts via 'mount -a' failed")
diff --git a/cloudinit/config/cc_phone_home.py b/cloudinit/config/cc_phone_home.py
index 3dcc9459..72176d42 100644
--- a/cloudinit/config/cc_phone_home.py
+++ b/cloudinit/config/cc_phone_home.py
@@ -65,7 +65,7 @@ def handle(name, cfg, cloud, log, args):
tries = ph_cfg.get('tries')
try:
tries = int(tries)
- except:
+ except Exception:
tries = 10
util.logexc(log, "Configuration entry 'tries' is not an integer, "
"using %s instead", tries)
@@ -87,7 +87,7 @@ def handle(name, cfg, cloud, log, args):
for (n, path) in pubkeys.items():
try:
all_keys[n] = util.load_file(path)
- except:
+ except Exception:
util.logexc(log, "%s: failed to open, can not phone home that "
"data!", path)
@@ -117,6 +117,6 @@ def handle(name, cfg, cloud, log, args):
util.read_file_or_url(url, data=real_submit_keys,
retries=tries, sec_between=3,
ssl_details=util.fetch_ssl_details(cloud.paths))
- except:
+ except Exception:
util.logexc(log, "Failed to post phone home data to %s in %s tries",
url, tries)
diff --git a/cloudinit/config/cc_rightscale_userdata.py b/cloudinit/config/cc_rightscale_userdata.py
index 0ecf3a4d..8118fac4 100644
--- a/cloudinit/config/cc_rightscale_userdata.py
+++ b/cloudinit/config/cc_rightscale_userdata.py
@@ -52,7 +52,7 @@ MY_HOOKNAME = 'CLOUD_INIT_REMOTE_HOOK'
def handle(name, _cfg, cloud, log, _args):
try:
ud = cloud.get_userdata_raw()
- except:
+ except Exception:
log.debug("Failed to get raw userdata in module %s", name)
return
@@ -63,7 +63,7 @@ def handle(name, _cfg, cloud, log, _args):
"did not find %s in parsed"
" raw userdata"), name, MY_HOOKNAME)
return
- except:
+ except Exception:
util.logexc(log, "Failed to parse query string %s into a dictionary",
ud)
raise
diff --git a/cloudinit/config/cc_runcmd.py b/cloudinit/config/cc_runcmd.py
index 66dc3363..bc09d38c 100644
--- a/cloudinit/config/cc_runcmd.py
+++ b/cloudinit/config/cc_runcmd.py
@@ -34,5 +34,5 @@ def handle(name, cfg, cloud, log, _args):
try:
content = util.shellify(cmd)
util.write_file(out_fn, content, 0o700)
- except:
+ except Exception:
util.logexc(log, "Failed to shellify %s into file %s", cmd, out_fn)
diff --git a/cloudinit/config/cc_scripts_per_boot.py b/cloudinit/config/cc_scripts_per_boot.py
index 42b987eb..ee3b6c9f 100644
--- a/cloudinit/config/cc_scripts_per_boot.py
+++ b/cloudinit/config/cc_scripts_per_boot.py
@@ -35,7 +35,7 @@ def handle(name, _cfg, cloud, log, _args):
runparts_path = os.path.join(cloud.get_cpath(), 'scripts', SCRIPT_SUBDIR)
try:
util.runparts(runparts_path)
- except:
+ except Exception:
log.warn("Failed to run module %s (%s in %s)",
name, SCRIPT_SUBDIR, runparts_path)
raise
diff --git a/cloudinit/config/cc_scripts_per_instance.py b/cloudinit/config/cc_scripts_per_instance.py
index b5d71c13..c0d62b12 100644
--- a/cloudinit/config/cc_scripts_per_instance.py
+++ b/cloudinit/config/cc_scripts_per_instance.py
@@ -35,7 +35,7 @@ def handle(name, _cfg, cloud, log, _args):
runparts_path = os.path.join(cloud.get_cpath(), 'scripts', SCRIPT_SUBDIR)
try:
util.runparts(runparts_path)
- except:
+ except Exception:
log.warn("Failed to run module %s (%s in %s)",
name, SCRIPT_SUBDIR, runparts_path)
raise
diff --git a/cloudinit/config/cc_scripts_per_once.py b/cloudinit/config/cc_scripts_per_once.py
index d77d36d5..ecb527f6 100644
--- a/cloudinit/config/cc_scripts_per_once.py
+++ b/cloudinit/config/cc_scripts_per_once.py
@@ -35,7 +35,7 @@ def handle(name, _cfg, cloud, log, _args):
runparts_path = os.path.join(cloud.get_cpath(), 'scripts', SCRIPT_SUBDIR)
try:
util.runparts(runparts_path)
- except:
+ except Exception:
log.warn("Failed to run module %s (%s in %s)",
name, SCRIPT_SUBDIR, runparts_path)
raise
diff --git a/cloudinit/config/cc_scripts_user.py b/cloudinit/config/cc_scripts_user.py
index 5c53014f..699857d1 100644
--- a/cloudinit/config/cc_scripts_user.py
+++ b/cloudinit/config/cc_scripts_user.py
@@ -36,7 +36,7 @@ def handle(name, _cfg, cloud, log, _args):
runparts_path = os.path.join(cloud.get_ipath_cur(), SCRIPT_SUBDIR)
try:
util.runparts(runparts_path)
- except:
+ except Exception:
log.warn("Failed to run module %s (%s in %s)",
name, SCRIPT_SUBDIR, runparts_path)
raise
diff --git a/cloudinit/config/cc_scripts_vendor.py b/cloudinit/config/cc_scripts_vendor.py
index 0c9e504e..80bf10ff 100644
--- a/cloudinit/config/cc_scripts_vendor.py
+++ b/cloudinit/config/cc_scripts_vendor.py
@@ -37,7 +37,7 @@ def handle(name, cfg, cloud, log, _args):
try:
util.runparts(runparts_path, exe_prefix=prefix)
- except:
+ except Exception:
log.warn("Failed to run module %s (%s in %s)",
name, SCRIPT_SUBDIR, runparts_path)
raise
diff --git a/cloudinit/config/cc_seed_random.py b/cloudinit/config/cc_seed_random.py
index 1b011216..5085c23a 100644
--- a/cloudinit/config/cc_seed_random.py
+++ b/cloudinit/config/cc_seed_random.py
@@ -24,8 +24,8 @@ import os
from six import BytesIO
-from cloudinit.settings import PER_INSTANCE
from cloudinit import log as logging
+from cloudinit.settings import PER_INSTANCE
from cloudinit import util
frequency = PER_INSTANCE
diff --git a/cloudinit/config/cc_set_passwords.py b/cloudinit/config/cc_set_passwords.py
index 58e1b713..5c8c23b8 100644
--- a/cloudinit/config/cc_set_passwords.py
+++ b/cloudinit/config/cc_set_passwords.py
@@ -155,7 +155,7 @@ def handle(_name, cfg, cloud, log, args):
cmd = filter(None, cmd) # Remove empty arguments
util.subp(cmd)
log.debug("Restarted the ssh daemon")
- except:
+ except Exception:
util.logexc(log, "Restarting of the ssh daemon failed")
if len(errors):
diff --git a/cloudinit/config/cc_snappy.py b/cloudinit/config/cc_snappy.py
index fa9d54a0..1a485ee6 100644
--- a/cloudinit/config/cc_snappy.py
+++ b/cloudinit/config/cc_snappy.py
@@ -47,12 +47,12 @@ Example config:
"""
from cloudinit import log as logging
-from cloudinit import util
from cloudinit.settings import PER_INSTANCE
+from cloudinit import util
import glob
-import tempfile
import os
+import tempfile
LOG = logging.getLogger(__name__)
diff --git a/cloudinit/config/cc_ssh.py b/cloudinit/config/cc_ssh.py
index d24e43c0..cb9b70aa 100644
--- a/cloudinit/config/cc_ssh.py
+++ b/cloudinit/config/cc_ssh.py
@@ -57,7 +57,7 @@ def handle(_name, cfg, cloud, log, _args):
for f in glob.glob(key_pth):
try:
util.del_file(f)
- except:
+ except Exception:
util.logexc(log, "Failed deleting key file %s", f)
if "ssh_keys" in cfg:
@@ -78,7 +78,7 @@ def handle(_name, cfg, cloud, log, _args):
with util.SeLinuxGuard("/etc/ssh", recursive=True):
util.subp(cmd, capture=False)
log.debug("Generated a key for %s from %s", pair[0], pair[1])
- except:
+ except Exception:
util.logexc(log, "Failed generated a key for %s from %s",
pair[0], pair[1])
else:
@@ -122,7 +122,7 @@ def handle(_name, cfg, cloud, log, _args):
keys.extend(cfgkeys)
apply_credentials(keys, user, disable_root, disable_root_opts)
- except:
+ except Exception:
util.logexc(log, "Applying ssh credentials failed!")
diff --git a/cloudinit/config/cc_ssh_import_id.py b/cloudinit/config/cc_ssh_import_id.py
index 2d480d7e..28c4585b 100644
--- a/cloudinit/config/cc_ssh_import_id.py
+++ b/cloudinit/config/cc_ssh_import_id.py
@@ -52,14 +52,14 @@ def handle(_name, cfg, cloud, log, args):
else:
try:
import_ids = user_cfg['ssh_import_id']
- except:
+ except Exception:
log.debug("User %s is not configured for ssh_import_id", user)
continue
try:
import_ids = util.uniq_merge(import_ids)
import_ids = [str(i) for i in import_ids]
- except:
+ except Exception:
log.debug("User %s is not correctly configured for ssh_import_id",
user)
continue
diff --git a/cloudinit/config/cc_ubuntu_init_switch.py b/cloudinit/config/cc_ubuntu_init_switch.py
index 7e88ed85..884d79f1 100644
--- a/cloudinit/config/cc_ubuntu_init_switch.py
+++ b/cloudinit/config/cc_ubuntu_init_switch.py
@@ -40,10 +40,10 @@ It can be configured with the following option structure::
mechanism you've used to switch the init system.
"""
-from cloudinit.settings import PER_INSTANCE
+from cloudinit.distros import ubuntu
from cloudinit import log as logging
+from cloudinit.settings import PER_INSTANCE
from cloudinit import util
-from cloudinit.distros import ubuntu
import os
import time
diff --git a/cloudinit/distros/__init__.py b/cloudinit/distros/__init__.py
index 5879dabf..0f222c8c 100644
--- a/cloudinit/distros/__init__.py
+++ b/cloudinit/distros/__init__.py
@@ -50,8 +50,8 @@ OSFAMILIES = {
LOG = logging.getLogger(__name__)
+@six.add_metaclass(abc.ABCMeta)
class Distro(object):
- __metaclass__ = abc.ABCMeta
usr_lib_exec = "/usr/lib"
hosts_fn = "/etc/hosts"
@@ -97,7 +97,7 @@ class Distro(object):
try:
res = os.lstat('/run/systemd/system')
return stat.S_ISDIR(res.st_mode)
- except:
+ except Exception:
return False
@abc.abstractmethod
diff --git a/cloudinit/distros/debian.py b/cloudinit/distros/debian.py
index 75ab340f..32bef1cd 100644
--- a/cloudinit/distros/debian.py
+++ b/cloudinit/distros/debian.py
@@ -25,8 +25,8 @@ import os
from cloudinit import distros
from cloudinit import helpers
from cloudinit import log as logging
-from cloudinit import util
from cloudinit import net
+from cloudinit import util
from cloudinit.distros.parsers.hostname import HostnameConf
@@ -221,7 +221,7 @@ def _maybe_remove_legacy_eth0(path="/etc/network/interfaces.d/eth0.cfg"):
msg = "removed %s with known contents" % path
else:
msg = (bmsg + " '%s' exists with user configured content." % path)
- except:
+ except Exception:
msg = bmsg + " %s exists, but could not be read." % path
LOG.warn(msg)
diff --git a/cloudinit/handlers/__init__.py b/cloudinit/handlers/__init__.py
index 53d5604a..b6c43ce8 100644
--- a/cloudinit/handlers/__init__.py
+++ b/cloudinit/handlers/__init__.py
@@ -71,8 +71,8 @@ INCLUSION_SRCH = sorted(list(INCLUSION_TYPES_MAP.keys()),
key=(lambda e: 0 - len(e)))
+@six.add_metaclass(abc.ABCMeta)
class Handler(object):
- __metaclass__ = abc.ABCMeta
def __init__(self, frequency, version=2):
self.handler_version = version
@@ -118,7 +118,7 @@ def run_part(mod, data, filename, payload, frequency, headers):
mod.handle_part(data, content_type, filename, payload)
else:
raise ValueError("Unknown module version %s" % (mod_ver))
- except:
+ except Exception:
util.logexc(LOG, "Failed calling handler %s (%s, %s, %s) with "
"frequency %s", mod, content_type, filename, mod_ver,
frequency)
@@ -157,7 +157,7 @@ def walker_handle_handler(pdata, _ctype, _filename, payload):
# register if it fails starting.
handlers.register(mod, initialized=True)
pdata['handlercount'] = curcount + 1
- except:
+ except Exception:
util.logexc(LOG, "Failed at registering python file: %s (part "
"handler %s)", modfname, curcount)
diff --git a/cloudinit/handlers/cloud_config.py b/cloudinit/handlers/cloud_config.py
index 07b6d0e0..cad4dc0f 100644
--- a/cloudinit/handlers/cloud_config.py
+++ b/cloudinit/handlers/cloud_config.py
@@ -158,6 +158,6 @@ class CloudConfigPartHandler(handlers.Handler):
for i in ("\n", "\r", "\t"):
filename = filename.replace(i, " ")
self.file_names.append(filename.strip())
- except:
+ except Exception:
util.logexc(LOG, "Failed at merging in cloud config part from %s",
filename)
diff --git a/cloudinit/handlers/upstart_job.py b/cloudinit/handlers/upstart_job.py
index c5bea711..ab381e00 100644
--- a/cloudinit/handlers/upstart_job.py
+++ b/cloudinit/handlers/upstart_job.py
@@ -80,7 +80,7 @@ def _has_suitable_upstart():
return False
try:
(version_out, _err) = util.subp(["initctl", "version"])
- except:
+ except Exception:
util.logexc(LOG, "initctl version failed")
return False
diff --git a/cloudinit/helpers.py b/cloudinit/helpers.py
index 7f00bf1f..09d75e65 100644
--- a/cloudinit/helpers.py
+++ b/cloudinit/helpers.py
@@ -86,7 +86,7 @@ class FileSemaphores(object):
name = canon_sem_name(name)
try:
yield self._acquire(name, freq)
- except:
+ except Exception:
if clear_on_fail:
self.clear(name, freq)
raise
@@ -219,7 +219,7 @@ class ConfigMerger(object):
ds_cfg = self._ds.get_config_obj()
if ds_cfg and isinstance(ds_cfg, (dict)):
d_cfgs.append(ds_cfg)
- except:
+ except Exception:
util.logexc(LOG, "Failed loading of datasource config object "
"from %s", self._ds)
return d_cfgs
@@ -230,7 +230,7 @@ class ConfigMerger(object):
e_fn = os.environ[CFG_ENV_NAME]
try:
e_cfgs.append(util.read_conf(e_fn))
- except:
+ except Exception:
util.logexc(LOG, 'Failed loading of env. config from %s',
e_fn)
return e_cfgs
@@ -251,7 +251,7 @@ class ConfigMerger(object):
if cc_fn and os.path.isfile(cc_fn):
try:
i_cfgs.append(util.read_conf(cc_fn))
- except:
+ except Exception:
util.logexc(LOG, 'Failed loading of cloud-config from %s',
cc_fn)
return i_cfgs
@@ -268,7 +268,7 @@ class ConfigMerger(object):
for c_fn in self._fns:
try:
cfgs.append(util.read_conf(c_fn))
- except:
+ except Exception:
util.logexc(LOG, "Failed loading of configuration from %s",
c_fn)
diff --git a/cloudinit/net/__init__.py b/cloudinit/net/__init__.py
index 31544fd8..91e36aca 100644
--- a/cloudinit/net/__init__.py
+++ b/cloudinit/net/__init__.py
@@ -26,9 +26,9 @@ import re
import shlex
from cloudinit import log as logging
+from cloudinit.net import network_state
+from cloudinit.net.udev import generate_udev_rule
from cloudinit import util
-from .udev import generate_udev_rule
-from . import network_state
LOG = logging.getLogger(__name__)
@@ -40,16 +40,16 @@ NET_CONFIG_OPTIONS = [
"pointtopoint", "media", "mtu", "hostname", "leasehours", "leasetime",
"vendor", "client", "bootfile", "server", "hwaddr", "provider", "frame",
"netnum", "endpoint", "local", "ttl",
- ]
+]
NET_CONFIG_COMMANDS = [
"pre-up", "up", "post-up", "down", "pre-down", "post-down",
- ]
+]
NET_CONFIG_BRIDGE_OPTIONS = [
"bridge_ageing", "bridge_bridgeprio", "bridge_fd", "bridge_gcinit",
"bridge_hello", "bridge_maxage", "bridge_maxwait", "bridge_stp",
- ]
+]
DEFAULT_PRIMARY_INTERFACE = 'eth0'
@@ -399,9 +399,7 @@ def config_from_klibc_net_cfg(files=None, mac_addrs=None):
def render_persistent_net(network_state):
- ''' Given state, emit udev rules to map
- mac to ifname
- '''
+ '''Given state, emit udev rules to map mac to ifname.'''
content = ""
interfaces = network_state.get('interfaces')
for iface in interfaces.values():
@@ -465,7 +463,7 @@ def iface_add_attrs(iface):
def render_route(route, indent=""):
- """ When rendering routes for an iface, in some cases applying a route
+ """When rendering routes for an iface, in some cases applying a route
may result in the route command returning non-zero which produces
some confusing output for users manually using ifup/ifdown[1]. To
that end, we will optionally include an '|| true' postfix to each
@@ -530,7 +528,7 @@ def iface_start_entry(iface, index):
def render_interfaces(network_state):
- ''' Given state, emit etc/network/interfaces content '''
+ '''Given state, emit etc/network/interfaces content.'''
content = ""
interfaces = network_state.get('interfaces')
diff --git a/cloudinit/net/network_state.py b/cloudinit/net/network_state.py
index e32d2cdf..4c726ab4 100644
--- a/cloudinit/net/network_state.py
+++ b/cloudinit/net/network_state.py
@@ -36,7 +36,7 @@ def from_state_file(state_file):
return network_state
-class NetworkState:
+class NetworkState(object):
def __init__(self, version=NETWORK_STATE_VERSION, config=None):
self.version = version
self.config = config
@@ -53,7 +53,7 @@ class NetworkState:
def get_command_handlers(self):
METHOD_PREFIX = 'handle_'
methods = filter(lambda x: callable(getattr(self, x)) and
- x.startswith(METHOD_PREFIX), dir(self))
+ x.startswith(METHOD_PREFIX), dir(self))
handlers = {}
for m in methods:
key = m.replace(METHOD_PREFIX, '')
@@ -379,8 +379,9 @@ def mask2cidr(mask):
if __name__ == '__main__':
- import sys
import random
+ import sys
+
from cloudinit import net
def load_config(nc):
diff --git a/cloudinit/net/udev.py b/cloudinit/net/udev.py
index 6435ace0..09188295 100644
--- a/cloudinit/net/udev.py
+++ b/cloudinit/net/udev.py
@@ -48,7 +48,7 @@ def generate_udev_rule(interface, mac):
compose_udev_equality('DRIVERS', '?*'),
compose_udev_attr_equality('address', mac),
compose_udev_setting('NAME', interface),
- ])
+ ])
return '%s\n' % rule
# vi: ts=4 expandtab syntax=python
diff --git a/cloudinit/netinfo.py b/cloudinit/netinfo.py
index e30d6fb5..d8698a5d 100644
--- a/cloudinit/netinfo.py
+++ b/cloudinit/netinfo.py
@@ -20,10 +20,11 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
-import cloudinit.util as util
-from cloudinit.log import logging
import re
+from cloudinit import log as logging
+from cloudinit import util
+
from prettytable import PrettyTable
LOG = logging.getLogger()
@@ -163,7 +164,7 @@ def route_info():
def getgateway():
try:
routes = route_info()
- except:
+ except Exception:
pass
else:
for r in routes.get('ipv4', []):
diff --git a/cloudinit/reporting/handlers.py b/cloudinit/reporting/handlers.py
index 3212d173..dff20ecb 100644
--- a/cloudinit/reporting/handlers.py
+++ b/cloudinit/reporting/handlers.py
@@ -4,9 +4,9 @@ import abc
import json
import six
-from ..registry import DictRegistry
-from .. import (url_helper, util)
-from .. import log as logging
+from cloudinit import log as logging
+from cloudinit.registry import DictRegistry
+from cloudinit import (url_helper, util)
LOG = logging.getLogger(__name__)
@@ -36,7 +36,7 @@ class LogHandler(ReportingHandler):
input_level = level
try:
level = getattr(logging, level.upper())
- except:
+ except Exception:
LOG.warn("invalid level '%s', using WARN", input_level)
level = logging.WARN
self.level = level
@@ -81,7 +81,7 @@ class WebHookHandler(ReportingHandler):
self.endpoint, data=json.dumps(event.as_dict()),
timeout=self.timeout,
retries=self.retries, ssl_details=self.ssl_details)
- except:
+ except Exception:
LOG.warn("failed posting event: %s" % event.as_string())
diff --git a/cloudinit/sources/DataSourceAzure.py b/cloudinit/sources/DataSourceAzure.py
index 698f4cac..2d046600 100644
--- a/cloudinit/sources/DataSourceAzure.py
+++ b/cloudinit/sources/DataSourceAzure.py
@@ -27,11 +27,12 @@ import xml.etree.ElementTree as ET
from xml.dom import minidom
+from cloudinit.sources.helpers.azure import get_metadata_from_fabric
+
from cloudinit import log as logging
from cloudinit.settings import PER_ALWAYS
from cloudinit import sources
from cloudinit import util
-from cloudinit.sources.helpers.azure import get_metadata_from_fabric
LOG = logging.getLogger(__name__)
@@ -40,7 +41,8 @@ DEFAULT_METADATA = {"instance-id": "iid-AZURE-NODE"}
AGENT_START = ['service', 'walinuxagent', 'start']
BOUNCE_COMMAND = [
'sh', '-xc',
- "i=$interface; x=0; ifdown $i || x=$?; ifup $i || x=$?; exit $x"]
+ "i=$interface; x=0; ifdown $i || x=$?; ifup $i || x=$?; exit $x"
+]
BUILTIN_DS_CONFIG = {
'agent_command': AGENT_START,
@@ -51,7 +53,7 @@ BUILTIN_DS_CONFIG = {
'policy': True,
'command': BOUNCE_COMMAND,
'hostname_command': 'hostname',
- },
+ },
'disk_aliases': {'ephemeral0': '/dev/sdb'},
}
@@ -60,7 +62,7 @@ BUILTIN_CLOUD_CONFIG = {
'ephemeral0': {'table_type': 'gpt',
'layout': [100],
'overwrite': True},
- },
+ },
'fs_setup': [{'filesystem': 'ext4',
'device': 'ephemeral0.1',
'replace_fs': 'ntfs'}],
@@ -312,7 +314,7 @@ def support_new_ephemeral(cfg):
file_count = 0
try:
file_count = util.mount_cb(device, count_files)
- except:
+ except Exception:
return None
LOG.debug("fabric prepared ephmeral0.1 has %s files on it", file_count)
diff --git a/cloudinit/sources/DataSourceBigstep.py b/cloudinit/sources/DataSourceBigstep.py
index b5ee4129..f80956a5 100644
--- a/cloudinit/sources/DataSourceBigstep.py
+++ b/cloudinit/sources/DataSourceBigstep.py
@@ -4,13 +4,13 @@
# Author: Alexandru Sirbu <alexandru.sirbu@bigstep.com>
#
-import json
import errno
+import json
from cloudinit import log as logging
from cloudinit import sources
-from cloudinit import util
from cloudinit import url_helper
+from cloudinit import util
LOG = logging.getLogger(__name__)
diff --git a/cloudinit/sources/DataSourceCloudSigma.py b/cloudinit/sources/DataSourceCloudSigma.py
index d7d4e844..33fe78b9 100644
--- a/cloudinit/sources/DataSourceCloudSigma.py
+++ b/cloudinit/sources/DataSourceCloudSigma.py
@@ -19,10 +19,11 @@ from base64 import b64decode
import os
import re
+from cloudinit.cs_utils import Cepko
+
from cloudinit import log as logging
from cloudinit import sources
from cloudinit import util
-from cloudinit.cs_utils import Cepko
LOG = logging.getLogger(__name__)
@@ -77,7 +78,7 @@ class DataSourceCloudSigma(sources.DataSource):
try:
server_context = self.cepko.all().result
server_meta = server_context['meta']
- except:
+ except Exception:
# TODO: check for explicit "config on", and then warn
# but since no explicit config is available now, just debug.
LOG.debug("CloudSigma: Unable to read from serial port")
diff --git a/cloudinit/sources/DataSourceCloudStack.py b/cloudinit/sources/DataSourceCloudStack.py
index 4ba019df..4de1f563 100644
--- a/cloudinit/sources/DataSourceCloudStack.py
+++ b/cloudinit/sources/DataSourceCloudStack.py
@@ -25,14 +25,15 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
-import time
from socket import inet_ntoa
from struct import pack
+import time
from cloudinit import ec2_utils as ec2
from cloudinit import log as logging
+from cloudinit import sources
from cloudinit import url_helper as uhelp
-from cloudinit import sources, util
+from cloudinit import util
LOG = logging.getLogger(__name__)
diff --git a/cloudinit/sources/DataSourceDigitalOcean.py b/cloudinit/sources/DataSourceDigitalOcean.py
index 12e863d2..44a17a00 100644
--- a/cloudinit/sources/DataSourceDigitalOcean.py
+++ b/cloudinit/sources/DataSourceDigitalOcean.py
@@ -14,10 +14,10 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
+from cloudinit import ec2_utils
from cloudinit import log as logging
-from cloudinit import util
from cloudinit import sources
-from cloudinit import ec2_utils
+from cloudinit import util
import functools
diff --git a/cloudinit/sources/DataSourceGCE.py b/cloudinit/sources/DataSourceGCE.py
index 7e7fc033..9234d1f8 100644
--- a/cloudinit/sources/DataSourceGCE.py
+++ b/cloudinit/sources/DataSourceGCE.py
@@ -18,9 +18,9 @@
from base64 import b64decode
from cloudinit import log as logging
-from cloudinit import util
from cloudinit import sources
from cloudinit import url_helper
+from cloudinit import util
LOG = logging.getLogger(__name__)
@@ -71,7 +71,7 @@ class DataSourceGCE(sources.DataSource):
index = public_key.index(':')
if index > 0:
return public_key[(index + 1):]
- except:
+ except Exception:
return public_key
def get_data(self):
diff --git a/cloudinit/sources/DataSourceNoCloud.py b/cloudinit/sources/DataSourceNoCloud.py
index 74d0e5ec..48c61a90 100644
--- a/cloudinit/sources/DataSourceNoCloud.py
+++ b/cloudinit/sources/DataSourceNoCloud.py
@@ -61,7 +61,7 @@ class DataSourceNoCloud(sources.DataSource):
if parse_cmdline_data(self.cmdline_id, md):
found.append("cmdline")
mydata = _merge_new_seed(mydata, {'meta-data': md})
- except:
+ except Exception:
util.logexc(LOG, "Unable to parse command line data")
return False
@@ -288,7 +288,7 @@ def parse_cmdline_data(ds_id, fill, cmdline=None):
continue
try:
(k, v) = item.split("=", 1)
- except:
+ except Exception:
k = item
v = None
if k in s2l:
diff --git a/cloudinit/sources/DataSourceOVF.py b/cloudinit/sources/DataSourceOVF.py
index 2a6cd050..f2bb9366 100644
--- a/cloudinit/sources/DataSourceOVF.py
+++ b/cloudinit/sources/DataSourceOVF.py
@@ -30,13 +30,20 @@ import time
from cloudinit import log as logging
from cloudinit import sources
from cloudinit import util
-from .helpers.vmware.imc.config import Config
-from .helpers.vmware.imc.config_file import ConfigFile
-from .helpers.vmware.imc.config_nic import NicConfigurator
-from .helpers.vmware.imc.guestcust_event import GuestCustEventEnum
-from .helpers.vmware.imc.guestcust_state import GuestCustStateEnum
-from .helpers.vmware.imc.guestcust_error import GuestCustErrorEnum
-from .helpers.vmware.imc.guestcust_util import (
+
+from cloudinit.sources.helpers.vmware.imc.config \
+ import Config
+from cloudinit.sources.helpers.vmware.imc.config_file \
+ import ConfigFile
+from cloudinit.sources.helpers.vmware.imc.config_nic \
+ import NicConfigurator
+from cloudinit.sources.helpers.vmware.imc.guestcust_event \
+ import GuestCustEventEnum
+from cloudinit.sources.helpers.vmware.imc.guestcust_state \
+ import GuestCustStateEnum
+from cloudinit.sourceshelpers.vmware.imc.guestcust_error \
+ import GuestCustErrorEnum
+from cloudinit.sourceshelpers.vmware.imc.guestcust_util import (
set_customization_status,
get_nics_to_enable,
enable_nics
@@ -262,7 +269,7 @@ def read_ovf_environment(contents):
elif prop == "user-data":
try:
ud = base64.decodestring(val)
- except:
+ except Exception:
ud = val
return (md, ud, cfg)
@@ -277,7 +284,7 @@ def get_ovf_env(dirname):
try:
contents = util.load_file(full_fn)
return (fname, contents)
- except:
+ except Exception:
util.logexc(LOG, "Failed loading ovf file %s", full_fn)
return (None, False)
diff --git a/cloudinit/sources/__init__.py b/cloudinit/sources/__init__.py
index 6bf2c33b..43e4fd57 100644
--- a/cloudinit/sources/__init__.py
+++ b/cloudinit/sources/__init__.py
@@ -45,10 +45,9 @@ class DataSourceNotFoundException(Exception):
pass
+@six.add_metaclass(abc.ABCMeta)
class DataSource(object):
- __metaclass__ = abc.ABCMeta
-
def __init__(self, sys_cfg, distro, paths, ud_proc=None):
self.sys_cfg = sys_cfg
self.distro = distro
diff --git a/cloudinit/sources/helpers/azure.py b/cloudinit/sources/helpers/azure.py
index 018cac6d..63ccf10e 100644
--- a/cloudinit/sources/helpers/azure.py
+++ b/cloudinit/sources/helpers/azure.py
@@ -5,6 +5,7 @@ import socket
import struct
import tempfile
import time
+
from contextlib import contextmanager
from xml.etree import ElementTree
@@ -220,7 +221,7 @@ class WALinuxAgentShim(object):
if 'unknown-245' in line:
value = line.strip(' ').split(' ', 2)[-1].strip(';\n"')
if value is None:
- raise Exception('No endpoint found in DHCP config.')
+ raise ValueError('No endpoint found in DHCP config.')
endpoint_ip_address = WALinuxAgentShim.get_ip_from_lease_value(value)
LOG.debug('Azure endpoint found at %s', endpoint_ip_address)
return endpoint_ip_address
diff --git a/cloudinit/sources/helpers/openstack.py b/cloudinit/sources/helpers/openstack.py
index 1aa6bbae..156aba6c 100644
--- a/cloudinit/sources/helpers/openstack.py
+++ b/cloudinit/sources/helpers/openstack.py
@@ -145,8 +145,8 @@ class SourceMixin(object):
return device
+@six.add_metaclass(abc.ABCMeta)
class BaseReader(object):
- __metaclass__ = abc.ABCMeta
def __init__(self, base_path):
self.base_path = base_path
@@ -475,7 +475,7 @@ class MetadataReader(BaseReader):
def convert_vendordata_json(data, recurse=True):
- """ data: a loaded json *object* (strings, arrays, dicts).
+ """data: a loaded json *object* (strings, arrays, dicts).
return something suitable for cloudinit vendordata_raw.
if data is:
diff --git a/cloudinit/sources/helpers/vmware/imc/boot_proto.py b/cloudinit/sources/helpers/vmware/imc/boot_proto.py
index faba5887..fb53ec1d 100644
--- a/cloudinit/sources/helpers/vmware/imc/boot_proto.py
+++ b/cloudinit/sources/helpers/vmware/imc/boot_proto.py
@@ -1,25 +1,25 @@
-# vi: ts=4 expandtab
-#
-# Copyright (C) 2015 Canonical Ltd.
-# Copyright (C) 2015 VMware Inc.
-#
-# Author: Sankar Tanguturi <stanguturi@vmware.com>
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 3, as
-# published by the Free Software Foundation.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-
-class BootProtoEnum:
- """Specifies the NIC Boot Settings."""
-
- DHCP = 'dhcp'
- STATIC = 'static'
+# vi: ts=4 expandtab
+#
+# Copyright (C) 2015 Canonical Ltd.
+# Copyright (C) 2015 VMware Inc.
+#
+# Author: Sankar Tanguturi <stanguturi@vmware.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 3, as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+class BootProtoEnum(object):
+ """Specifies the NIC Boot Settings."""
+
+ DHCP = 'dhcp'
+ STATIC = 'static'
diff --git a/cloudinit/sources/helpers/vmware/imc/config.py b/cloudinit/sources/helpers/vmware/imc/config.py
index aebc12a0..d645c497 100644
--- a/cloudinit/sources/helpers/vmware/imc/config.py
+++ b/cloudinit/sources/helpers/vmware/imc/config.py
@@ -1,95 +1,95 @@
-# vi: ts=4 expandtab
-#
-# Copyright (C) 2015 Canonical Ltd.
-# Copyright (C) 2015 VMware Inc.
-#
-# Author: Sankar Tanguturi <stanguturi@vmware.com>
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 3, as
-# published by the Free Software Foundation.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-from .nic import Nic
-
-
-class Config:
- """
- Stores the Contents specified in the Customization
- Specification file.
- """
-
- DNS = 'DNS|NAMESERVER|'
- SUFFIX = 'DNS|SUFFIX|'
- PASS = 'PASSWORD|-PASS'
- TIMEZONE = 'DATETIME|TIMEZONE'
- UTC = 'DATETIME|UTC'
- HOSTNAME = 'NETWORK|HOSTNAME'
- DOMAINNAME = 'NETWORK|DOMAINNAME'
-
- def __init__(self, configFile):
- self._configFile = configFile
-
- @property
- def host_name(self):
- """Return the hostname."""
- return self._configFile.get(Config.HOSTNAME, None)
-
- @property
- def domain_name(self):
- """Return the domain name."""
- return self._configFile.get(Config.DOMAINNAME, None)
-
- @property
- def timezone(self):
- """Return the timezone."""
- return self._configFile.get(Config.TIMEZONE, None)
-
- @property
- def utc(self):
- """Retrieves whether to set time to UTC or Local."""
- return self._configFile.get(Config.UTC, None)
-
- @property
- def admin_password(self):
- """Return the root password to be set."""
- return self._configFile.get(Config.PASS, None)
-
- @property
- def name_servers(self):
- """Return the list of DNS servers."""
- res = []
- cnt = self._configFile.get_count_with_prefix(Config.DNS)
- for i in range(1, cnt + 1):
- key = Config.DNS + str(i)
- res.append(self._configFile[key])
-
- return res
-
- @property
- def dns_suffixes(self):
- """Return the list of DNS Suffixes."""
- res = []
- cnt = self._configFile.get_count_with_prefix(Config.SUFFIX)
- for i in range(1, cnt + 1):
- key = Config.SUFFIX + str(i)
- res.append(self._configFile[key])
-
- return res
-
- @property
- def nics(self):
- """Return the list of associated NICs."""
- res = []
- nics = self._configFile['NIC-CONFIG|NICS']
- for nic in nics.split(','):
- res.append(Nic(nic, self._configFile))
-
- return res
+# vi: ts=4 expandtab
+#
+# Copyright (C) 2015 Canonical Ltd.
+# Copyright (C) 2015 VMware Inc.
+#
+# Author: Sankar Tanguturi <stanguturi@vmware.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 3, as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+from .nic import Nic
+
+
+class Config(object):
+ """
+ Stores the Contents specified in the Customization
+ Specification file.
+ """
+
+ DNS = 'DNS|NAMESERVER|'
+ SUFFIX = 'DNS|SUFFIX|'
+ PASS = 'PASSWORD|-PASS'
+ TIMEZONE = 'DATETIME|TIMEZONE'
+ UTC = 'DATETIME|UTC'
+ HOSTNAME = 'NETWORK|HOSTNAME'
+ DOMAINNAME = 'NETWORK|DOMAINNAME'
+
+ def __init__(self, configFile):
+ self._configFile = configFile
+
+ @property
+ def host_name(self):
+ """Return the hostname."""
+ return self._configFile.get(Config.HOSTNAME, None)
+
+ @property
+ def domain_name(self):
+ """Return the domain name."""
+ return self._configFile.get(Config.DOMAINNAME, None)
+
+ @property
+ def timezone(self):
+ """Return the timezone."""
+ return self._configFile.get(Config.TIMEZONE, None)
+
+ @property
+ def utc(self):
+ """Retrieves whether to set time to UTC or Local."""
+ return self._configFile.get(Config.UTC, None)
+
+ @property
+ def admin_password(self):
+ """Return the root password to be set."""
+ return self._configFile.get(Config.PASS, None)
+
+ @property
+ def name_servers(self):
+ """Return the list of DNS servers."""
+ res = []
+ cnt = self._configFile.get_count_with_prefix(Config.DNS)
+ for i in range(1, cnt + 1):
+ key = Config.DNS + str(i)
+ res.append(self._configFile[key])
+
+ return res
+
+ @property
+ def dns_suffixes(self):
+ """Return the list of DNS Suffixes."""
+ res = []
+ cnt = self._configFile.get_count_with_prefix(Config.SUFFIX)
+ for i in range(1, cnt + 1):
+ key = Config.SUFFIX + str(i)
+ res.append(self._configFile[key])
+
+ return res
+
+ @property
+ def nics(self):
+ """Return the list of associated NICs."""
+ res = []
+ nics = self._configFile['NIC-CONFIG|NICS']
+ for nic in nics.split(','):
+ res.append(Nic(nic, self._configFile))
+
+ return res
diff --git a/cloudinit/sources/helpers/vmware/imc/config_namespace.py b/cloudinit/sources/helpers/vmware/imc/config_namespace.py
index 7266b699..b28830f5 100644
--- a/cloudinit/sources/helpers/vmware/imc/config_namespace.py
+++ b/cloudinit/sources/helpers/vmware/imc/config_namespace.py
@@ -1,25 +1,25 @@
-# vi: ts=4 expandtab
-#
-# Copyright (C) 2015 Canonical Ltd.
-# Copyright (C) 2015 VMware Inc.
-#
-# Author: Sankar Tanguturi <stanguturi@vmware.com>
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 3, as
-# published by the Free Software Foundation.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-from .config_source import ConfigSource
-
-
-class ConfigNamespace(ConfigSource):
- """Specifies the Config Namespace."""
- pass
+# vi: ts=4 expandtab
+#
+# Copyright (C) 2015 Canonical Ltd.
+# Copyright (C) 2015 VMware Inc.
+#
+# Author: Sankar Tanguturi <stanguturi@vmware.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 3, as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+from .config_source import ConfigSource
+
+
+class ConfigNamespace(ConfigSource):
+ """Specifies the Config Namespace."""
+ pass
diff --git a/cloudinit/sources/helpers/vmware/imc/config_nic.py b/cloudinit/sources/helpers/vmware/imc/config_nic.py
index 77098a05..511cc918 100644
--- a/cloudinit/sources/helpers/vmware/imc/config_nic.py
+++ b/cloudinit/sources/helpers/vmware/imc/config_nic.py
@@ -26,7 +26,7 @@ from cloudinit import util
logger = logging.getLogger(__name__)
-class NicConfigurator:
+class NicConfigurator(object):
def __init__(self, nics):
"""
Initialize the Nic Configurator
diff --git a/cloudinit/sources/helpers/vmware/imc/config_source.py b/cloudinit/sources/helpers/vmware/imc/config_source.py
index a367e476..28ef306a 100644
--- a/cloudinit/sources/helpers/vmware/imc/config_source.py
+++ b/cloudinit/sources/helpers/vmware/imc/config_source.py
@@ -1,23 +1,23 @@
-# vi: ts=4 expandtab
-#
-# Copyright (C) 2015 Canonical Ltd.
-# Copyright (C) 2015 VMware Inc.
-#
-# Author: Sankar Tanguturi <stanguturi@vmware.com>
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 3, as
-# published by the Free Software Foundation.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-
-class ConfigSource:
- """Specifies a source for the Config Content."""
- pass
+# vi: ts=4 expandtab
+#
+# Copyright (C) 2015 Canonical Ltd.
+# Copyright (C) 2015 VMware Inc.
+#
+# Author: Sankar Tanguturi <stanguturi@vmware.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 3, as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+class ConfigSource(object):
+ """Specifies a source for the Config Content."""
+ pass
diff --git a/cloudinit/sources/helpers/vmware/imc/guestcust_error.py b/cloudinit/sources/helpers/vmware/imc/guestcust_error.py
index 1b04161f..d1546852 100644
--- a/cloudinit/sources/helpers/vmware/imc/guestcust_error.py
+++ b/cloudinit/sources/helpers/vmware/imc/guestcust_error.py
@@ -1,24 +1,24 @@
-# vi: ts=4 expandtab
-#
-# Copyright (C) 2016 Canonical Ltd.
-# Copyright (C) 2016 VMware Inc.
-#
-# Author: Sankar Tanguturi <stanguturi@vmware.com>
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 3, as
-# published by the Free Software Foundation.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-
-class GuestCustErrorEnum:
- """Specifies different errors of Guest Customization engine"""
-
- GUESTCUST_ERROR_SUCCESS = 0
+# vi: ts=4 expandtab
+#
+# Copyright (C) 2016 Canonical Ltd.
+# Copyright (C) 2016 VMware Inc.
+#
+# Author: Sankar Tanguturi <stanguturi@vmware.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 3, as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+class GuestCustErrorEnum(object):
+ """Specifies different errors of Guest Customization engine"""
+
+ GUESTCUST_ERROR_SUCCESS = 0
diff --git a/cloudinit/sources/helpers/vmware/imc/guestcust_event.py b/cloudinit/sources/helpers/vmware/imc/guestcust_event.py
index fc22568f..ce90c898 100644
--- a/cloudinit/sources/helpers/vmware/imc/guestcust_event.py
+++ b/cloudinit/sources/helpers/vmware/imc/guestcust_event.py
@@ -1,27 +1,27 @@
-# vi: ts=4 expandtab
-#
-# Copyright (C) 2016 Canonical Ltd.
-# Copyright (C) 2016 VMware Inc.
-#
-# Author: Sankar Tanguturi <stanguturi@vmware.com>
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 3, as
-# published by the Free Software Foundation.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-
-class GuestCustEventEnum:
- """Specifies different types of Guest Customization Events"""
-
- GUESTCUST_EVENT_CUSTOMIZE_FAILED = 100
- GUESTCUST_EVENT_NETWORK_SETUP_FAILED = 101
- GUESTCUST_EVENT_ENABLE_NICS = 103
- GUESTCUST_EVENT_QUERY_NICS = 104
+# vi: ts=4 expandtab
+#
+# Copyright (C) 2016 Canonical Ltd.
+# Copyright (C) 2016 VMware Inc.
+#
+# Author: Sankar Tanguturi <stanguturi@vmware.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 3, as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+class GuestCustEventEnum(object):
+ """Specifies different types of Guest Customization Events"""
+
+ GUESTCUST_EVENT_CUSTOMIZE_FAILED = 100
+ GUESTCUST_EVENT_NETWORK_SETUP_FAILED = 101
+ GUESTCUST_EVENT_ENABLE_NICS = 103
+ GUESTCUST_EVENT_QUERY_NICS = 104
diff --git a/cloudinit/sources/helpers/vmware/imc/guestcust_state.py b/cloudinit/sources/helpers/vmware/imc/guestcust_state.py
index f255be5f..422a096d 100644
--- a/cloudinit/sources/helpers/vmware/imc/guestcust_state.py
+++ b/cloudinit/sources/helpers/vmware/imc/guestcust_state.py
@@ -1,25 +1,25 @@
-# vi: ts=4 expandtab
-#
-# Copyright (C) 2016 Canonical Ltd.
-# Copyright (C) 2016 VMware Inc.
-#
-# Author: Sankar Tanguturi <stanguturi@vmware.com>
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 3, as
-# published by the Free Software Foundation.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-
-class GuestCustStateEnum:
- """Specifies different states of Guest Customization engine"""
-
- GUESTCUST_STATE_RUNNING = 4
- GUESTCUST_STATE_DONE = 5
+# vi: ts=4 expandtab
+#
+# Copyright (C) 2016 Canonical Ltd.
+# Copyright (C) 2016 VMware Inc.
+#
+# Author: Sankar Tanguturi <stanguturi@vmware.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 3, as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+class GuestCustStateEnum(object):
+ """Specifies different states of Guest Customization engine"""
+
+ GUESTCUST_STATE_RUNNING = 4
+ GUESTCUST_STATE_DONE = 5
diff --git a/cloudinit/sources/helpers/vmware/imc/guestcust_util.py b/cloudinit/sources/helpers/vmware/imc/guestcust_util.py
index d39f0a65..c07c5949 100644
--- a/cloudinit/sources/helpers/vmware/imc/guestcust_util.py
+++ b/cloudinit/sources/helpers/vmware/imc/guestcust_util.py
@@ -1,128 +1,128 @@
-# vi: ts=4 expandtab
-#
-# Copyright (C) 2016 Canonical Ltd.
-# Copyright (C) 2016 VMware Inc.
-#
-# Author: Sankar Tanguturi <stanguturi@vmware.com>
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 3, as
-# published by the Free Software Foundation.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-import logging
-import os
-import time
-
-from cloudinit import util
-
-from .guestcust_state import GuestCustStateEnum
-from .guestcust_event import GuestCustEventEnum
-
-logger = logging.getLogger(__name__)
-
-
-CLOUDINIT_LOG_FILE = "/var/log/cloud-init.log"
-QUERY_NICS_SUPPORTED = "queryNicsSupported"
-NICS_STATUS_CONNECTED = "connected"
-
-
-# This will send a RPC command to the underlying
-# VMware Virtualization Platform.
-def send_rpc(rpc):
- if not rpc:
- return None
-
- out = ""
- err = "Error sending the RPC command"
-
- try:
- logger.debug("Sending RPC command: %s", rpc)
- (out, err) = util.subp(["vmware-rpctool", rpc], rcs=[0])
- # Remove the trailing newline in the output.
- if out:
- out = out.rstrip()
- except Exception as e:
- logger.debug("Failed to send RPC command")
- logger.exception(e)
-
- return (out, err)
-
-
-# This will send the customization status to the
-# underlying VMware Virtualization Platform.
-def set_customization_status(custstate, custerror, errormessage=None):
- message = ""
-
- if errormessage:
- message = CLOUDINIT_LOG_FILE + "@" + errormessage
- else:
- message = CLOUDINIT_LOG_FILE
-
- rpc = "deployPkg.update.state %d %d %s" % (custstate, custerror, message)
- (out, err) = send_rpc(rpc)
- return (out, err)
-
-
-# This will read the file nics.txt in the specified directory
-# and return the content
-def get_nics_to_enable(dirpath):
- if not dirpath:
- return None
-
- NICS_SIZE = 1024
- nicsfilepath = os.path.join(dirpath, "nics.txt")
- if not os.path.exists(nicsfilepath):
- return None
-
- with open(nicsfilepath, 'r') as fp:
- nics = fp.read(NICS_SIZE)
-
- return nics
-
-
-# This will send a RPC command to the underlying VMware Virtualization platform
-# and enable nics.
-def enable_nics(nics):
- if not nics:
- logger.warning("No Nics found")
- return
-
- enableNicsWaitRetries = 5
- enableNicsWaitCount = 5
- enableNicsWaitSeconds = 1
-
- for attempt in range(0, enableNicsWaitRetries):
- logger.debug("Trying to connect interfaces, attempt %d", attempt)
- (out, err) = set_customization_status(
- GuestCustStateEnum.GUESTCUST_STATE_RUNNING,
- GuestCustEventEnum.GUESTCUST_EVENT_ENABLE_NICS,
- nics)
- if not out:
- time.sleep(enableNicsWaitCount * enableNicsWaitSeconds)
- continue
-
- if out != QUERY_NICS_SUPPORTED:
- logger.warning("NICS connection status query is not supported")
- return
-
- for count in range(0, enableNicsWaitCount):
- (out, err) = set_customization_status(
- GuestCustStateEnum.GUESTCUST_STATE_RUNNING,
- GuestCustEventEnum.GUESTCUST_EVENT_QUERY_NICS,
- nics)
- if out and out == NICS_STATUS_CONNECTED:
- logger.info("NICS are connected on %d second", count)
- return
-
- time.sleep(enableNicsWaitSeconds)
-
- logger.warning("Can't connect network interfaces after %d attempts",
- enableNicsWaitRetries)
+# vi: ts=4 expandtab
+#
+# Copyright (C) 2016 Canonical Ltd.
+# Copyright (C) 2016 VMware Inc.
+#
+# Author: Sankar Tanguturi <stanguturi@vmware.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 3, as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import logging
+import os
+import time
+
+from cloudinit import util
+
+from .guestcust_event import GuestCustEventEnum
+from .guestcust_state import GuestCustStateEnum
+
+logger = logging.getLogger(__name__)
+
+
+CLOUDINIT_LOG_FILE = "/var/log/cloud-init.log"
+QUERY_NICS_SUPPORTED = "queryNicsSupported"
+NICS_STATUS_CONNECTED = "connected"
+
+
+# This will send a RPC command to the underlying
+# VMware Virtualization Platform.
+def send_rpc(rpc):
+ if not rpc:
+ return None
+
+ out = ""
+ err = "Error sending the RPC command"
+
+ try:
+ logger.debug("Sending RPC command: %s", rpc)
+ (out, err) = util.subp(["vmware-rpctool", rpc], rcs=[0])
+ # Remove the trailing newline in the output.
+ if out:
+ out = out.rstrip()
+ except Exception as e:
+ logger.debug("Failed to send RPC command")
+ logger.exception(e)
+
+ return (out, err)
+
+
+# This will send the customization status to the
+# underlying VMware Virtualization Platform.
+def set_customization_status(custstate, custerror, errormessage=None):
+ message = ""
+
+ if errormessage:
+ message = CLOUDINIT_LOG_FILE + "@" + errormessage
+ else:
+ message = CLOUDINIT_LOG_FILE
+
+ rpc = "deployPkg.update.state %d %d %s" % (custstate, custerror, message)
+ (out, err) = send_rpc(rpc)
+ return (out, err)
+
+
+# This will read the file nics.txt in the specified directory
+# and return the content
+def get_nics_to_enable(dirpath):
+ if not dirpath:
+ return None
+
+ NICS_SIZE = 1024
+ nicsfilepath = os.path.join(dirpath, "nics.txt")
+ if not os.path.exists(nicsfilepath):
+ return None
+
+ with open(nicsfilepath, 'r') as fp:
+ nics = fp.read(NICS_SIZE)
+
+ return nics
+
+
+# This will send a RPC command to the underlying VMware Virtualization platform
+# and enable nics.
+def enable_nics(nics):
+ if not nics:
+ logger.warning("No Nics found")
+ return
+
+ enableNicsWaitRetries = 5
+ enableNicsWaitCount = 5
+ enableNicsWaitSeconds = 1
+
+ for attempt in range(0, enableNicsWaitRetries):
+ logger.debug("Trying to connect interfaces, attempt %d", attempt)
+ (out, err) = set_customization_status(
+ GuestCustStateEnum.GUESTCUST_STATE_RUNNING,
+ GuestCustEventEnum.GUESTCUST_EVENT_ENABLE_NICS,
+ nics)
+ if not out:
+ time.sleep(enableNicsWaitCount * enableNicsWaitSeconds)
+ continue
+
+ if out != QUERY_NICS_SUPPORTED:
+ logger.warning("NICS connection status query is not supported")
+ return
+
+ for count in range(0, enableNicsWaitCount):
+ (out, err) = set_customization_status(
+ GuestCustStateEnum.GUESTCUST_STATE_RUNNING,
+ GuestCustEventEnum.GUESTCUST_EVENT_QUERY_NICS,
+ nics)
+ if out and out == NICS_STATUS_CONNECTED:
+ logger.info("NICS are connected on %d second", count)
+ return
+
+ time.sleep(enableNicsWaitSeconds)
+
+ logger.warning("Can't connect network interfaces after %d attempts",
+ enableNicsWaitRetries)
diff --git a/cloudinit/sources/helpers/vmware/imc/ipv4_mode.py b/cloudinit/sources/helpers/vmware/imc/ipv4_mode.py
index 33f88726..873ddc3b 100644
--- a/cloudinit/sources/helpers/vmware/imc/ipv4_mode.py
+++ b/cloudinit/sources/helpers/vmware/imc/ipv4_mode.py
@@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
-class Ipv4ModeEnum:
+class Ipv4ModeEnum(object):
"""
The IPv4 configuration mode which directly represents the user's goal.
diff --git a/cloudinit/sources/helpers/vmware/imc/nic_base.py b/cloudinit/sources/helpers/vmware/imc/nic_base.py
index 030ba311..3c892db0 100644
--- a/cloudinit/sources/helpers/vmware/imc/nic_base.py
+++ b/cloudinit/sources/helpers/vmware/imc/nic_base.py
@@ -18,7 +18,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
-class NicBase:
+class NicBase(object):
"""
Define what are expected of each nic.
The following properties should be provided in an implementation class.
@@ -93,7 +93,7 @@ class NicBase:
raise NotImplementedError('Check constraints on properties')
-class StaticIpv4Base:
+class StaticIpv4Base(object):
"""
Define what are expected of a static IPv4 setting
The following properties should be provided in an implementation class.
@@ -124,7 +124,7 @@ class StaticIpv4Base:
raise NotImplementedError('Ipv4 GATEWAY')
-class StaticIpv6Base:
+class StaticIpv6Base(object):
"""Define what are expected of a static IPv6 setting
The following properties should be provided in an implementation class.
"""
diff --git a/cloudinit/stages.py b/cloudinit/stages.py
index ffb15165..62d066de 100644
--- a/cloudinit/stages.py
+++ b/cloudinit/stages.py
@@ -44,10 +44,10 @@ from cloudinit import helpers
from cloudinit import importer
from cloudinit import log as logging
from cloudinit import net
+from cloudinit.reporting import events
from cloudinit import sources
from cloudinit import type_utils
from cloudinit import util
-from cloudinit.reporting import events
LOG = logging.getLogger(__name__)
@@ -483,7 +483,7 @@ class Init(object):
c_handlers.initialized.remove(mod)
try:
handlers.call_end(mod, data, frequency)
- except:
+ except Exception:
util.logexc(LOG, "Failed to finalize handler: %s", mod)
try:
diff --git a/cloudinit/url_helper.py b/cloudinit/url_helper.py
index 936f7da5..c05e9d90 100644
--- a/cloudinit/url_helper.py
+++ b/cloudinit/url_helper.py
@@ -28,8 +28,9 @@ import time
from email.utils import parsedate
from functools import partial
-from requests import exceptions
+
import oauthlib.oauth1 as oauth1
+from requests import exceptions
from six.moves.urllib.parse import (
urlparse, urlunparse,
@@ -61,7 +62,7 @@ try:
SSL_ENABLED = True
if _REQ_VER >= LooseVersion('0.7.0') and _REQ_VER < LooseVersion('1.0.0'):
CONFIG_ENABLED = True
-except:
+except ImportError:
pass
diff --git a/cloudinit/user_data.py b/cloudinit/user_data.py
index f7c5787c..f0631906 100644
--- a/cloudinit/user_data.py
+++ b/cloudinit/user_data.py
@@ -178,7 +178,7 @@ class UserDataProcessor(object):
payload = util.load_yaml(msg.get_payload(decode=True))
if payload:
payload_idx = payload.get('launch-index')
- except:
+ except Exception:
pass
# Header overrides contents, for now (?) or the other way around?
if header_idx is not None:
diff --git a/cloudinit/util.py b/cloudinit/util.py
index 0773af69..d6b80dbe 100644
--- a/cloudinit/util.py
+++ b/cloudinit/util.py
@@ -288,7 +288,7 @@ def fork_cb(child_cb, *args, **kwargs):
try:
child_cb(*args, **kwargs)
os._exit(0)
- except:
+ except Exception:
logexc(LOG, "Failed forking and calling callback %s",
type_utils.obj_name(child_cb))
os._exit(1)
@@ -482,7 +482,7 @@ def is_ipv4(instr):
try:
toks = [x for x in toks if int(x) < 256 and int(x) >= 0]
- except:
+ except Exception:
return False
return len(toks) == 4
@@ -1220,7 +1220,7 @@ def get_cmdline():
else:
try:
cmdline = load_file("/proc/cmdline").strip()
- except:
+ except Exception:
cmdline = ""
PROC_CMDLINE = cmdline
@@ -1390,7 +1390,7 @@ def read_write_cmdline_url(target_fn):
if not os.path.exists(target_fn):
try:
(key, url, content) = get_cmdline_url()
- except:
+ except Exception:
logexc(LOG, "Failed fetching command line url")
return
try:
@@ -1401,7 +1401,7 @@ def read_write_cmdline_url(target_fn):
elif key and not content:
LOG.debug(("Command line key %s with url"
" %s had no contents"), key, url)
- except:
+ except Exception:
logexc(LOG, "Failed writing url content to %s", target_fn)
@@ -1459,7 +1459,7 @@ def mounts():
mp = m.group(2)
fstype = m.group(3)
opts = m.group(4)
- except:
+ except Exception:
continue
# If the name of the mount point contains spaces these
# can be escaped as '\040', so undo that..
@@ -1585,7 +1585,7 @@ def copy(src, dest):
def time_rfc2822():
try:
ts = time.strftime("%a, %d %b %Y %H:%M:%S %z", time.gmtime())
- except:
+ except Exception:
ts = "??"
return ts
@@ -1611,7 +1611,7 @@ def uptime():
bootup = buf.value
uptime_str = now - bootup
- except:
+ except Exception:
logexc(LOG, "Unable to read uptime using method: %s" % method)
return uptime_str
@@ -2065,7 +2065,7 @@ def log_time(logfunc, msg, func, args=None, kwargs=None, get_uptime=False):
tmsg += " (N/A)"
try:
logfunc(msg + tmsg)
- except:
+ except Exception:
pass
return ret
diff --git a/doc/examples/cloud-config-boot-cmds.txt b/doc/examples/cloud-config-boot-cmds.txt
index b281d327..3e59755d 100644
--- a/doc/examples/cloud-config-boot-cmds.txt
+++ b/doc/examples/cloud-config-boot-cmds.txt
@@ -7,9 +7,9 @@
# bootcmd should really only be used for things that could not be
# done later in the boot process. bootcmd is very much like
# boothook, but possibly with more friendly.
-# * bootcmd will run on every boot
-# * the INSTANCE_ID variable will be set to the current instance id.
-# * you can use 'cloud-init-boot-per' command to help only run once
+# - bootcmd will run on every boot
+# - the INSTANCE_ID variable will be set to the current instance id.
+# - you can use 'cloud-init-boot-per' command to help only run once
bootcmd:
- echo 192.168.1.130 us.archive.ubuntu.com > /etc/hosts
- [ cloud-init-per, once, mymkfs, mkfs, /dev/vdb ]
diff --git a/doc/examples/cloud-config-run-cmds.txt b/doc/examples/cloud-config-run-cmds.txt
index 61b3bd63..3bb06864 100644
--- a/doc/examples/cloud-config-run-cmds.txt
+++ b/doc/examples/cloud-config-run-cmds.txt
@@ -5,12 +5,13 @@
# runcmd contains a list of either lists or a string
# each item will be executed in order at rc.local like level with
# output to the console
+# - runcmd only runs during the first boot
# - if the item is a list, the items will be properly executed as if
# passed to execve(3) (with the first arg as the command).
# - if the item is a string, it will be simply written to the file and
# will be interpreted by 'sh'
#
-# Note, that the list has to be proper yaml, so you have to escape
+# Note, that the list has to be proper yaml, so you have to quote
# any characters yaml would eat (':' can be problematic)
runcmd:
- [ ls, -l, / ]
diff --git a/setup.py b/setup.py
index f86727b2..db46eae9 100755
--- a/setup.py
+++ b/setup.py
@@ -57,15 +57,15 @@ def tiny_p(cmd, capture=True):
def pkg_config_read(library, var):
fallbacks = {
- 'systemd': {
- 'systemdsystemunitdir': '/lib/systemd/system',
- 'systemdsystemgeneratordir': '/lib/systemd/system-generators',
- }
+ 'systemd': {
+ 'systemdsystemunitdir': '/lib/systemd/system',
+ 'systemdsystemgeneratordir': '/lib/systemd/system-generators',
+ }
}
cmd = ['pkg-config', '--variable=%s' % var, library]
try:
(path, err) = tiny_p(cmd)
- except:
+ except Exception:
return fallbacks[library][var]
return str(path).strip()
@@ -212,4 +212,4 @@ setuptools.setup(
data_files=data_files,
install_requires=requirements,
cmdclass=cmdclass,
- )
+)
diff --git a/test-requirements.txt b/test-requirements.txt
index 9b3d07c5..2ab53707 100644
--- a/test-requirements.txt
+++ b/test-requirements.txt
@@ -1,7 +1,14 @@
+# Needed generally in tests
httpretty>=0.7.1
mock
nose
-pep8==1.5.7
-pyflakes
+
+# Only really needed on older versions of python
contextlib2
setuptools
+
+# Used for syle checking
+pep8==1.7.0
+pyflakes==1.1.0
+flake8==2.5.4
+hacking==0.10.2
diff --git a/tests/unittests/helpers.py b/tests/unittests/helpers.py
index fb9c83a7..50b2bd72 100644
--- a/tests/unittests/helpers.py
+++ b/tests/unittests/helpers.py
@@ -2,8 +2,8 @@ from __future__ import print_function
import functools
import os
-import sys
import shutil
+import sys
import tempfile
import unittest
diff --git a/tests/unittests/test_builtin_handlers.py b/tests/unittests/test_builtin_handlers.py
index ad32d0b2..dea908d7 100644
--- a/tests/unittests/test_builtin_handlers.py
+++ b/tests/unittests/test_builtin_handlers.py
@@ -40,7 +40,7 @@ class TestBuiltins(test_helpers.FilesystemMockingTestCase):
'test.conf', 'blah', freq)
h.handle_part('', handlers.CONTENT_END,
None, None, None)
- self.assertEquals(0, len(os.listdir(up_root)))
+ self.assertEqual(0, len(os.listdir(up_root)))
def test_upstart_frequency_single(self):
# files should be written out when frequency is ! per-instance
@@ -67,7 +67,7 @@ class TestBuiltins(test_helpers.FilesystemMockingTestCase):
h.handle_part('', handlers.CONTENT_END,
None, None, None)
- self.assertEquals(len(os.listdir('/etc/upstart')), 1)
+ self.assertEqual(len(os.listdir('/etc/upstart')), 1)
mockobj.assert_called_once_with(
['initctl', 'reload-configuration'], capture=False)
diff --git a/tests/unittests/test_cli.py b/tests/unittests/test_cli.py
index ed863399..f537bd83 100644
--- a/tests/unittests/test_cli.py
+++ b/tests/unittests/test_cli.py
@@ -1,7 +1,7 @@
import imp
import os
-import sys
import six
+import sys
from . import helpers as test_helpers
@@ -31,7 +31,7 @@ class TestCLI(test_helpers.FilesystemMockingTestCase):
'cli', open(BIN_CLOUDINIT), '', ('', 'r', imp.PY_SOURCE))
try:
return cli.main()
- except:
+ except Exception:
pass
@test_helpers.skipIf(not os.path.isfile(BIN_CLOUDINIT), "no bin/cloudinit")
diff --git a/tests/unittests/test_data.py b/tests/unittests/test_data.py
index 9c1ec1d4..1923e2af 100644
--- a/tests/unittests/test_data.py
+++ b/tests/unittests/test_data.py
@@ -106,9 +106,9 @@ class TestConsumeUserData(helpers.FilesystemMockingTestCase):
ci.consume_data()
cc_contents = util.load_file(ci.paths.get_ipath("cloud_config"))
cc = util.load_yaml(cc_contents)
- self.assertEquals(2, len(cc))
- self.assertEquals('qux', cc['baz'])
- self.assertEquals('qux2', cc['bar'])
+ self.assertEqual(2, len(cc))
+ self.assertEqual('qux', cc['baz'])
+ self.assertEqual('qux2', cc['bar'])
def test_simple_jsonp_vendor_and_user(self):
# test that user-data wins over vendor
@@ -145,9 +145,9 @@ class TestConsumeUserData(helpers.FilesystemMockingTestCase):
(_which_ran, _failures) = mods.run_section('cloud_init_modules')
cfg = mods.cfg
self.assertIn('vendor_data', cfg)
- self.assertEquals('qux', cfg['baz'])
- self.assertEquals('qux2', cfg['bar'])
- self.assertEquals('quxC', cfg['foo'])
+ self.assertEqual('qux', cfg['baz'])
+ self.assertEqual('qux2', cfg['bar'])
+ self.assertEqual('quxC', cfg['foo'])
def test_simple_jsonp_no_vendor_consumed(self):
# make sure that vendor data is not consumed
@@ -184,8 +184,8 @@ class TestConsumeUserData(helpers.FilesystemMockingTestCase):
mods = stages.Modules(initer)
(_which_ran, _failures) = mods.run_section('cloud_init_modules')
cfg = mods.cfg
- self.assertEquals('qux', cfg['baz'])
- self.assertEquals('qux2', cfg['bar'])
+ self.assertEqual('qux', cfg['baz'])
+ self.assertEqual('qux2', cfg['bar'])
self.assertNotIn('foo', cfg)
def test_mixed_cloud_config(self):
@@ -222,8 +222,8 @@ c: d
ci.consume_data()
cc_contents = util.load_file(ci.paths.get_ipath("cloud_config"))
cc = util.load_yaml(cc_contents)
- self.assertEquals(1, len(cc))
- self.assertEquals('c', cc['a'])
+ self.assertEqual(1, len(cc))
+ self.assertEqual('c', cc['a'])
def test_vendor_user_yaml_cloud_config(self):
vendor_blob = '''
@@ -263,8 +263,8 @@ run:
(_which_ran, _failures) = mods.run_section('cloud_init_modules')
cfg = mods.cfg
self.assertIn('vendor_data', cfg)
- self.assertEquals('c', cfg['a'])
- self.assertEquals('user', cfg['name'])
+ self.assertEqual('c', cfg['a'])
+ self.assertEqual('user', cfg['name'])
self.assertNotIn('x', cfg['run'])
self.assertNotIn('y', cfg['run'])
self.assertIn('z', cfg['run'])
@@ -358,10 +358,10 @@ p: 1
None)
contents = util.load_file(paths.get_ipath('cloud_config'))
contents = util.load_yaml(contents)
- self.assertEquals(contents['run'], ['b', 'c', 'stuff', 'morestuff'])
- self.assertEquals(contents['a'], 'be')
- self.assertEquals(contents['e'], [1, 2, 3])
- self.assertEquals(contents['p'], 1)
+ self.assertEqual(contents['run'], ['b', 'c', 'stuff', 'morestuff'])
+ self.assertEqual(contents['a'], 'be')
+ self.assertEqual(contents['e'], [1, 2, 3])
+ self.assertEqual(contents['p'], 1)
def test_unhandled_type_warning(self):
"""Raw text without magic is ignored but shows warning."""
@@ -411,10 +411,10 @@ c: 4
contents = util.load_file(ci.paths.get_ipath("cloud_config"))
contents = util.load_yaml(contents)
self.assertTrue(isinstance(contents, dict))
- self.assertEquals(3, len(contents))
- self.assertEquals(2, contents['a'])
- self.assertEquals(3, contents['b'])
- self.assertEquals(4, contents['c'])
+ self.assertEqual(3, len(contents))
+ self.assertEqual(2, contents['a'])
+ self.assertEqual(3, contents['b'])
+ self.assertEqual(4, contents['c'])
def test_mime_text_plain(self):
"""Mime message of type text/plain is ignored but shows warning."""
@@ -449,8 +449,7 @@ c: 4
mockobj.assert_has_calls([
mock.call(outpath, script, 0o700),
- mock.call(ci.paths.get_ipath("cloud_config"), "", 0o600),
- ])
+ mock.call(ci.paths.get_ipath("cloud_config"), "", 0o600)])
def test_mime_text_x_shellscript(self):
"""Mime message of type text/x-shellscript is treated as script."""
@@ -470,8 +469,7 @@ c: 4
mockobj.assert_has_calls([
mock.call(outpath, script, 0o700),
- mock.call(ci.paths.get_ipath("cloud_config"), "", 0o600),
- ])
+ mock.call(ci.paths.get_ipath("cloud_config"), "", 0o600)])
def test_mime_text_plain_shell(self):
"""Mime type text/plain starting #!/bin/sh is treated as script."""
@@ -491,8 +489,7 @@ c: 4
mockobj.assert_has_calls([
mock.call(outpath, script, 0o700),
- mock.call(ci.paths.get_ipath("cloud_config"), "", 0o600),
- ])
+ mock.call(ci.paths.get_ipath("cloud_config"), "", 0o600)])
def test_mime_application_octet_stream(self):
"""Mime type application/octet-stream is ignored but shows warning."""
diff --git a/tests/unittests/test_datasource/test_altcloud.py b/tests/unittests/test_datasource/test_altcloud.py
index 85759c68..12966563 100644
--- a/tests/unittests/test_datasource/test_altcloud.py
+++ b/tests/unittests/test_datasource/test_altcloud.py
@@ -134,7 +134,7 @@ class TestGetCloudType(TestCase):
'''
util.read_dmi_data = _dmi_data('RHEV')
dsrc = DataSourceAltCloud({}, None, self.paths)
- self.assertEquals('RHEV', dsrc.get_cloud_type())
+ self.assertEqual('RHEV', dsrc.get_cloud_type())
def test_vsphere(self):
'''
@@ -143,7 +143,7 @@ class TestGetCloudType(TestCase):
'''
util.read_dmi_data = _dmi_data('VMware Virtual Platform')
dsrc = DataSourceAltCloud({}, None, self.paths)
- self.assertEquals('VSPHERE', dsrc.get_cloud_type())
+ self.assertEqual('VSPHERE', dsrc.get_cloud_type())
def test_unknown(self):
'''
@@ -152,7 +152,7 @@ class TestGetCloudType(TestCase):
'''
util.read_dmi_data = _dmi_data('Unrecognized Platform')
dsrc = DataSourceAltCloud({}, None, self.paths)
- self.assertEquals('UNKNOWN', dsrc.get_cloud_type())
+ self.assertEqual('UNKNOWN', dsrc.get_cloud_type())
class TestGetDataCloudInfoFile(TestCase):
@@ -187,7 +187,7 @@ class TestGetDataCloudInfoFile(TestCase):
_write_cloud_info_file('RHEV')
dsrc = DataSourceAltCloud({}, None, self.paths)
dsrc.user_data_rhevm = lambda: True
- self.assertEquals(True, dsrc.get_data())
+ self.assertEqual(True, dsrc.get_data())
def test_vsphere(self):
'''Success Test module get_data() forcing VSPHERE.'''
@@ -195,7 +195,7 @@ class TestGetDataCloudInfoFile(TestCase):
_write_cloud_info_file('VSPHERE')
dsrc = DataSourceAltCloud({}, None, self.paths)
dsrc.user_data_vsphere = lambda: True
- self.assertEquals(True, dsrc.get_data())
+ self.assertEqual(True, dsrc.get_data())
def test_fail_rhev(self):
'''Failure Test module get_data() forcing RHEV.'''
@@ -203,7 +203,7 @@ class TestGetDataCloudInfoFile(TestCase):
_write_cloud_info_file('RHEV')
dsrc = DataSourceAltCloud({}, None, self.paths)
dsrc.user_data_rhevm = lambda: False
- self.assertEquals(False, dsrc.get_data())
+ self.assertEqual(False, dsrc.get_data())
def test_fail_vsphere(self):
'''Failure Test module get_data() forcing VSPHERE.'''
@@ -211,14 +211,14 @@ class TestGetDataCloudInfoFile(TestCase):
_write_cloud_info_file('VSPHERE')
dsrc = DataSourceAltCloud({}, None, self.paths)
dsrc.user_data_vsphere = lambda: False
- self.assertEquals(False, dsrc.get_data())
+ self.assertEqual(False, dsrc.get_data())
def test_unrecognized(self):
'''Failure Test module get_data() forcing unrecognized.'''
_write_cloud_info_file('unrecognized')
dsrc = DataSourceAltCloud({}, None, self.paths)
- self.assertEquals(False, dsrc.get_data())
+ self.assertEqual(False, dsrc.get_data())
class TestGetDataNoCloudInfoFile(TestCase):
@@ -250,7 +250,7 @@ class TestGetDataNoCloudInfoFile(TestCase):
util.read_dmi_data = _dmi_data('RHEV Hypervisor')
dsrc = DataSourceAltCloud({}, None, self.paths)
dsrc.user_data_rhevm = lambda: True
- self.assertEquals(True, dsrc.get_data())
+ self.assertEqual(True, dsrc.get_data())
def test_vsphere_no_cloud_file(self):
'''Test No cloud info file module get_data() forcing VSPHERE.'''
@@ -258,14 +258,14 @@ class TestGetDataNoCloudInfoFile(TestCase):
util.read_dmi_data = _dmi_data('VMware Virtual Platform')
dsrc = DataSourceAltCloud({}, None, self.paths)
dsrc.user_data_vsphere = lambda: True
- self.assertEquals(True, dsrc.get_data())
+ self.assertEqual(True, dsrc.get_data())
def test_failure_no_cloud_file(self):
'''Test No cloud info file module get_data() forcing unrecognized.'''
util.read_dmi_data = _dmi_data('Unrecognized Platform')
dsrc = DataSourceAltCloud({}, None, self.paths)
- self.assertEquals(False, dsrc.get_data())
+ self.assertEqual(False, dsrc.get_data())
class TestUserDataRhevm(TestCase):
@@ -305,7 +305,7 @@ class TestUserDataRhevm(TestCase):
dsrc = DataSourceAltCloud({}, None, self.paths)
- self.assertEquals(False, dsrc.user_data_rhevm())
+ self.assertEqual(False, dsrc.user_data_rhevm())
def test_modprobe_fails(self):
'''Test user_data_rhevm() where modprobe fails.'''
@@ -315,7 +315,7 @@ class TestUserDataRhevm(TestCase):
dsrc = DataSourceAltCloud({}, None, self.paths)
- self.assertEquals(False, dsrc.user_data_rhevm())
+ self.assertEqual(False, dsrc.user_data_rhevm())
def test_no_modprobe_cmd(self):
'''Test user_data_rhevm() with no modprobe command.'''
@@ -325,7 +325,7 @@ class TestUserDataRhevm(TestCase):
dsrc = DataSourceAltCloud({}, None, self.paths)
- self.assertEquals(False, dsrc.user_data_rhevm())
+ self.assertEqual(False, dsrc.user_data_rhevm())
def test_udevadm_fails(self):
'''Test user_data_rhevm() where udevadm fails.'''
@@ -335,7 +335,7 @@ class TestUserDataRhevm(TestCase):
dsrc = DataSourceAltCloud({}, None, self.paths)
- self.assertEquals(False, dsrc.user_data_rhevm())
+ self.assertEqual(False, dsrc.user_data_rhevm())
def test_no_udevadm_cmd(self):
'''Test user_data_rhevm() with no udevadm command.'''
@@ -345,7 +345,7 @@ class TestUserDataRhevm(TestCase):
dsrc = DataSourceAltCloud({}, None, self.paths)
- self.assertEquals(False, dsrc.user_data_rhevm())
+ self.assertEqual(False, dsrc.user_data_rhevm())
class TestUserDataVsphere(TestCase):
@@ -380,7 +380,7 @@ class TestUserDataVsphere(TestCase):
dsrc = DataSourceAltCloud({}, None, self.paths)
- self.assertEquals(False, dsrc.user_data_vsphere())
+ self.assertEqual(False, dsrc.user_data_vsphere())
class TestReadUserDataCallback(TestCase):
@@ -408,8 +408,8 @@ class TestReadUserDataCallback(TestCase):
def test_callback_both(self):
'''Test read_user_data_callback() with both files.'''
- self.assertEquals('test user data',
- read_user_data_callback(self.mount_dir))
+ self.assertEqual('test user data',
+ read_user_data_callback(self.mount_dir))
def test_callback_dc(self):
'''Test read_user_data_callback() with only DC file.'''
@@ -418,8 +418,8 @@ class TestReadUserDataCallback(TestCase):
dc_file=False,
non_dc_file=True)
- self.assertEquals('test user data',
- read_user_data_callback(self.mount_dir))
+ self.assertEqual('test user data',
+ read_user_data_callback(self.mount_dir))
def test_callback_non_dc(self):
'''Test read_user_data_callback() with only non-DC file.'''
@@ -428,14 +428,14 @@ class TestReadUserDataCallback(TestCase):
dc_file=True,
non_dc_file=False)
- self.assertEquals('test user data',
- read_user_data_callback(self.mount_dir))
+ self.assertEqual('test user data',
+ read_user_data_callback(self.mount_dir))
def test_callback_none(self):
'''Test read_user_data_callback() no files are found.'''
_remove_user_data_files(self.mount_dir)
- self.assertEquals(None, read_user_data_callback(self.mount_dir))
+ self.assertEqual(None, read_user_data_callback(self.mount_dir))
def force_arch(arch=None):
diff --git a/tests/unittests/test_datasource/test_azure.py b/tests/unittests/test_datasource/test_azure.py
index 444e2799..5f3eb31f 100644
--- a/tests/unittests/test_datasource/test_azure.py
+++ b/tests/unittests/test_datasource/test_azure.py
@@ -14,11 +14,11 @@ except ImportError:
import crypt
import os
-import stat
-import yaml
import shutil
+import stat
import tempfile
import xml.etree.ElementTree as ET
+import yaml
def construct_valid_ovf_env(data=None, pubkeys=None, userdata=None):
@@ -165,7 +165,7 @@ class TestAzureDataSource(TestCase):
def tags_equal(x, y):
for x_tag, x_val in x.items():
y_val = y.get(x_val.tag)
- self.assertEquals(x_val.text, y_val.text)
+ self.assertEqual(x_val.text, y_val.text)
old_cnt = create_tag_index(oxml)
new_cnt = create_tag_index(nxml)
@@ -354,8 +354,8 @@ class TestAzureDataSource(TestCase):
self.assertTrue(ret)
cfg = dsrc.get_config_obj()
- self.assertEquals(dsrc.device_name_to_device("ephemeral0"),
- "/dev/sdb")
+ self.assertEqual(dsrc.device_name_to_device("ephemeral0"),
+ "/dev/sdb")
assert 'disk_setup' in cfg
assert 'fs_setup' in cfg
self.assertIsInstance(cfg['disk_setup'], dict)
@@ -404,15 +404,15 @@ class TestAzureDataSource(TestCase):
self.xml_notequals(data['ovfcontent'], on_disk_ovf)
# Make sure that the redacted password on disk is not used by CI
- self.assertNotEquals(dsrc.cfg.get('password'),
- DataSourceAzure.DEF_PASSWD_REDACTION)
+ self.assertNotEqual(dsrc.cfg.get('password'),
+ DataSourceAzure.DEF_PASSWD_REDACTION)
# Make sure that the password was really encrypted
et = ET.fromstring(on_disk_ovf)
for elem in et.iter():
if 'UserPassword' in elem.tag:
- self.assertEquals(DataSourceAzure.DEF_PASSWD_REDACTION,
- elem.text)
+ self.assertEqual(DataSourceAzure.DEF_PASSWD_REDACTION,
+ elem.text)
def test_ovf_env_arrives_in_waagent_dir(self):
xml = construct_valid_ovf_env(data={}, userdata="FOODATA")
diff --git a/tests/unittests/test_datasource/test_azure_helper.py b/tests/unittests/test_datasource/test_azure_helper.py
index 1134199b..d07a1f07 100644
--- a/tests/unittests/test_datasource/test_azure_helper.py
+++ b/tests/unittests/test_datasource/test_azure_helper.py
@@ -1,6 +1,7 @@
import os
from cloudinit.sources.helpers import azure as azure_helper
+
from ..helpers import TestCase
try:
@@ -70,7 +71,7 @@ class TestFindEndpoint(TestCase):
def test_missing_special_azure_line(self):
self.load_file.return_value = ''
- self.assertRaises(Exception,
+ self.assertRaises(ValueError,
azure_helper.WALinuxAgentShim.find_endpoint)
@staticmethod
diff --git a/tests/unittests/test_datasource/test_cloudstack.py b/tests/unittests/test_datasource/test_cloudstack.py
index 656d80d1..974b3704 100644
--- a/tests/unittests/test_datasource/test_cloudstack.py
+++ b/tests/unittests/test_datasource/test_cloudstack.py
@@ -1,5 +1,6 @@
from cloudinit import helpers
from cloudinit.sources.DataSourceCloudStack import DataSourceCloudStack
+
from ..helpers import TestCase
try:
diff --git a/tests/unittests/test_datasource/test_configdrive.py b/tests/unittests/test_datasource/test_configdrive.py
index 89b15f54..195b8207 100644
--- a/tests/unittests/test_datasource/test_configdrive.py
+++ b/tests/unittests/test_datasource/test_configdrive.py
@@ -151,7 +151,7 @@ class TestConfigDriveDataSource(TestCase):
mock.patch.object(os.path, 'exists',
side_effect=exists_side_effect()))
device = cfg_ds.device_name_to_device(name)
- self.assertEquals(dev_name, device)
+ self.assertEqual(dev_name, device)
find_mock.assert_called_once_with(mock.ANY)
self.assertEqual(exists_mock.call_count, 2)
@@ -179,7 +179,7 @@ class TestConfigDriveDataSource(TestCase):
mock.patch.object(os.path, 'exists',
return_value=True))
device = cfg_ds.device_name_to_device(name)
- self.assertEquals(dev_name, device)
+ self.assertEqual(dev_name, device)
find_mock.assert_called_once_with(mock.ANY)
exists_mock.assert_called_once_with(mock.ANY)
@@ -214,7 +214,7 @@ class TestConfigDriveDataSource(TestCase):
with mock.patch.object(os.path, 'exists',
side_effect=exists_side_effect()):
device = cfg_ds.device_name_to_device(name)
- self.assertEquals(dev_name, device)
+ self.assertEqual(dev_name, device)
# We don't assert the call count for os.path.exists() because
# not all of the entries in name_tests results in two calls to
# that function. Specifically, 'root2k' doesn't seem to call
@@ -242,7 +242,7 @@ class TestConfigDriveDataSource(TestCase):
for name, dev_name in name_tests.items():
with mock.patch.object(os.path, 'exists', return_value=True):
device = cfg_ds.device_name_to_device(name)
- self.assertEquals(dev_name, device)
+ self.assertEqual(dev_name, device)
def test_dir_valid(self):
"""Verify a dir is read as such."""
diff --git a/tests/unittests/test_datasource/test_digitalocean.py b/tests/unittests/test_datasource/test_digitalocean.py
index 679d1b82..8936a1e3 100644
--- a/tests/unittests/test_datasource/test_digitalocean.py
+++ b/tests/unittests/test_datasource/test_digitalocean.py
@@ -19,8 +19,8 @@ import re
from six.moves.urllib_parse import urlparse
-from cloudinit import settings
from cloudinit import helpers
+from cloudinit import settings
from cloudinit.sources import DataSourceDigitalOcean
from .. import helpers as test_helpers
diff --git a/tests/unittests/test_datasource/test_gce.py b/tests/unittests/test_datasource/test_gce.py
index fa714070..1f7eb99e 100644
--- a/tests/unittests/test_datasource/test_gce.py
+++ b/tests/unittests/test_datasource/test_gce.py
@@ -20,8 +20,8 @@ import re
from base64 import b64encode, b64decode
from six.moves.urllib_parse import urlparse
-from cloudinit import settings
from cloudinit import helpers
+from cloudinit import settings
from cloudinit.sources import DataSourceGCE
from .. import helpers as test_helpers
diff --git a/tests/unittests/test_datasource/test_maas.py b/tests/unittests/test_datasource/test_maas.py
index 77d15cac..f66f1c6d 100644
--- a/tests/unittests/test_datasource/test_maas.py
+++ b/tests/unittests/test_datasource/test_maas.py
@@ -104,13 +104,13 @@ class TestMAASDataSource(TestCase):
'meta-data/local-hostname': 'test-hostname',
'meta-data/public-keys': 'test-hostname',
'user-data': b'foodata',
- }
+ }
valid_order = [
'meta-data/local-hostname',
'meta-data/instance-id',
'meta-data/public-keys',
'user-data',
- ]
+ ]
my_seed = "http://example.com/xmeta"
my_ver = "1999-99-99"
my_headers = {'header1': 'value1', 'header2': 'value2'}
diff --git a/tests/unittests/test_datasource/test_nocloud.py b/tests/unittests/test_datasource/test_nocloud.py
index 2d5fc37c..3c528c23 100644
--- a/tests/unittests/test_datasource/test_nocloud.py
+++ b/tests/unittests/test_datasource/test_nocloud.py
@@ -4,10 +4,10 @@ from cloudinit import util
from ..helpers import TestCase, populate_dir
import os
-import yaml
import shutil
import tempfile
import unittest
+import yaml
try:
from unittest import mock
diff --git a/tests/unittests/test_datasource/test_openstack.py b/tests/unittests/test_datasource/test_openstack.py
index 0aa1ba84..4140d054 100644
--- a/tests/unittests/test_datasource/test_openstack.py
+++ b/tests/unittests/test_datasource/test_openstack.py
@@ -22,8 +22,8 @@ import re
from .. import helpers as test_helpers
-from six import StringIO
from six.moves.urllib.parse import urlparse
+from six import StringIO
from cloudinit import helpers
from cloudinit import settings
@@ -142,34 +142,34 @@ class TestOpenStackDataSource(test_helpers.HttprettyTestCase):
def test_successful(self):
_register_uris(self.VERSION, EC2_FILES, EC2_META, OS_FILES)
f = ds.read_metadata_service(BASE_URL)
- self.assertEquals(VENDOR_DATA, f.get('vendordata'))
- self.assertEquals(CONTENT_0, f['files']['/etc/foo.cfg'])
- self.assertEquals(CONTENT_1, f['files']['/etc/bar/bar.cfg'])
- self.assertEquals(2, len(f['files']))
- self.assertEquals(USER_DATA, f.get('userdata'))
- self.assertEquals(EC2_META, f.get('ec2-metadata'))
- self.assertEquals(2, f.get('version'))
+ self.assertEqual(VENDOR_DATA, f.get('vendordata'))
+ self.assertEqual(CONTENT_0, f['files']['/etc/foo.cfg'])
+ self.assertEqual(CONTENT_1, f['files']['/etc/bar/bar.cfg'])
+ self.assertEqual(2, len(f['files']))
+ self.assertEqual(USER_DATA, f.get('userdata'))
+ self.assertEqual(EC2_META, f.get('ec2-metadata'))
+ self.assertEqual(2, f.get('version'))
metadata = f['metadata']
- self.assertEquals('nova', metadata.get('availability_zone'))
- self.assertEquals('sm-foo-test.novalocal', metadata.get('hostname'))
- self.assertEquals('sm-foo-test.novalocal',
- metadata.get('local-hostname'))
- self.assertEquals('sm-foo-test', metadata.get('name'))
- self.assertEquals('b0fa911b-69d4-4476-bbe2-1c92bff6535c',
- metadata.get('uuid'))
- self.assertEquals('b0fa911b-69d4-4476-bbe2-1c92bff6535c',
- metadata.get('instance-id'))
+ self.assertEqual('nova', metadata.get('availability_zone'))
+ self.assertEqual('sm-foo-test.novalocal', metadata.get('hostname'))
+ self.assertEqual('sm-foo-test.novalocal',
+ metadata.get('local-hostname'))
+ self.assertEqual('sm-foo-test', metadata.get('name'))
+ self.assertEqual('b0fa911b-69d4-4476-bbe2-1c92bff6535c',
+ metadata.get('uuid'))
+ self.assertEqual('b0fa911b-69d4-4476-bbe2-1c92bff6535c',
+ metadata.get('instance-id'))
@hp.activate
def test_no_ec2(self):
_register_uris(self.VERSION, {}, {}, OS_FILES)
f = ds.read_metadata_service(BASE_URL)
- self.assertEquals(VENDOR_DATA, f.get('vendordata'))
- self.assertEquals(CONTENT_0, f['files']['/etc/foo.cfg'])
- self.assertEquals(CONTENT_1, f['files']['/etc/bar/bar.cfg'])
- self.assertEquals(USER_DATA, f.get('userdata'))
- self.assertEquals({}, f.get('ec2-metadata'))
- self.assertEquals(2, f.get('version'))
+ self.assertEqual(VENDOR_DATA, f.get('vendordata'))
+ self.assertEqual(CONTENT_0, f['files']['/etc/foo.cfg'])
+ self.assertEqual(CONTENT_1, f['files']['/etc/bar/bar.cfg'])
+ self.assertEqual(USER_DATA, f.get('userdata'))
+ self.assertEqual({}, f.get('ec2-metadata'))
+ self.assertEqual(2, f.get('version'))
@hp.activate
def test_bad_metadata(self):
@@ -201,9 +201,9 @@ class TestOpenStackDataSource(test_helpers.HttprettyTestCase):
os_files.pop(k, None)
_register_uris(self.VERSION, {}, {}, os_files)
f = ds.read_metadata_service(BASE_URL)
- self.assertEquals(VENDOR_DATA, f.get('vendordata'))
- self.assertEquals(CONTENT_0, f['files']['/etc/foo.cfg'])
- self.assertEquals(CONTENT_1, f['files']['/etc/bar/bar.cfg'])
+ self.assertEqual(VENDOR_DATA, f.get('vendordata'))
+ self.assertEqual(CONTENT_0, f['files']['/etc/foo.cfg'])
+ self.assertEqual(CONTENT_1, f['files']['/etc/bar/bar.cfg'])
self.assertFalse(f.get('userdata'))
@hp.activate
@@ -214,8 +214,8 @@ class TestOpenStackDataSource(test_helpers.HttprettyTestCase):
os_files.pop(k, None)
_register_uris(self.VERSION, {}, {}, os_files)
f = ds.read_metadata_service(BASE_URL)
- self.assertEquals(CONTENT_0, f['files']['/etc/foo.cfg'])
- self.assertEquals(CONTENT_1, f['files']['/etc/bar/bar.cfg'])
+ self.assertEqual(CONTENT_0, f['files']['/etc/foo.cfg'])
+ self.assertEqual(CONTENT_1, f['files']['/etc/bar/bar.cfg'])
self.assertFalse(f.get('vendordata'))
@hp.activate
@@ -247,16 +247,16 @@ class TestOpenStackDataSource(test_helpers.HttprettyTestCase):
self.assertIsNone(ds_os.version)
found = ds_os.get_data()
self.assertTrue(found)
- self.assertEquals(2, ds_os.version)
+ self.assertEqual(2, ds_os.version)
md = dict(ds_os.metadata)
md.pop('instance-id', None)
md.pop('local-hostname', None)
- self.assertEquals(OSTACK_META, md)
- self.assertEquals(EC2_META, ds_os.ec2_metadata)
- self.assertEquals(USER_DATA, ds_os.userdata_raw)
- self.assertEquals(2, len(ds_os.files))
- self.assertEquals(VENDOR_DATA, ds_os.vendordata_pure)
- self.assertEquals(ds_os.vendordata_raw, None)
+ self.assertEqual(OSTACK_META, md)
+ self.assertEqual(EC2_META, ds_os.ec2_metadata)
+ self.assertEqual(USER_DATA, ds_os.userdata_raw)
+ self.assertEqual(2, len(ds_os.files))
+ self.assertEqual(VENDOR_DATA, ds_os.vendordata_pure)
+ self.assertEqual(ds_os.vendordata_raw, None)
@hp.activate
def test_bad_datasource_meta(self):
diff --git a/tests/unittests/test_datasource/test_smartos.py b/tests/unittests/test_datasource/test_smartos.py
index 5c49966a..cdd04a72 100644
--- a/tests/unittests/test_datasource/test_smartos.py
+++ b/tests/unittests/test_datasource/test_smartos.py
@@ -24,6 +24,7 @@
from __future__ import print_function
+from binascii import crc32
import os
import os.path
import re
@@ -31,7 +32,6 @@ import shutil
import stat
import tempfile
import uuid
-from binascii import crc32
import serial
import six
@@ -157,16 +157,16 @@ class TestSmartOSDataSource(helpers.FilesystemMockingTestCase):
dsrc = self._get_ds()
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals('kvm', dsrc.smartos_type)
- self.assertEquals('/dev/ttyS1', dsrc.seed)
+ self.assertEqual('kvm', dsrc.smartos_type)
+ self.assertEqual('/dev/ttyS1', dsrc.seed)
def test_seed_lxbrand(self):
# default seed should be /dev/ttyS1
dsrc = self._get_ds(is_lxbrand=True)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals('lx-brand', dsrc.smartos_type)
- self.assertEquals('/native/.zonecontrol/metadata.sock', dsrc.seed)
+ self.assertEqual('lx-brand', dsrc.smartos_type)
+ self.assertEqual('/native/.zonecontrol/metadata.sock', dsrc.seed)
def test_issmartdc(self):
dsrc = self._get_ds()
@@ -190,29 +190,29 @@ class TestSmartOSDataSource(helpers.FilesystemMockingTestCase):
dsrc = self._get_ds(mockdata=MOCK_RETURNS)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['sdc:uuid'],
- dsrc.metadata['instance-id'])
+ self.assertEqual(MOCK_RETURNS['sdc:uuid'],
+ dsrc.metadata['instance-id'])
def test_root_keys(self):
dsrc = self._get_ds(mockdata=MOCK_RETURNS)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['root_authorized_keys'],
- dsrc.metadata['public-keys'])
+ self.assertEqual(MOCK_RETURNS['root_authorized_keys'],
+ dsrc.metadata['public-keys'])
def test_hostname_b64(self):
dsrc = self._get_ds(mockdata=MOCK_RETURNS)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['hostname'],
- dsrc.metadata['local-hostname'])
+ self.assertEqual(MOCK_RETURNS['hostname'],
+ dsrc.metadata['local-hostname'])
def test_hostname(self):
dsrc = self._get_ds(mockdata=MOCK_RETURNS)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['hostname'],
- dsrc.metadata['local-hostname'])
+ self.assertEqual(MOCK_RETURNS['hostname'],
+ dsrc.metadata['local-hostname'])
def test_base64_all(self):
# metadata provided base64_all of true
@@ -224,16 +224,16 @@ class TestSmartOSDataSource(helpers.FilesystemMockingTestCase):
dsrc = self._get_ds(mockdata=my_returns)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['hostname'],
- dsrc.metadata['local-hostname'])
- self.assertEquals(MOCK_RETURNS['cloud-init:user-data'],
- dsrc.userdata_raw)
- self.assertEquals(MOCK_RETURNS['root_authorized_keys'],
- dsrc.metadata['public-keys'])
- self.assertEquals(MOCK_RETURNS['disable_iptables_flag'],
- dsrc.metadata['iptables_disable'])
- self.assertEquals(MOCK_RETURNS['enable_motd_sys_info'],
- dsrc.metadata['motd_sys_info'])
+ self.assertEqual(MOCK_RETURNS['hostname'],
+ dsrc.metadata['local-hostname'])
+ self.assertEqual(MOCK_RETURNS['cloud-init:user-data'],
+ dsrc.userdata_raw)
+ self.assertEqual(MOCK_RETURNS['root_authorized_keys'],
+ dsrc.metadata['public-keys'])
+ self.assertEqual(MOCK_RETURNS['disable_iptables_flag'],
+ dsrc.metadata['iptables_disable'])
+ self.assertEqual(MOCK_RETURNS['enable_motd_sys_info'],
+ dsrc.metadata['motd_sys_info'])
def test_b64_userdata(self):
my_returns = MOCK_RETURNS.copy()
@@ -245,12 +245,12 @@ class TestSmartOSDataSource(helpers.FilesystemMockingTestCase):
dsrc = self._get_ds(mockdata=my_returns)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['hostname'],
- dsrc.metadata['local-hostname'])
- self.assertEquals(MOCK_RETURNS['cloud-init:user-data'],
- dsrc.userdata_raw)
- self.assertEquals(MOCK_RETURNS['root_authorized_keys'],
- dsrc.metadata['public-keys'])
+ self.assertEqual(MOCK_RETURNS['hostname'],
+ dsrc.metadata['local-hostname'])
+ self.assertEqual(MOCK_RETURNS['cloud-init:user-data'],
+ dsrc.userdata_raw)
+ self.assertEqual(MOCK_RETURNS['root_authorized_keys'],
+ dsrc.metadata['public-keys'])
def test_b64_keys(self):
my_returns = MOCK_RETURNS.copy()
@@ -261,39 +261,39 @@ class TestSmartOSDataSource(helpers.FilesystemMockingTestCase):
dsrc = self._get_ds(mockdata=my_returns)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['hostname'],
- dsrc.metadata['local-hostname'])
- self.assertEquals(MOCK_RETURNS['cloud-init:user-data'],
- dsrc.userdata_raw)
+ self.assertEqual(MOCK_RETURNS['hostname'],
+ dsrc.metadata['local-hostname'])
+ self.assertEqual(MOCK_RETURNS['cloud-init:user-data'],
+ dsrc.userdata_raw)
def test_userdata(self):
dsrc = self._get_ds(mockdata=MOCK_RETURNS)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['user-data'],
- dsrc.metadata['legacy-user-data'])
- self.assertEquals(MOCK_RETURNS['cloud-init:user-data'],
- dsrc.userdata_raw)
+ self.assertEqual(MOCK_RETURNS['user-data'],
+ dsrc.metadata['legacy-user-data'])
+ self.assertEqual(MOCK_RETURNS['cloud-init:user-data'],
+ dsrc.userdata_raw)
def test_sdc_scripts(self):
dsrc = self._get_ds(mockdata=MOCK_RETURNS)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['user-script'],
- dsrc.metadata['user-script'])
+ self.assertEqual(MOCK_RETURNS['user-script'],
+ dsrc.metadata['user-script'])
legacy_script_f = "%s/user-script" % self.legacy_user_d
self.assertTrue(os.path.exists(legacy_script_f))
self.assertTrue(os.path.islink(legacy_script_f))
user_script_perm = oct(os.stat(legacy_script_f)[stat.ST_MODE])[-3:]
- self.assertEquals(user_script_perm, '700')
+ self.assertEqual(user_script_perm, '700')
def test_scripts_shebanged(self):
dsrc = self._get_ds(mockdata=MOCK_RETURNS)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['user-script'],
- dsrc.metadata['user-script'])
+ self.assertEqual(MOCK_RETURNS['user-script'],
+ dsrc.metadata['user-script'])
legacy_script_f = "%s/user-script" % self.legacy_user_d
self.assertTrue(os.path.exists(legacy_script_f))
@@ -301,9 +301,9 @@ class TestSmartOSDataSource(helpers.FilesystemMockingTestCase):
shebang = None
with open(legacy_script_f, 'r') as f:
shebang = f.readlines()[0].strip()
- self.assertEquals(shebang, "#!/bin/bash")
+ self.assertEqual(shebang, "#!/bin/bash")
user_script_perm = oct(os.stat(legacy_script_f)[stat.ST_MODE])[-3:]
- self.assertEquals(user_script_perm, '700')
+ self.assertEqual(user_script_perm, '700')
def test_scripts_shebang_not_added(self):
"""
@@ -319,8 +319,8 @@ class TestSmartOSDataSource(helpers.FilesystemMockingTestCase):
dsrc = self._get_ds(mockdata=my_returns)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(my_returns['user-script'],
- dsrc.metadata['user-script'])
+ self.assertEqual(my_returns['user-script'],
+ dsrc.metadata['user-script'])
legacy_script_f = "%s/user-script" % self.legacy_user_d
self.assertTrue(os.path.exists(legacy_script_f))
@@ -328,7 +328,7 @@ class TestSmartOSDataSource(helpers.FilesystemMockingTestCase):
shebang = None
with open(legacy_script_f, 'r') as f:
shebang = f.readlines()[0].strip()
- self.assertEquals(shebang, "#!/usr/bin/perl")
+ self.assertEqual(shebang, "#!/usr/bin/perl")
def test_userdata_removed(self):
"""
@@ -358,7 +358,7 @@ class TestSmartOSDataSource(helpers.FilesystemMockingTestCase):
if re.match(r'.*\/mdata-user-data$', name_f):
found_new = True
print(name_f)
- self.assertEquals(permissions, '400')
+ self.assertEqual(permissions, '400')
self.assertFalse(found_new)
@@ -366,8 +366,8 @@ class TestSmartOSDataSource(helpers.FilesystemMockingTestCase):
dsrc = self._get_ds(mockdata=MOCK_RETURNS)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['sdc:vendor-data'],
- dsrc.metadata['vendor-data'])
+ self.assertEqual(MOCK_RETURNS['sdc:vendor-data'],
+ dsrc.metadata['vendor-data'])
def test_default_vendor_data(self):
my_returns = MOCK_RETURNS.copy()
@@ -376,7 +376,7 @@ class TestSmartOSDataSource(helpers.FilesystemMockingTestCase):
dsrc = self._get_ds(mockdata=my_returns)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertNotEquals(def_op_script, dsrc.metadata['vendor-data'])
+ self.assertNotEqual(def_op_script, dsrc.metadata['vendor-data'])
# we expect default vendor-data is a boothook
self.assertTrue(dsrc.vendordata_raw.startswith("#cloud-boothook"))
@@ -385,15 +385,15 @@ class TestSmartOSDataSource(helpers.FilesystemMockingTestCase):
dsrc = self._get_ds(mockdata=MOCK_RETURNS)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['disable_iptables_flag'],
- dsrc.metadata['iptables_disable'])
+ self.assertEqual(MOCK_RETURNS['disable_iptables_flag'],
+ dsrc.metadata['iptables_disable'])
def test_motd_sys_info(self):
dsrc = self._get_ds(mockdata=MOCK_RETURNS)
ret = dsrc.get_data()
self.assertTrue(ret)
- self.assertEquals(MOCK_RETURNS['enable_motd_sys_info'],
- dsrc.metadata['motd_sys_info'])
+ self.assertEqual(MOCK_RETURNS['enable_motd_sys_info'],
+ dsrc.metadata['motd_sys_info'])
def test_default_ephemeral(self):
# Test to make sure that the builtin config has the ephemeral
diff --git a/tests/unittests/test_distros/test_generic.py b/tests/unittests/test_distros/test_generic.py
index 6ed1704c..96fa0811 100644
--- a/tests/unittests/test_distros/test_generic.py
+++ b/tests/unittests/test_distros/test_generic.py
@@ -87,13 +87,13 @@ class TestGenericDistro(helpers.FilesystemMockingTestCase):
rules = 'ALL=(ALL:ALL) ALL'
contents = self._write_load_sudoers('harlowja', rules)
expected = ['harlowja ALL=(ALL:ALL) ALL']
- self.assertEquals(len(expected), self._count_in(expected, contents))
+ self.assertEqual(len(expected), self._count_in(expected, contents))
not_expected = [
'harlowja A',
'harlowja L',
'harlowja L',
]
- self.assertEquals(0, self._count_in(not_expected, contents))
+ self.assertEqual(0, self._count_in(not_expected, contents))
def test_sudoers_ensure_rules_list(self):
rules = [
@@ -107,13 +107,13 @@ class TestGenericDistro(helpers.FilesystemMockingTestCase):
'harlowja B-ALL=(ALL:ALL) ALL',
'harlowja C-ALL=(ALL:ALL) ALL',
]
- self.assertEquals(len(expected), self._count_in(expected, contents))
+ self.assertEqual(len(expected), self._count_in(expected, contents))
not_expected = [
'harlowja A',
'harlowja L',
'harlowja L',
]
- self.assertEquals(0, self._count_in(not_expected, contents))
+ self.assertEqual(0, self._count_in(not_expected, contents))
def test_sudoers_ensure_new(self):
cls = distros.fetch("ubuntu")
@@ -136,7 +136,7 @@ class TestGenericDistro(helpers.FilesystemMockingTestCase):
self.assertIn("includedir /b", contents)
self.assertTrue(os.path.isdir("/b"))
self.assertIn("josh", contents)
- self.assertEquals(2, contents.count("josh"))
+ self.assertEqual(2, contents.count("josh"))
def test_arch_package_mirror_info_unknown(self):
"""for an unknown arch, we should get back that with arch 'default'."""
diff --git a/tests/unittests/test_distros/test_hostname.py b/tests/unittests/test_distros/test_hostname.py
index 143e29a9..5f28a868 100644
--- a/tests/unittests/test_distros/test_hostname.py
+++ b/tests/unittests/test_distros/test_hostname.py
@@ -15,24 +15,24 @@ BASE_HOSTNAME = BASE_HOSTNAME.strip()
class TestHostnameHelper(unittest.TestCase):
def test_parse_same(self):
hn = hostname.HostnameConf(BASE_HOSTNAME)
- self.assertEquals(str(hn).strip(), BASE_HOSTNAME)
- self.assertEquals(hn.hostname, 'blahblah')
+ self.assertEqual(str(hn).strip(), BASE_HOSTNAME)
+ self.assertEqual(hn.hostname, 'blahblah')
def test_no_adjust_hostname(self):
hn = hostname.HostnameConf(BASE_HOSTNAME)
prev_name = hn.hostname
hn.set_hostname("")
- self.assertEquals(hn.hostname, prev_name)
+ self.assertEqual(hn.hostname, prev_name)
def test_adjust_hostname(self):
hn = hostname.HostnameConf(BASE_HOSTNAME)
prev_name = hn.hostname
- self.assertEquals(prev_name, 'blahblah')
+ self.assertEqual(prev_name, 'blahblah')
hn.set_hostname("bbbbd")
- self.assertEquals(hn.hostname, 'bbbbd')
+ self.assertEqual(hn.hostname, 'bbbbd')
expected_out = '''
# My super-duper-hostname
bbbbd
'''
- self.assertEquals(str(hn).strip(), expected_out.strip())
+ self.assertEqual(str(hn).strip(), expected_out.strip())
diff --git a/tests/unittests/test_distros/test_hosts.py b/tests/unittests/test_distros/test_hosts.py
index fc701eaa..ab867c6f 100644
--- a/tests/unittests/test_distros/test_hosts.py
+++ b/tests/unittests/test_distros/test_hosts.py
@@ -17,25 +17,25 @@ BASE_ETC = BASE_ETC.strip()
class TestHostsHelper(unittest.TestCase):
def test_parse(self):
eh = hosts.HostsConf(BASE_ETC)
- self.assertEquals(eh.get_entry('127.0.0.1'), [['localhost']])
- self.assertEquals(eh.get_entry('192.168.1.10'),
- [['foo.mydomain.org', 'foo'],
- ['bar.mydomain.org', 'bar']])
+ self.assertEqual(eh.get_entry('127.0.0.1'), [['localhost']])
+ self.assertEqual(eh.get_entry('192.168.1.10'),
+ [['foo.mydomain.org', 'foo'],
+ ['bar.mydomain.org', 'bar']])
eh = str(eh)
self.assertTrue(eh.startswith('# Example'))
def test_add(self):
eh = hosts.HostsConf(BASE_ETC)
eh.add_entry('127.0.0.0', 'blah')
- self.assertEquals(eh.get_entry('127.0.0.0'), [['blah']])
+ self.assertEqual(eh.get_entry('127.0.0.0'), [['blah']])
eh.add_entry('127.0.0.3', 'blah', 'blah2', 'blah3')
- self.assertEquals(eh.get_entry('127.0.0.3'),
- [['blah', 'blah2', 'blah3']])
+ self.assertEqual(eh.get_entry('127.0.0.3'),
+ [['blah', 'blah2', 'blah3']])
def test_del(self):
eh = hosts.HostsConf(BASE_ETC)
eh.add_entry('127.0.0.0', 'blah')
- self.assertEquals(eh.get_entry('127.0.0.0'), [['blah']])
+ self.assertEqual(eh.get_entry('127.0.0.0'), [['blah']])
eh.del_entries('127.0.0.0')
- self.assertEquals(eh.get_entry('127.0.0.0'), [])
+ self.assertEqual(eh.get_entry('127.0.0.0'), [])
diff --git a/tests/unittests/test_distros/test_netconfig.py b/tests/unittests/test_distros/test_netconfig.py
index 2c2a424d..9172e3aa 100644
--- a/tests/unittests/test_distros/test_netconfig.py
+++ b/tests/unittests/test_distros/test_netconfig.py
@@ -1,4 +1,5 @@
import os
+from six import StringIO
try:
from unittest import mock
@@ -9,16 +10,14 @@ try:
except ImportError:
from contextlib2 import ExitStack
-from six import StringIO
from ..helpers import TestCase
from cloudinit import distros
+from cloudinit.distros.parsers.sys_conf import SysConf
from cloudinit import helpers
from cloudinit import settings
from cloudinit import util
-from cloudinit.distros.parsers.sys_conf import SysConf
-
BASE_NET_CFG = '''
auto lo
@@ -108,23 +107,23 @@ class TestNetCfgDistro(TestCase):
ub_distro.apply_network(BASE_NET_CFG, False)
- self.assertEquals(len(write_bufs), 1)
+ self.assertEqual(len(write_bufs), 1)
eni_name = '/etc/network/interfaces.d/50-cloud-init.cfg'
self.assertIn(eni_name, write_bufs)
write_buf = write_bufs[eni_name]
- self.assertEquals(str(write_buf).strip(), BASE_NET_CFG.strip())
- self.assertEquals(write_buf.mode, 0o644)
+ self.assertEqual(str(write_buf).strip(), BASE_NET_CFG.strip())
+ self.assertEqual(write_buf.mode, 0o644)
def assertCfgEquals(self, blob1, blob2):
b1 = dict(SysConf(blob1.strip().splitlines()))
b2 = dict(SysConf(blob2.strip().splitlines()))
- self.assertEquals(b1, b2)
+ self.assertEqual(b1, b2)
for (k, v) in b1.items():
self.assertIn(k, b2)
for (k, v) in b2.items():
self.assertIn(k, b1)
for (k, v) in b1.items():
- self.assertEquals(v, b2[k])
+ self.assertEqual(v, b2[k])
def test_simple_write_rh(self):
rh_distro = self._get_distro('rhel')
@@ -148,7 +147,7 @@ class TestNetCfgDistro(TestCase):
rh_distro.apply_network(BASE_NET_CFG, False)
- self.assertEquals(len(write_bufs), 4)
+ self.assertEqual(len(write_bufs), 4)
self.assertIn('/etc/sysconfig/network-scripts/ifcfg-lo',
write_bufs)
write_buf = write_bufs['/etc/sysconfig/network-scripts/ifcfg-lo']
@@ -157,7 +156,7 @@ DEVICE="lo"
ONBOOT=yes
'''
self.assertCfgEquals(expected_buf, str(write_buf))
- self.assertEquals(write_buf.mode, 0o644)
+ self.assertEqual(write_buf.mode, 0o644)
self.assertIn('/etc/sysconfig/network-scripts/ifcfg-eth0',
write_bufs)
@@ -172,7 +171,7 @@ GATEWAY="192.168.1.254"
BROADCAST="192.168.1.0"
'''
self.assertCfgEquals(expected_buf, str(write_buf))
- self.assertEquals(write_buf.mode, 0o644)
+ self.assertEqual(write_buf.mode, 0o644)
self.assertIn('/etc/sysconfig/network-scripts/ifcfg-eth1',
write_bufs)
@@ -183,7 +182,7 @@ BOOTPROTO="dhcp"
ONBOOT=yes
'''
self.assertCfgEquals(expected_buf, str(write_buf))
- self.assertEquals(write_buf.mode, 0o644)
+ self.assertEqual(write_buf.mode, 0o644)
self.assertIn('/etc/sysconfig/network', write_bufs)
write_buf = write_bufs['/etc/sysconfig/network']
@@ -192,7 +191,7 @@ ONBOOT=yes
NETWORKING=yes
'''
self.assertCfgEquals(expected_buf, str(write_buf))
- self.assertEquals(write_buf.mode, 0o644)
+ self.assertEqual(write_buf.mode, 0o644)
def test_write_ipv6_rhel(self):
rh_distro = self._get_distro('rhel')
@@ -216,7 +215,7 @@ NETWORKING=yes
rh_distro.apply_network(BASE_NET_CFG_IPV6, False)
- self.assertEquals(len(write_bufs), 4)
+ self.assertEqual(len(write_bufs), 4)
self.assertIn('/etc/sysconfig/network-scripts/ifcfg-lo',
write_bufs)
write_buf = write_bufs['/etc/sysconfig/network-scripts/ifcfg-lo']
@@ -225,7 +224,7 @@ DEVICE="lo"
ONBOOT=yes
'''
self.assertCfgEquals(expected_buf, str(write_buf))
- self.assertEquals(write_buf.mode, 0o644)
+ self.assertEqual(write_buf.mode, 0o644)
self.assertIn('/etc/sysconfig/network-scripts/ifcfg-eth0',
write_bufs)
@@ -243,7 +242,7 @@ IPV6ADDR="2607:f0d0:1002:0011::2"
IPV6_DEFAULTGW="2607:f0d0:1002:0011::1"
'''
self.assertCfgEquals(expected_buf, str(write_buf))
- self.assertEquals(write_buf.mode, 0o644)
+ self.assertEqual(write_buf.mode, 0o644)
self.assertIn('/etc/sysconfig/network-scripts/ifcfg-eth1',
write_bufs)
write_buf = write_bufs['/etc/sysconfig/network-scripts/ifcfg-eth1']
@@ -260,7 +259,7 @@ IPV6ADDR="2607:f0d0:1002:0011::3"
IPV6_DEFAULTGW="2607:f0d0:1002:0011::1"
'''
self.assertCfgEquals(expected_buf, str(write_buf))
- self.assertEquals(write_buf.mode, 0o644)
+ self.assertEqual(write_buf.mode, 0o644)
self.assertIn('/etc/sysconfig/network', write_bufs)
write_buf = write_bufs['/etc/sysconfig/network']
@@ -271,7 +270,7 @@ NETWORKING_IPV6=yes
IPV6_AUTOCONF=no
'''
self.assertCfgEquals(expected_buf, str(write_buf))
- self.assertEquals(write_buf.mode, 0o644)
+ self.assertEqual(write_buf.mode, 0o644)
def test_simple_write_freebsd(self):
fbsd_distro = self._get_distro('freebsd')
@@ -319,4 +318,4 @@ ifconfig_vtnet1="DHCP"
defaultrouter="192.168.1.254"
'''
self.assertCfgEquals(expected_buf, str(write_buf))
- self.assertEquals(write_buf.mode, 0o644)
+ self.assertEqual(write_buf.mode, 0o644)
diff --git a/tests/unittests/test_distros/test_resolv.py b/tests/unittests/test_distros/test_resolv.py
index 9edeb6e7..9402b5ea 100644
--- a/tests/unittests/test_distros/test_resolv.py
+++ b/tests/unittests/test_distros/test_resolv.py
@@ -1,9 +1,10 @@
from cloudinit.distros.parsers import resolv_conf
from cloudinit.distros import rhel_util
+from ..helpers import TestCase
+
import re
import tempfile
-from ..helpers import TestCase
BASE_RESOLVE = '''
@@ -19,7 +20,7 @@ class TestResolvHelper(TestCase):
def test_parse_same(self):
rp = resolv_conf.ResolvConf(BASE_RESOLVE)
rp_r = str(rp).strip()
- self.assertEquals(BASE_RESOLVE, rp_r)
+ self.assertEqual(BASE_RESOLVE, rp_r)
def test_write_works(self):
with tempfile.NamedTemporaryFile() as fh:
@@ -27,10 +28,10 @@ class TestResolvHelper(TestCase):
def test_local_domain(self):
rp = resolv_conf.ResolvConf(BASE_RESOLVE)
- self.assertEquals(None, rp.local_domain)
+ self.assertEqual(None, rp.local_domain)
rp.local_domain = "bob"
- self.assertEquals('bob', rp.local_domain)
+ self.assertEqual('bob', rp.local_domain)
self.assertIn('domain bob', str(rp))
def test_nameservers(self):
@@ -41,7 +42,7 @@ class TestResolvHelper(TestCase):
self.assertIn('10.2', rp.nameservers)
self.assertIn('nameserver 10.2', str(rp))
self.assertNotIn('10.3', rp.nameservers)
- self.assertEquals(len(rp.nameservers), 3)
+ self.assertEqual(len(rp.nameservers), 3)
rp.add_nameserver('10.2')
self.assertRaises(ValueError, rp.add_nameserver, '10.3')
self.assertNotIn('10.3', rp.nameservers)
@@ -55,12 +56,12 @@ class TestResolvHelper(TestCase):
self.assertTrue(re.search(r'search(.*)bbb.y.com(.*)', str(rp)))
self.assertIn('bbb.y.com', rp.search_domains)
rp.add_search_domain('bbb.y.com')
- self.assertEquals(len(rp.search_domains), 3)
+ self.assertEqual(len(rp.search_domains), 3)
rp.add_search_domain('bbb2.y.com')
- self.assertEquals(len(rp.search_domains), 4)
+ self.assertEqual(len(rp.search_domains), 4)
rp.add_search_domain('bbb3.y.com')
- self.assertEquals(len(rp.search_domains), 5)
+ self.assertEqual(len(rp.search_domains), 5)
rp.add_search_domain('bbb4.y.com')
- self.assertEquals(len(rp.search_domains), 6)
+ self.assertEqual(len(rp.search_domains), 6)
self.assertRaises(ValueError, rp.add_search_domain, 'bbb5.y.com')
- self.assertEquals(len(rp.search_domains), 6)
+ self.assertEqual(len(rp.search_domains), 6)
diff --git a/tests/unittests/test_distros/test_sysconfig.py b/tests/unittests/test_distros/test_sysconfig.py
index 03d89a10..8cb55522 100644
--- a/tests/unittests/test_distros/test_sysconfig.py
+++ b/tests/unittests/test_distros/test_sysconfig.py
@@ -1,6 +1,7 @@
import re
from cloudinit.distros.parsers.sys_conf import SysConf
+
from ..helpers import TestCase
@@ -27,34 +28,34 @@ IPV6TO4_ROUTING='eth0-:0004::1/64 eth1-:0005::1/64'
ETHTOOL_OPTS="-K ${DEVICE} tso on; -G ${DEVICE} rx 256 tx 256"
USEMD5=no'''
conf = SysConf(contents.splitlines())
- self.assertEquals(conf['HOSTNAME'], 'blahblah')
- self.assertEquals(conf['SHORTDATE'], '$(date +%y:%m:%d:%H:%M)')
+ self.assertEqual(conf['HOSTNAME'], 'blahblah')
+ self.assertEqual(conf['SHORTDATE'], '$(date +%y:%m:%d:%H:%M)')
# Should be unquoted
- self.assertEquals(conf['ETHTOOL_OPTS'], ('-K ${DEVICE} tso on; '
- '-G ${DEVICE} rx 256 tx 256'))
- self.assertEquals(contents, str(conf))
+ self.assertEqual(conf['ETHTOOL_OPTS'], ('-K ${DEVICE} tso on; '
+ '-G ${DEVICE} rx 256 tx 256'))
+ self.assertEqual(contents, str(conf))
def test_parse_shell_vars(self):
contents = 'USESMBAUTH=$XYZ'
conf = SysConf(contents.splitlines())
- self.assertEquals(contents, str(conf))
+ self.assertEqual(contents, str(conf))
conf = SysConf('')
conf['B'] = '${ZZ}d apples'
# Should be quoted
- self.assertEquals('B="${ZZ}d apples"', str(conf))
+ self.assertEqual('B="${ZZ}d apples"', str(conf))
conf = SysConf('')
conf['B'] = '$? d apples'
- self.assertEquals('B="$? d apples"', str(conf))
+ self.assertEqual('B="$? d apples"', str(conf))
contents = 'IPMI_WATCHDOG_OPTIONS="timeout=60"'
conf = SysConf(contents.splitlines())
- self.assertEquals('IPMI_WATCHDOG_OPTIONS=timeout=60', str(conf))
+ self.assertEqual('IPMI_WATCHDOG_OPTIONS=timeout=60', str(conf))
def test_parse_adjust(self):
contents = 'IPV6TO4_ROUTING="eth0-:0004::1/64 eth1-:0005::1/64"'
conf = SysConf(contents.splitlines())
# Should be unquoted
- self.assertEquals('eth0-:0004::1/64 eth1-:0005::1/64',
- conf['IPV6TO4_ROUTING'])
+ self.assertEqual('eth0-:0004::1/64 eth1-:0005::1/64',
+ conf['IPV6TO4_ROUTING'])
conf['IPV6TO4_ROUTING'] = "blah \tblah"
contents2 = str(conf).strip()
# Should be requoted due to whitespace
@@ -65,12 +66,12 @@ USEMD5=no'''
conf = SysConf(''.splitlines())
conf['B'] = ' $(time)'
contents = str(conf)
- self.assertEquals('B= $(time)', contents)
+ self.assertEqual('B= $(time)', contents)
def test_parse_empty(self):
contents = ''
conf = SysConf(contents.splitlines())
- self.assertEquals('', str(conf).strip())
+ self.assertEqual('', str(conf).strip())
def test_parse_add_new(self):
contents = 'BLAH=b'
diff --git a/tests/unittests/test_distros/test_user_data_normalize.py b/tests/unittests/test_distros/test_user_data_normalize.py
index 4525f487..a887a930 100644
--- a/tests/unittests/test_distros/test_user_data_normalize.py
+++ b/tests/unittests/test_distros/test_user_data_normalize.py
@@ -33,20 +33,19 @@ class TestUGNormalize(TestCase):
def test_group_dict(self):
distro = self._make_distro('ubuntu')
- g = {'groups': [
- {'ubuntu': ['foo', 'bar'],
- 'bob': 'users'},
- 'cloud-users',
- {'bob': 'users2'}
- ]}
+ g = {'groups':
+ [{'ubuntu': ['foo', 'bar'],
+ 'bob': 'users'},
+ 'cloud-users',
+ {'bob': 'users2'}]}
(_users, groups) = self._norm(g, distro)
self.assertIn('ubuntu', groups)
ub_members = groups['ubuntu']
- self.assertEquals(sorted(['foo', 'bar']), sorted(ub_members))
+ self.assertEqual(sorted(['foo', 'bar']), sorted(ub_members))
self.assertIn('bob', groups)
b_members = groups['bob']
- self.assertEquals(sorted(['users', 'users2']),
- sorted(b_members))
+ self.assertEqual(sorted(['users', 'users2']),
+ sorted(b_members))
def test_basic_groups(self):
distro = self._make_distro('ubuntu')
@@ -55,7 +54,7 @@ class TestUGNormalize(TestCase):
}
(users, groups) = self._norm(ug_cfg, distro)
self.assertIn('bob', groups)
- self.assertEquals({}, users)
+ self.assertEqual({}, users)
def test_csv_groups(self):
distro = self._make_distro('ubuntu')
@@ -66,7 +65,7 @@ class TestUGNormalize(TestCase):
self.assertIn('bob', groups)
self.assertIn('joe', groups)
self.assertIn('steve', groups)
- self.assertEquals({}, users)
+ self.assertEqual({}, users)
def test_more_groups(self):
distro = self._make_distro('ubuntu')
@@ -77,7 +76,7 @@ class TestUGNormalize(TestCase):
self.assertIn('bob', groups)
self.assertIn('joe', groups)
self.assertIn('steve', groups)
- self.assertEquals({}, users)
+ self.assertEqual({}, users)
def test_member_groups(self):
distro = self._make_distro('ubuntu')
@@ -90,11 +89,11 @@ class TestUGNormalize(TestCase):
}
(users, groups) = self._norm(ug_cfg, distro)
self.assertIn('bob', groups)
- self.assertEquals(['s'], groups['bob'])
- self.assertEquals([], groups['joe'])
+ self.assertEqual(['s'], groups['bob'])
+ self.assertEqual([], groups['joe'])
self.assertIn('joe', groups)
self.assertIn('steve', groups)
- self.assertEquals({}, users)
+ self.assertEqual({}, users)
def test_users_simple_dict(self):
distro = self._make_distro('ubuntu', bcfg)
@@ -128,14 +127,14 @@ class TestUGNormalize(TestCase):
}
}
(users, _groups) = self._norm(ug_cfg, distro)
- self.assertEquals({}, users)
+ self.assertEqual({}, users)
ug_cfg = {
'users': {
'default': 'no',
}
}
(users, _groups) = self._norm(ug_cfg, distro)
- self.assertEquals({}, users)
+ self.assertEqual({}, users)
def test_users_simple_csv(self):
distro = self._make_distro('ubuntu')
@@ -145,8 +144,8 @@ class TestUGNormalize(TestCase):
(users, _groups) = self._norm(ug_cfg, distro)
self.assertIn('joe', users)
self.assertIn('bob', users)
- self.assertEquals({'default': False}, users['joe'])
- self.assertEquals({'default': False}, users['bob'])
+ self.assertEqual({'default': False}, users['joe'])
+ self.assertEqual({'default': False}, users['bob'])
def test_users_simple(self):
distro = self._make_distro('ubuntu')
@@ -159,8 +158,8 @@ class TestUGNormalize(TestCase):
(users, _groups) = self._norm(ug_cfg, distro)
self.assertIn('joe', users)
self.assertIn('bob', users)
- self.assertEquals({'default': False}, users['joe'])
- self.assertEquals({'default': False}, users['bob'])
+ self.assertEqual({'default': False}, users['joe'])
+ self.assertEqual({'default': False}, users['bob'])
def test_users_old_user(self):
distro = self._make_distro('ubuntu', bcfg)
@@ -211,8 +210,8 @@ class TestUGNormalize(TestCase):
self.assertIn('zetta', users)
ug_cfg = {}
(users, groups) = self._norm(ug_cfg, distro)
- self.assertEquals({}, users)
- self.assertEquals({}, groups)
+ self.assertEqual({}, users)
+ self.assertEqual({}, groups)
def test_users_dict_default_additional(self):
distro = self._make_distro('ubuntu', bcfg)
@@ -223,12 +222,10 @@ class TestUGNormalize(TestCase):
}
(users, _groups) = self._norm(ug_cfg, distro)
self.assertIn('bob', users)
- self.assertEquals(",".join(distro.get_default_user()['groups']),
- users['bob']['groups'])
- self.assertEquals(True,
- users['bob']['blah'])
- self.assertEquals(True,
- users['bob']['default'])
+ self.assertEqual(",".join(distro.get_default_user()['groups']),
+ users['bob']['groups'])
+ self.assertEqual(True, users['bob']['blah'])
+ self.assertEqual(True, users['bob']['default'])
def test_users_dict_extract(self):
distro = self._make_distro('ubuntu', bcfg)
@@ -240,7 +237,7 @@ class TestUGNormalize(TestCase):
(users, _groups) = self._norm(ug_cfg, distro)
self.assertIn('bob', users)
(name, config) = distros.extract_default(users)
- self.assertEquals(name, 'bob')
+ self.assertEqual(name, 'bob')
expected_config = {}
def_config = None
try:
@@ -255,7 +252,7 @@ class TestUGNormalize(TestCase):
expected_config.pop('name', None)
expected_config.pop('groups', None)
config.pop('groups', None)
- self.assertEquals(config, expected_config)
+ self.assertEqual(config, expected_config)
def test_users_dict_default(self):
distro = self._make_distro('ubuntu', bcfg)
@@ -266,10 +263,9 @@ class TestUGNormalize(TestCase):
}
(users, _groups) = self._norm(ug_cfg, distro)
self.assertIn('bob', users)
- self.assertEquals(",".join(distro.get_default_user()['groups']),
- users['bob']['groups'])
- self.assertEquals(True,
- users['bob']['default'])
+ self.assertEqual(",".join(distro.get_default_user()['groups']),
+ users['bob']['groups'])
+ self.assertEqual(True, users['bob']['default'])
def test_users_dict_trans(self):
distro = self._make_distro('ubuntu')
@@ -283,8 +279,8 @@ class TestUGNormalize(TestCase):
(users, _groups) = self._norm(ug_cfg, distro)
self.assertIn('joe', users)
self.assertIn('bob', users)
- self.assertEquals({'tr_me': True, 'default': False}, users['joe'])
- self.assertEquals({'default': False}, users['bob'])
+ self.assertEqual({'tr_me': True, 'default': False}, users['joe'])
+ self.assertEqual({'default': False}, users['bob'])
def test_users_dict(self):
distro = self._make_distro('ubuntu')
@@ -297,5 +293,5 @@ class TestUGNormalize(TestCase):
(users, _groups) = self._norm(ug_cfg, distro)
self.assertIn('joe', users)
self.assertIn('bob', users)
- self.assertEquals({'default': False}, users['joe'])
- self.assertEquals({'default': False}, users['bob'])
+ self.assertEqual({'default': False}, users['joe'])
+ self.assertEqual({'default': False}, users['bob'])
diff --git a/tests/unittests/test_ec2_util.py b/tests/unittests/test_ec2_util.py
index 99fc54be..d6cf17fa 100644
--- a/tests/unittests/test_ec2_util.py
+++ b/tests/unittests/test_ec2_util.py
@@ -16,7 +16,7 @@ class TestEc2Util(helpers.HttprettyTestCase):
body='stuff',
status=200)
userdata = eu.get_instance_userdata(self.VERSION)
- self.assertEquals('stuff', userdata.decode('utf-8'))
+ self.assertEqual('stuff', userdata.decode('utf-8'))
@hp.activate
def test_userdata_fetch_fail_not_found(self):
@@ -24,7 +24,7 @@ class TestEc2Util(helpers.HttprettyTestCase):
'http://169.254.169.254/%s/user-data' % (self.VERSION),
status=404)
userdata = eu.get_instance_userdata(self.VERSION, retries=0)
- self.assertEquals('', userdata)
+ self.assertEqual('', userdata)
@hp.activate
def test_userdata_fetch_fail_server_dead(self):
@@ -32,7 +32,7 @@ class TestEc2Util(helpers.HttprettyTestCase):
'http://169.254.169.254/%s/user-data' % (self.VERSION),
status=500)
userdata = eu.get_instance_userdata(self.VERSION, retries=0)
- self.assertEquals('', userdata)
+ self.assertEqual('', userdata)
@hp.activate
def test_userdata_fetch_fail_server_not_found(self):
@@ -40,7 +40,7 @@ class TestEc2Util(helpers.HttprettyTestCase):
'http://169.254.169.254/%s/user-data' % (self.VERSION),
status=404)
userdata = eu.get_instance_userdata(self.VERSION)
- self.assertEquals('', userdata)
+ self.assertEqual('', userdata)
@hp.activate
def test_metadata_fetch_no_keys(self):
@@ -56,9 +56,9 @@ class TestEc2Util(helpers.HttprettyTestCase):
hp.register_uri(hp.GET, uh.combine_url(base_url, 'ami-launch-index'),
status=200, body='1')
md = eu.get_instance_metadata(self.VERSION, retries=0)
- self.assertEquals(md['hostname'], 'ec2.fake.host.name.com')
- self.assertEquals(md['instance-id'], '123')
- self.assertEquals(md['ami-launch-index'], '1')
+ self.assertEqual(md['hostname'], 'ec2.fake.host.name.com')
+ self.assertEqual(md['instance-id'], '123')
+ self.assertEqual(md['ami-launch-index'], '1')
@hp.activate
def test_metadata_fetch_key(self):
@@ -77,9 +77,9 @@ class TestEc2Util(helpers.HttprettyTestCase):
uh.combine_url(base_url, 'public-keys/0/openssh-key'),
status=200, body='ssh-rsa AAAA.....wZEf my-public-key')
md = eu.get_instance_metadata(self.VERSION, retries=0, timeout=0.1)
- self.assertEquals(md['hostname'], 'ec2.fake.host.name.com')
- self.assertEquals(md['instance-id'], '123')
- self.assertEquals(1, len(md['public-keys']))
+ self.assertEqual(md['hostname'], 'ec2.fake.host.name.com')
+ self.assertEqual(md['instance-id'], '123')
+ self.assertEqual(1, len(md['public-keys']))
@hp.activate
def test_metadata_fetch_with_2_keys(self):
@@ -102,9 +102,9 @@ class TestEc2Util(helpers.HttprettyTestCase):
uh.combine_url(base_url, 'public-keys/1/openssh-key'),
status=200, body='ssh-rsa AAAA.....wZEf my-other-key')
md = eu.get_instance_metadata(self.VERSION, retries=0, timeout=0.1)
- self.assertEquals(md['hostname'], 'ec2.fake.host.name.com')
- self.assertEquals(md['instance-id'], '123')
- self.assertEquals(2, len(md['public-keys']))
+ self.assertEqual(md['hostname'], 'ec2.fake.host.name.com')
+ self.assertEqual(md['instance-id'], '123')
+ self.assertEqual(2, len(md['public-keys']))
@hp.activate
def test_metadata_fetch_bdm(self):
@@ -131,9 +131,9 @@ class TestEc2Util(helpers.HttprettyTestCase):
status=200,
body="sdc")
md = eu.get_instance_metadata(self.VERSION, retries=0, timeout=0.1)
- self.assertEquals(md['hostname'], 'ec2.fake.host.name.com')
- self.assertEquals(md['instance-id'], '123')
+ self.assertEqual(md['hostname'], 'ec2.fake.host.name.com')
+ self.assertEqual(md['instance-id'], '123')
bdm = md['block-device-mapping']
- self.assertEquals(2, len(bdm))
- self.assertEquals(bdm['ami'], 'sdb')
- self.assertEquals(bdm['ephemeral0'], 'sdc')
+ self.assertEqual(2, len(bdm))
+ self.assertEqual(bdm['ami'], 'sdb')
+ self.assertEqual(bdm['ephemeral0'], 'sdc')
diff --git a/tests/unittests/test_filters/test_launch_index.py b/tests/unittests/test_filters/test_launch_index.py
index 95d24b9b..395713e6 100644
--- a/tests/unittests/test_filters/test_launch_index.py
+++ b/tests/unittests/test_filters/test_launch_index.py
@@ -25,7 +25,7 @@ class TestLaunchFilter(helpers.ResourceUsingTestCase):
for (index, count) in expected_counts.items():
index = util.safe_int(index)
filtered_message = launch_index.Filter(index).apply(message)
- self.assertEquals(count_messages(filtered_message), count)
+ self.assertEqual(count_messages(filtered_message), count)
# Ensure original message still ok/not modified
self.assertTrue(self.equivalentMessage(message, orig_message))
diff --git a/tests/unittests/test_handler/test_handler_apt_configure.py b/tests/unittests/test_handler/test_handler_apt_configure.py
index 1ed185ca..d1dca2c4 100644
--- a/tests/unittests/test_handler/test_handler_apt_configure.py
+++ b/tests/unittests/test_handler/test_handler_apt_configure.py
@@ -1,6 +1,6 @@
+from cloudinit.config import cc_apt_configure
from cloudinit import util
-from cloudinit.config import cc_apt_configure
from ..helpers import TestCase
import os
diff --git a/tests/unittests/test_handler/test_handler_ca_certs.py b/tests/unittests/test_handler/test_handler_ca_certs.py
index a6b9c0fd..5e771731 100644
--- a/tests/unittests/test_handler/test_handler_ca_certs.py
+++ b/tests/unittests/test_handler/test_handler_ca_certs.py
@@ -1,8 +1,8 @@
from cloudinit import cloud
+from cloudinit.config import cc_ca_certs
from cloudinit import helpers
from cloudinit import util
-from cloudinit.config import cc_ca_certs
from ..helpers import TestCase
import logging
@@ -176,8 +176,7 @@ class TestAddCaCerts(TestCase):
mock_write.assert_has_calls([
mock.call("/usr/share/ca-certificates/cloud-init-ca-certs.crt",
cert, mode=0o644),
- mock.call("/etc/ca-certificates.conf", expected, omode="wb"),
- ])
+ mock.call("/etc/ca-certificates.conf", expected, omode="wb")])
mock_load.assert_called_once_with("/etc/ca-certificates.conf")
def test_single_cert_no_trailing_cr(self):
@@ -202,8 +201,7 @@ class TestAddCaCerts(TestCase):
mock.call("/etc/ca-certificates.conf",
"%s\n%s\n" % (ca_certs_content,
"cloud-init-ca-certs.crt"),
- omode="wb"),
- ])
+ omode="wb")])
mock_load.assert_called_once_with("/etc/ca-certificates.conf")
@@ -228,8 +226,7 @@ class TestAddCaCerts(TestCase):
mock.call("/etc/ca-certificates.conf",
"%s\n%s\n" % (ca_certs_content,
"cloud-init-ca-certs.crt"),
- omode='wb'),
- ])
+ omode='wb')])
mock_load.assert_called_once_with("/etc/ca-certificates.conf")
@@ -264,8 +261,7 @@ class TestRemoveDefaultCaCerts(TestCase):
mock_delete.assert_has_calls([
mock.call("/usr/share/ca-certificates/"),
- mock.call("/etc/ssl/certs/"),
- ])
+ mock.call("/etc/ssl/certs/")])
mock_write.assert_called_once_with(
"/etc/ca-certificates.conf", "", mode=0o644)
diff --git a/tests/unittests/test_handler/test_handler_chef.py b/tests/unittests/test_handler/test_handler_chef.py
index 7763f23b..7a1bc317 100644
--- a/tests/unittests/test_handler/test_handler_chef.py
+++ b/tests/unittests/test_handler/test_handler_chef.py
@@ -1,21 +1,19 @@
import json
+import logging
import os
-
-from cloudinit.config import cc_chef
+import shutil
+import six
+import tempfile
from cloudinit import cloud
+from cloudinit.config import cc_chef
from cloudinit import distros
from cloudinit import helpers
-from cloudinit import util
from cloudinit.sources import DataSourceNone
+from cloudinit import util
from .. import helpers as t_help
-import six
-import logging
-import shutil
-import tempfile
-
LOG = logging.getLogger(__name__)
CLIENT_TEMPL = os.path.sep.join(["templates", "chef_client.rb.tmpl"])
diff --git a/tests/unittests/test_handler/test_handler_growpart.py b/tests/unittests/test_handler/test_handler_growpart.py
index bef0d80d..e653488a 100644
--- a/tests/unittests/test_handler/test_handler_growpart.py
+++ b/tests/unittests/test_handler/test_handler_growpart.py
@@ -1,7 +1,7 @@
from cloudinit import cloud
+from cloudinit.config import cc_growpart
from cloudinit import util
-from cloudinit.config import cc_growpart
from ..helpers import TestCase
import errno
diff --git a/tests/unittests/test_handler/test_handler_locale.py b/tests/unittests/test_handler/test_handler_locale.py
index de85eff6..c91908f4 100644
--- a/tests/unittests/test_handler/test_handler_locale.py
+++ b/tests/unittests/test_handler/test_handler_locale.py
@@ -64,4 +64,4 @@ class TestLocale(t_help.FilesystemMockingTestCase):
contents = util.load_file('/etc/sysconfig/language', decode=False)
n_cfg = ConfigObj(BytesIO(contents))
- self.assertEquals({'RC_LANG': cfg['locale']}, dict(n_cfg))
+ self.assertEqual({'RC_LANG': cfg['locale']}, dict(n_cfg))
diff --git a/tests/unittests/test_handler/test_handler_lxd.py b/tests/unittests/test_handler/test_handler_lxd.py
index 5f61ba6a..6f90defb 100644
--- a/tests/unittests/test_handler/test_handler_lxd.py
+++ b/tests/unittests/test_handler/test_handler_lxd.py
@@ -1,6 +1,6 @@
from cloudinit.config import cc_lxd
-from cloudinit import (distros, helpers, cloud)
from cloudinit.sources import DataSourceNoCloud
+from cloudinit import (distros, helpers, cloud)
from .. import helpers as t_help
import logging
@@ -42,11 +42,11 @@ class TestLxd(t_help.TestCase):
cc_lxd.handle('cc_lxd', self.lxd_cfg, cc, LOG, [])
self.assertTrue(mock_util.which.called)
init_call = mock_util.subp.call_args_list[0][0][0]
- self.assertEquals(init_call,
- ['lxd', 'init', '--auto',
- '--network-address=0.0.0.0',
- '--storage-backend=zfs',
- '--storage-pool=poolname'])
+ self.assertEqual(init_call,
+ ['lxd', 'init', '--auto',
+ '--network-address=0.0.0.0',
+ '--storage-backend=zfs',
+ '--storage-pool=poolname'])
@mock.patch("cloudinit.config.cc_lxd.util")
def test_lxd_install(self, mock_util):
@@ -56,7 +56,7 @@ class TestLxd(t_help.TestCase):
cc_lxd.handle('cc_lxd', self.lxd_cfg, cc, LOG, [])
self.assertTrue(cc.distro.install_packages.called)
install_pkg = cc.distro.install_packages.call_args_list[0][0][0]
- self.assertEquals(sorted(install_pkg), ['lxd', 'zfs'])
+ self.assertEqual(sorted(install_pkg), ['lxd', 'zfs'])
@mock.patch("cloudinit.config.cc_lxd.util")
def test_no_init_does_nothing(self, mock_util):
@@ -87,7 +87,7 @@ class TestLxd(t_help.TestCase):
"ipv6_netmask": "64",
"ipv6_nat": "true",
"domain": "lxd"}
- self.assertEquals(
+ self.assertEqual(
cc_lxd.bridge_to_debconf(data),
{"lxd/setup-bridge": "true",
"lxd/bridge-name": "testbr0",
@@ -109,7 +109,7 @@ class TestLxd(t_help.TestCase):
"ipv6_address": "fd98:9e0:3744::1",
"ipv6_netmask": "64",
"ipv6_nat": "true"}
- self.assertEquals(
+ self.assertEqual(
cc_lxd.bridge_to_debconf(data),
{"lxd/setup-bridge": "true",
"lxd/bridge-ipv6": "true",
@@ -120,7 +120,7 @@ class TestLxd(t_help.TestCase):
def test_lxd_debconf_existing(self):
data = {"mode": "existing",
"name": "testbr0"}
- self.assertEquals(
+ self.assertEqual(
cc_lxd.bridge_to_debconf(data),
{"lxd/setup-bridge": "false",
"lxd/use-existing-bridge": "true",
@@ -128,7 +128,7 @@ class TestLxd(t_help.TestCase):
def test_lxd_debconf_none(self):
data = {"mode": "none"}
- self.assertEquals(
+ self.assertEqual(
cc_lxd.bridge_to_debconf(data),
{"lxd/setup-bridge": "false",
"lxd/bridge-name": ""})
diff --git a/tests/unittests/test_handler/test_handler_power_state.py b/tests/unittests/test_handler/test_handler_power_state.py
index 04ce5687..feff319d 100644
--- a/tests/unittests/test_handler/test_handler_power_state.py
+++ b/tests/unittests/test_handler/test_handler_power_state.py
@@ -119,7 +119,7 @@ def check_lps_ret(psc_return, mode=None):
try:
float(timeout)
- except:
+ except Exception:
errs.append("timeout failed convert to float")
if len(errs):
diff --git a/tests/unittests/test_handler/test_handler_rsyslog.py b/tests/unittests/test_handler/test_handler_rsyslog.py
index b932165c..38636063 100644
--- a/tests/unittests/test_handler/test_handler_rsyslog.py
+++ b/tests/unittests/test_handler/test_handler_rsyslog.py
@@ -31,7 +31,7 @@ class TestLoadConfig(t_help.TestCase):
'config_dir': "mydir",
'config_filename': 'myfilename',
'service_reload_command': 'auto'}
- )
+ )
self.assertEqual(found, self.basecfg)
diff --git a/tests/unittests/test_handler/test_handler_seed_random.py b/tests/unittests/test_handler/test_handler_seed_random.py
index 98bc9b81..a0390da9 100644
--- a/tests/unittests/test_handler/test_handler_seed_random.py
+++ b/tests/unittests/test_handler/test_handler_seed_random.py
@@ -92,7 +92,7 @@ class TestRandomSeed(t_help.TestCase):
}
cc_seed_random.handle('test', cfg, self._get_cloud('ubuntu'), LOG, [])
contents = util.load_file(self._seed_file)
- self.assertEquals("tiny-tim-was-here", contents)
+ self.assertEqual("tiny-tim-was-here", contents)
def test_append_random_unknown_encoding(self):
data = self._compress(b"tiny-toe")
@@ -117,7 +117,7 @@ class TestRandomSeed(t_help.TestCase):
}
cc_seed_random.handle('test', cfg, self._get_cloud('ubuntu'), LOG, [])
contents = util.load_file(self._seed_file)
- self.assertEquals("tiny-toe", contents)
+ self.assertEqual("tiny-toe", contents)
def test_append_random_gz(self):
data = self._compress(b"big-toe")
@@ -130,7 +130,7 @@ class TestRandomSeed(t_help.TestCase):
}
cc_seed_random.handle('test', cfg, self._get_cloud('ubuntu'), LOG, [])
contents = util.load_file(self._seed_file)
- self.assertEquals("big-toe", contents)
+ self.assertEqual("big-toe", contents)
def test_append_random_base64(self):
data = util.b64e('bubbles')
@@ -143,7 +143,7 @@ class TestRandomSeed(t_help.TestCase):
}
cc_seed_random.handle('test', cfg, self._get_cloud('ubuntu'), LOG, [])
contents = util.load_file(self._seed_file)
- self.assertEquals("bubbles", contents)
+ self.assertEqual("bubbles", contents)
def test_append_random_b64(self):
data = util.b64e('kit-kat')
@@ -156,7 +156,7 @@ class TestRandomSeed(t_help.TestCase):
}
cc_seed_random.handle('test', cfg, self._get_cloud('ubuntu'), LOG, [])
contents = util.load_file(self._seed_file)
- self.assertEquals("kit-kat", contents)
+ self.assertEqual("kit-kat", contents)
def test_append_random_metadata(self):
cfg = {
@@ -168,7 +168,7 @@ class TestRandomSeed(t_help.TestCase):
c = self._get_cloud('ubuntu', {'random_seed': '-so-was-josh'})
cc_seed_random.handle('test', cfg, c, LOG, [])
contents = util.load_file(self._seed_file)
- self.assertEquals('tiny-tim-was-here-so-was-josh', contents)
+ self.assertEqual('tiny-tim-was-here-so-was-josh', contents)
def test_seed_command_provided_and_available(self):
c = self._get_cloud('ubuntu', {})
diff --git a/tests/unittests/test_handler/test_handler_set_hostname.py b/tests/unittests/test_handler/test_handler_set_hostname.py
index d358b069..7effa124 100644
--- a/tests/unittests/test_handler/test_handler_set_hostname.py
+++ b/tests/unittests/test_handler/test_handler_set_hostname.py
@@ -7,13 +7,11 @@ from cloudinit import util
from .. import helpers as t_help
-import shutil
-import tempfile
+from configobj import ConfigObj
import logging
-
+import shutil
from six import BytesIO
-
-from configobj import ConfigObj
+import tempfile
LOG = logging.getLogger(__name__)
@@ -43,8 +41,8 @@ class TestHostname(t_help.FilesystemMockingTestCase):
if not distro.uses_systemd():
contents = util.load_file("/etc/sysconfig/network", decode=False)
n_cfg = ConfigObj(BytesIO(contents))
- self.assertEquals({'HOSTNAME': 'blah.blah.blah.yahoo.com'},
- dict(n_cfg))
+ self.assertEqual({'HOSTNAME': 'blah.blah.blah.yahoo.com'},
+ dict(n_cfg))
def test_write_hostname_debian(self):
cfg = {
@@ -58,7 +56,7 @@ class TestHostname(t_help.FilesystemMockingTestCase):
cc_set_hostname.handle('cc_set_hostname',
cfg, cc, LOG, [])
contents = util.load_file("/etc/hostname")
- self.assertEquals('blah', contents.strip())
+ self.assertEqual('blah', contents.strip())
def test_write_hostname_sles(self):
cfg = {
@@ -71,4 +69,4 @@ class TestHostname(t_help.FilesystemMockingTestCase):
self.patchUtils(self.tmp)
cc_set_hostname.handle('cc_set_hostname', cfg, cc, LOG, [])
contents = util.load_file("/etc/HOSTNAME")
- self.assertEquals('blah', contents.strip())
+ self.assertEqual('blah', contents.strip())
diff --git a/tests/unittests/test_handler/test_handler_snappy.py b/tests/unittests/test_handler/test_handler_snappy.py
index 8aeff53c..57dce1bc 100644
--- a/tests/unittests/test_handler/test_handler_snappy.py
+++ b/tests/unittests/test_handler/test_handler_snappy.py
@@ -1,6 +1,7 @@
from cloudinit.config.cc_snappy import (
makeop, get_package_ops, render_snap_op)
from cloudinit import util
+
from .. import helpers as t_help
import os
diff --git a/tests/unittests/test_handler/test_handler_timezone.py b/tests/unittests/test_handler/test_handler_timezone.py
index e3df8759..b7e6b03d 100644
--- a/tests/unittests/test_handler/test_handler_timezone.py
+++ b/tests/unittests/test_handler/test_handler_timezone.py
@@ -28,12 +28,10 @@ from cloudinit.sources import DataSourceNoCloud
from .. import helpers as t_help
from configobj import ConfigObj
-
-from six import BytesIO
-
+import logging
import shutil
+from six import BytesIO
import tempfile
-import logging
LOG = logging.getLogger(__name__)
@@ -72,7 +70,7 @@ class TestTimezone(t_help.FilesystemMockingTestCase):
contents = util.load_file('/etc/sysconfig/clock', decode=False)
n_cfg = ConfigObj(BytesIO(contents))
- self.assertEquals({'TIMEZONE': cfg['timezone']}, dict(n_cfg))
+ self.assertEqual({'TIMEZONE': cfg['timezone']}, dict(n_cfg))
contents = util.load_file('/etc/localtime')
- self.assertEquals(dummy_contents, contents.strip())
+ self.assertEqual(dummy_contents, contents.strip())
diff --git a/tests/unittests/test_handler/test_handler_write_files.py b/tests/unittests/test_handler/test_handler_write_files.py
index f1c7f7b4..466e45f8 100644
--- a/tests/unittests/test_handler/test_handler_write_files.py
+++ b/tests/unittests/test_handler/test_handler_write_files.py
@@ -1,6 +1,6 @@
-from cloudinit import util
-from cloudinit import log as logging
from cloudinit.config.cc_write_files import write_files
+from cloudinit import log as logging
+from cloudinit import util
from ..helpers import FilesystemMockingTestCase
diff --git a/tests/unittests/test_handler/test_handler_yum_add_repo.py b/tests/unittests/test_handler/test_handler_yum_add_repo.py
index 3a8aa7c1..28b060f8 100644
--- a/tests/unittests/test_handler/test_handler_yum_add_repo.py
+++ b/tests/unittests/test_handler/test_handler_yum_add_repo.py
@@ -1,16 +1,13 @@
-from cloudinit import util
-
from cloudinit.config import cc_yum_add_repo
+from cloudinit import util
from .. import helpers
-import shutil
-import tempfile
+import configobj
import logging
-
+import shutil
from six import BytesIO
-
-import configobj
+import tempfile
LOG = logging.getLogger(__name__)
@@ -68,4 +65,4 @@ class TestConfig(helpers.FilesystemMockingTestCase):
'gpgcheck': '1',
}
}
- self.assertEquals(expected, dict(contents))
+ self.assertEqual(expected, dict(contents))
diff --git a/tests/unittests/test_merging.py b/tests/unittests/test_merging.py
index 976d8283..681f3780 100644
--- a/tests/unittests/test_merging.py
+++ b/tests/unittests/test_merging.py
@@ -133,7 +133,7 @@ class TestSimpleRun(helpers.ResourceUsingTestCase):
for test in test_dicts:
c = _old_mergemanydict(*test)
d = util.mergemanydict(test)
- self.assertEquals(c, d)
+ self.assertEqual(c, d)
def test_merge_cc_samples(self):
tests = self._load_merge_files()
@@ -155,7 +155,7 @@ class TestSimpleRun(helpers.ResourceUsingTestCase):
fail_msg = fail_msg % (expected_fn,
",".join(merging_fns), merged_buf,
expected_merge)
- self.assertEquals(expected_merge, merged_buf, msg=fail_msg)
+ self.assertEqual(expected_merge, merged_buf, msg=fail_msg)
def test_compat_merges_dict(self):
a = {
@@ -167,7 +167,7 @@ class TestSimpleRun(helpers.ResourceUsingTestCase):
}
c = _old_mergedict(a, b)
d = util.mergemanydict([a, b])
- self.assertEquals(c, d)
+ self.assertEqual(c, d)
def test_compat_merges_dict2(self):
a = {
@@ -182,7 +182,7 @@ class TestSimpleRun(helpers.ResourceUsingTestCase):
}
c = _old_mergedict(a, b)
d = util.mergemanydict([a, b])
- self.assertEquals(c, d)
+ self.assertEqual(c, d)
def test_compat_merges_list(self):
a = {'b': [1, 2, 3]}
@@ -190,7 +190,7 @@ class TestSimpleRun(helpers.ResourceUsingTestCase):
c = {'b': [6, 7]}
e = _old_mergemanydict(a, b, c)
f = util.mergemanydict([a, b, c])
- self.assertEquals(e, f)
+ self.assertEqual(e, f)
def test_compat_merges_str(self):
a = {'b': "hi"}
@@ -198,7 +198,7 @@ class TestSimpleRun(helpers.ResourceUsingTestCase):
c = {'b': "hallo"}
e = _old_mergemanydict(a, b, c)
f = util.mergemanydict([a, b, c])
- self.assertEquals(e, f)
+ self.assertEqual(e, f)
def test_compat_merge_sub_dict(self):
a = {
@@ -222,7 +222,7 @@ class TestSimpleRun(helpers.ResourceUsingTestCase):
}
c = _old_mergedict(a, b)
d = util.mergemanydict([a, b])
- self.assertEquals(c, d)
+ self.assertEqual(c, d)
def test_compat_merge_sub_dict2(self):
a = {
@@ -238,7 +238,7 @@ class TestSimpleRun(helpers.ResourceUsingTestCase):
}
c = _old_mergedict(a, b)
d = util.mergemanydict([a, b])
- self.assertEquals(c, d)
+ self.assertEqual(c, d)
def test_compat_merge_sub_list(self):
a = {
@@ -254,4 +254,4 @@ class TestSimpleRun(helpers.ResourceUsingTestCase):
}
c = _old_mergedict(a, b)
d = util.mergemanydict([a, b])
- self.assertEquals(c, d)
+ self.assertEqual(c, d)
diff --git a/tests/unittests/test_net.py b/tests/unittests/test_net.py
index 09235c4d..624a9aa8 100644
--- a/tests/unittests/test_net.py
+++ b/tests/unittests/test_net.py
@@ -1,11 +1,12 @@
-from cloudinit import util
from cloudinit import net
+from cloudinit import util
+
from .helpers import TestCase
import base64
import copy
-import io
import gzip
+import io
import json
import os
diff --git a/tests/unittests/test_reporting.py b/tests/unittests/test_reporting.py
index 32356ef9..5cad8406 100644
--- a/tests/unittests/test_reporting.py
+++ b/tests/unittests/test_reporting.py
@@ -4,8 +4,8 @@
# vi: ts=4 expandtab
from cloudinit import reporting
-from cloudinit.reporting import handlers
from cloudinit.reporting import events
+from cloudinit.reporting import handlers
from .helpers import (mock, TestCase)
diff --git a/tests/unittests/test_rh_subscription.py b/tests/unittests/test_rh_subscription.py
index 8c586ad7..b84c807b 100644
--- a/tests/unittests/test_rh_subscription.py
+++ b/tests/unittests/test_rh_subscription.py
@@ -1,5 +1,6 @@
-from cloudinit import util
from cloudinit.config import cc_rh_subscription
+from cloudinit import util
+
import logging
import mock
import unittest
diff --git a/tests/unittests/test_runs/test_merge_run.py b/tests/unittests/test_runs/test_merge_run.py
index d0ec36a9..ce43798e 100644
--- a/tests/unittests/test_runs/test_merge_run.py
+++ b/tests/unittests/test_runs/test_merge_run.py
@@ -42,13 +42,13 @@ class TestMergeRun(helpers.FilesystemMockingTestCase):
args=[PER_INSTANCE],
freq=PER_INSTANCE)
mirrors = initer.distro.get_option('package_mirrors')
- self.assertEquals(1, len(mirrors))
+ self.assertEqual(1, len(mirrors))
mirror = mirrors[0]
- self.assertEquals(mirror['arches'], ['i386', 'amd64', 'blah'])
+ self.assertEqual(mirror['arches'], ['i386', 'amd64', 'blah'])
mods = stages.Modules(initer)
(which_ran, failures) = mods.run_section('cloud_init_modules')
self.assertTrue(len(failures) == 0)
self.assertTrue(os.path.exists('/etc/blah.ini'))
self.assertIn('write-files', which_ran)
contents = util.load_file('/etc/blah.ini')
- self.assertEquals(contents, 'blah')
+ self.assertEqual(contents, 'blah')
diff --git a/tests/unittests/test_runs/test_simple_run.py b/tests/unittests/test_runs/test_simple_run.py
index e19e65cd..07e7b1a8 100644
--- a/tests/unittests/test_runs/test_simple_run.py
+++ b/tests/unittests/test_runs/test_simple_run.py
@@ -63,7 +63,7 @@ class TestSimpleRun(helpers.FilesystemMockingTestCase):
initer.fetch()
iid = initer.instancify()
- self.assertEquals(iid, 'iid-datasource-none')
+ self.assertEqual(iid, 'iid-datasource-none')
initer.update()
self.assertTrue(os.path.islink("var/lib/cloud/instance"))
@@ -78,4 +78,4 @@ class TestSimpleRun(helpers.FilesystemMockingTestCase):
self.assertTrue(os.path.exists('/etc/blah.ini'))
self.assertIn('write-files', which_ran)
contents = util.load_file('/etc/blah.ini')
- self.assertEquals(contents, 'blah')
+ self.assertEqual(contents, 'blah')
diff --git a/tests/unittests/test_templating.py b/tests/unittests/test_templating.py
index b9863650..94b6e061 100644
--- a/tests/unittests/test_templating.py
+++ b/tests/unittests/test_templating.py
@@ -58,7 +58,7 @@ class TestTemplates(test_helpers.TestCase):
blob = "blahblah $blah"
(template_type, renderer, contents) = templater.detect_template(blob)
self.assertIn("cheetah", template_type)
- self.assertEquals(blob, contents)
+ self.assertEqual(blob, contents)
blob = '##template:something-new'
self.assertRaises(ValueError, templater.detect_template, blob)
@@ -67,18 +67,18 @@ class TestTemplates(test_helpers.TestCase):
blob = '''## template:cheetah
$a,$b'''
c = templater.render_string(blob, {"a": 1, "b": 2})
- self.assertEquals("1,2", c)
+ self.assertEqual("1,2", c)
def test_render_jinja(self):
blob = '''## template:jinja
{{a}},{{b}}'''
c = templater.render_string(blob, {"a": 1, "b": 2})
- self.assertEquals("1,2", c)
+ self.assertEqual("1,2", c)
def test_render_default(self):
blob = '''$a,$b'''
c = templater.render_string(blob, {"a": 1, "b": 2})
- self.assertEquals("1,2", c)
+ self.assertEqual("1,2", c)
def test_render_basic_deeper(self):
hn = 'myfoohost.yahoo.com'
diff --git a/tox.ini b/tox.ini
index bd7c27dd..dafaaf6d 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
[tox]
-envlist = py27,py3,pyflakes
+envlist = py27,py3,flake8
recreate = True
[testenv]
@@ -10,10 +10,9 @@ deps = -r{toxinidir}/test-requirements.txt
[testenv:py3]
basepython = python3
-[testenv:pyflakes]
+[testenv:flake8]
basepython = python3
-commands = {envpython} -m pyflakes {posargs:cloudinit/ tests/ tools/}
- {envpython} -m pep8 {posargs:cloudinit/ tests/ tools/}
+commands = {envpython} -m flake8 {posargs:cloudinit/ tests/ tools/}
# https://github.com/gabrielfalcao/HTTPretty/issues/223
setenv =
@@ -30,3 +29,7 @@ deps =
pyflakes
setenv =
LC_ALL = C
+
+[flake8]
+ignore=H404,H405,H105,H301,H104,H403,H101
+exclude = .venv,.tox,dist,doc,*egg,.git,build,tools