Merge ~smoser/cloud-init:cleanup/pylint-respect-W0612-unused-variable into cloud-init:master

Proposed by Scott Moser
Status: Merged
Approved by: Scott Moser
Approved revision: 3ddd3a322945a9bff8d1906fe2a268c70f851b92
Merge reported by: Chad Smith
Merged at revision: 1081962eacf2814fea6f4fa3255c530de14e4a24
Proposed branch: ~smoser/cloud-init:cleanup/pylint-respect-W0612-unused-variable
Merge into: cloud-init:master
Diff against target: 955 lines (+95/-112)
51 files modified
.pylintrc (+1/-1)
cloudinit/analyze/dump.py (+1/-1)
cloudinit/cmd/tests/test_main.py (+3/-3)
cloudinit/config/cc_apt_configure.py (+1/-1)
cloudinit/config/cc_emit_upstart.py (+1/-1)
cloudinit/config/cc_resizefs.py (+3/-5)
cloudinit/config/cc_rh_subscription.py (+8/-10)
cloudinit/config/cc_snap.py (+2/-2)
cloudinit/config/cc_snappy.py (+2/-2)
cloudinit/config/cc_ubuntu_advantage.py (+2/-2)
cloudinit/config/schema.py (+2/-2)
cloudinit/distros/freebsd.py (+1/-1)
cloudinit/distros/ubuntu.py (+1/-1)
cloudinit/net/__init__.py (+1/-1)
cloudinit/net/cmdline.py (+1/-1)
cloudinit/net/dhcp.py (+1/-1)
cloudinit/net/sysconfig.py (+1/-1)
cloudinit/reporting/events.py (+1/-1)
cloudinit/sources/DataSourceAliYun.py (+1/-1)
cloudinit/sources/DataSourceAzure.py (+13/-20)
cloudinit/sources/DataSourceMAAS.py (+1/-1)
cloudinit/sources/DataSourceOVF.py (+1/-1)
cloudinit/sources/DataSourceOpenStack.py (+2/-2)
cloudinit/sources/helpers/digitalocean.py (+3/-4)
cloudinit/sources/helpers/openstack.py (+1/-1)
cloudinit/sources/helpers/vmware/imc/config_nic.py (+1/-1)
cloudinit/sources/helpers/vmware/imc/config_passwd.py (+2/-2)
cloudinit/sources/helpers/vmware/imc/guestcust_util.py (+2/-2)
cloudinit/sources/tests/test_init.py (+1/-1)
cloudinit/templater.py (+1/-1)
cloudinit/tests/helpers.py (+1/-1)
cloudinit/tests/test_util.py (+1/-1)
cloudinit/url_helper.py (+1/-1)
cloudinit/util.py (+1/-1)
tests/cloud_tests/bddeb.py (+1/-1)
tests/cloud_tests/collect.py (+2/-1)
tests/cloud_tests/platforms/instances.py (+1/-1)
tests/cloud_tests/platforms/lxd/instance.py (+4/-6)
tests/cloud_tests/setup_image.py (+5/-6)
tests/cloud_tests/testcases/base.py (+1/-1)
tests/cloud_tests/testcases/examples/including_user_groups.py (+1/-1)
tests/cloud_tests/testcases/modules/user_groups.py (+1/-1)
tests/cloud_tests/util.py (+1/-1)
tests/unittests/test__init__.py (+1/-1)
tests/unittests/test_datasource/test_azure.py (+2/-2)
tests/unittests/test_datasource/test_maas.py (+2/-2)
tests/unittests/test_datasource/test_nocloud.py (+0/-3)
tests/unittests/test_handler/test_handler_apt_source_v3.py (+1/-1)
tests/unittests/test_handler/test_handler_ntp.py (+1/-1)
tests/unittests/test_templating.py (+2/-2)
tests/unittests/test_util.py (+3/-3)
Reviewer Review Type Date Requested Status
Ryan Harper Approve
Server Team CI bot continuous-integration Approve
Review via email: mp+343469@code.launchpad.net

Commit message

pylint: pay attention to unused variable warnings.

This enables warnings produced by pylint for unused variables (W0612),
and fixes the existing errors.

Description of the change

see commit message

To post a comment you must log in.
Revision history for this message
Server Team CI bot (server-team-bot) wrote :

FAILED: Continuous integration, rev:2a46897cce9284be00a722d7b2b30a8a8f28a6e9
https://jenkins.ubuntu.com/server/job/cloud-init-ci/1019/
Executed test runs:
    SUCCESS: Checkout
    FAILED: Unit & Style Tests

Click here to trigger a rebuild:
https://jenkins.ubuntu.com/server/job/cloud-init-ci/1019/rebuild

review: Needs Fixing (continuous-integration)
Revision history for this message
Ryan Harper (raharper) wrote :

Fix your commit message, you're paying attention to:

# W0612(unused-variable)

Not

# W0621(redefined-outer-name)

Revision history for this message
Ryan Harper (raharper) wrote :

tox -e pylint finds a few more for me.

Revision history for this message
Server Team CI bot (server-team-bot) wrote :

FAILED: Continuous integration, rev:41e3e47422f4c4bbb4fcbbd93ebf5b03b56f979d
https://jenkins.ubuntu.com/server/job/cloud-init-ci/1020/
Executed test runs:
    SUCCESS: Checkout
    FAILED: Unit & Style Tests

Click here to trigger a rebuild:
https://jenkins.ubuntu.com/server/job/cloud-init-ci/1020/rebuild

review: Needs Fixing (continuous-integration)
Revision history for this message
Server Team CI bot (server-team-bot) wrote :

PASSED: Continuous integration, rev:3ddd3a322945a9bff8d1906fe2a268c70f851b92
https://jenkins.ubuntu.com/server/job/cloud-init-ci/1021/
Executed test runs:
    SUCCESS: Checkout
    SUCCESS: Unit & Style Tests
    SUCCESS: Ubuntu LTS: Build
    SUCCESS: Ubuntu LTS: Integration
    SUCCESS: MAAS Compatability Testing
    IN_PROGRESS: Declarative: Post Actions

Click here to trigger a rebuild:
https://jenkins.ubuntu.com/server/job/cloud-init-ci/1021/rebuild

review: Approve (continuous-integration)
Revision history for this message
Ryan Harper (raharper) wrote :

Looks good.

review: Approve
Revision history for this message
Chad Smith (chad.smith) wrote :

An upstream commit landed for this bug.

To view that commit see the following URL:
https://git.launchpad.net/cloud-init/commit/?id=1081962e

There was an error fetching revisions from git servers. Please try again in a few minutes. If the problem persists, contact Launchpad support.

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
diff --git a/.pylintrc b/.pylintrc
index 0bdfa59..3bfa0c8 100644
--- a/.pylintrc
+++ b/.pylintrc
@@ -28,7 +28,7 @@ jobs=4
28# W0703(broad-except)28# W0703(broad-except)
29# W1401(anomalous-backslash-in-string)29# W1401(anomalous-backslash-in-string)
3030
31disable=C, F, I, R, W0105, W0107, W0201, W0212, W0221, W0222, W0223, W0231, W0311, W0511, W0602, W0603, W0611, W0612, W0613, W0621, W0622, W0631, W0703, W140131disable=C, F, I, R, W0105, W0107, W0201, W0212, W0221, W0222, W0223, W0231, W0311, W0511, W0602, W0603, W0611, W0613, W0621, W0622, W0631, W0703, W1401
3232
3333
34[REPORTS]34[REPORTS]
diff --git a/cloudinit/analyze/dump.py b/cloudinit/analyze/dump.py
index b071aa1..1f3060d 100644
--- a/cloudinit/analyze/dump.py
+++ b/cloudinit/analyze/dump.py
@@ -112,7 +112,7 @@ def parse_ci_logline(line):
112 return None112 return None
113 event_description = stage_to_description[event_name]113 event_description = stage_to_description[event_name]
114 else:114 else:
115 (pymodloglvl, event_type, event_name) = eventstr.split()[0:3]115 (_pymodloglvl, event_type, event_name) = eventstr.split()[0:3]
116 event_description = eventstr.split(event_name)[1].strip()116 event_description = eventstr.split(event_name)[1].strip()
117117
118 event = {118 event = {
diff --git a/cloudinit/cmd/tests/test_main.py b/cloudinit/cmd/tests/test_main.py
index dbe421c..e2c54ae 100644
--- a/cloudinit/cmd/tests/test_main.py
+++ b/cloudinit/cmd/tests/test_main.py
@@ -56,7 +56,7 @@ class TestMain(FilesystemMockingTestCase):
56 cmdargs = myargs(56 cmdargs = myargs(
57 debug=False, files=None, force=False, local=False, reporter=None,57 debug=False, files=None, force=False, local=False, reporter=None,
58 subcommand='init')58 subcommand='init')
59 (item1, item2) = wrap_and_call(59 (_item1, item2) = wrap_and_call(
60 'cloudinit.cmd.main',60 'cloudinit.cmd.main',
61 {'util.close_stdin': True,61 {'util.close_stdin': True,
62 'netinfo.debug_info': 'my net debug info',62 'netinfo.debug_info': 'my net debug info',
@@ -85,7 +85,7 @@ class TestMain(FilesystemMockingTestCase):
85 cmdargs = myargs(85 cmdargs = myargs(
86 debug=False, files=None, force=False, local=False, reporter=None,86 debug=False, files=None, force=False, local=False, reporter=None,
87 subcommand='init')87 subcommand='init')
88 (item1, item2) = wrap_and_call(88 (_item1, item2) = wrap_and_call(
89 'cloudinit.cmd.main',89 'cloudinit.cmd.main',
90 {'util.close_stdin': True,90 {'util.close_stdin': True,
91 'netinfo.debug_info': 'my net debug info',91 'netinfo.debug_info': 'my net debug info',
@@ -133,7 +133,7 @@ class TestMain(FilesystemMockingTestCase):
133 self.assertEqual(main.LOG, log)133 self.assertEqual(main.LOG, log)
134 self.assertIsNone(args)134 self.assertIsNone(args)
135135
136 (item1, item2) = wrap_and_call(136 (_item1, item2) = wrap_and_call(
137 'cloudinit.cmd.main',137 'cloudinit.cmd.main',
138 {'util.close_stdin': True,138 {'util.close_stdin': True,
139 'netinfo.debug_info': 'my net debug info',139 'netinfo.debug_info': 'my net debug info',
diff --git a/cloudinit/config/cc_apt_configure.py b/cloudinit/config/cc_apt_configure.py
index 5b9cbca..e4cc993 100644
--- a/cloudinit/config/cc_apt_configure.py
+++ b/cloudinit/config/cc_apt_configure.py
@@ -378,7 +378,7 @@ def apply_debconf_selections(cfg, target=None):
378378
379 # get a complete list of packages listed in input379 # get a complete list of packages listed in input
380 pkgs_cfgd = set()380 pkgs_cfgd = set()
381 for key, content in selsets.items():381 for _key, content in selsets.items():
382 for line in content.splitlines():382 for line in content.splitlines():
383 if line.startswith("#"):383 if line.startswith("#"):
384 continue384 continue
diff --git a/cloudinit/config/cc_emit_upstart.py b/cloudinit/config/cc_emit_upstart.py
index 69dc2d5..eb9fbe6 100644
--- a/cloudinit/config/cc_emit_upstart.py
+++ b/cloudinit/config/cc_emit_upstart.py
@@ -43,7 +43,7 @@ def is_upstart_system():
43 del myenv['UPSTART_SESSION']43 del myenv['UPSTART_SESSION']
44 check_cmd = ['initctl', 'version']44 check_cmd = ['initctl', 'version']
45 try:45 try:
46 (out, err) = util.subp(check_cmd, env=myenv)46 (out, _err) = util.subp(check_cmd, env=myenv)
47 return 'upstart' in out47 return 'upstart' in out
48 except util.ProcessExecutionError as e:48 except util.ProcessExecutionError as e:
49 LOG.debug("'%s' returned '%s', not using upstart",49 LOG.debug("'%s' returned '%s', not using upstart",
diff --git a/cloudinit/config/cc_resizefs.py b/cloudinit/config/cc_resizefs.py
index 013e69b..82f29e1 100644
--- a/cloudinit/config/cc_resizefs.py
+++ b/cloudinit/config/cc_resizefs.py
@@ -89,13 +89,11 @@ def _resize_zfs(mount_point, devpth):
8989
9090
91def _get_dumpfs_output(mount_point):91def _get_dumpfs_output(mount_point):
92 dumpfs_res, err = util.subp(['dumpfs', '-m', mount_point])92 return util.subp(['dumpfs', '-m', mount_point])[0]
93 return dumpfs_res
9493
9594
96def _get_gpart_output(part):95def _get_gpart_output(part):
97 gpart_res, err = util.subp(['gpart', 'show', part])96 return util.subp(['gpart', 'show', part])[0]
98 return gpart_res
9997
10098
101def _can_skip_resize_ufs(mount_point, devpth):99def _can_skip_resize_ufs(mount_point, devpth):
@@ -113,7 +111,7 @@ def _can_skip_resize_ufs(mount_point, devpth):
113 if not line.startswith('#'):111 if not line.startswith('#'):
114 newfs_cmd = shlex.split(line)112 newfs_cmd = shlex.split(line)
115 opt_value = 'O:Ua:s:b:d:e:f:g:h:i:jk:m:o:'113 opt_value = 'O:Ua:s:b:d:e:f:g:h:i:jk:m:o:'
116 optlist, args = getopt.getopt(newfs_cmd[1:], opt_value)114 optlist, _args = getopt.getopt(newfs_cmd[1:], opt_value)
117 for o, a in optlist:115 for o, a in optlist:
118 if o == "-s":116 if o == "-s":
119 cur_fs_sz = int(a)117 cur_fs_sz = int(a)
diff --git a/cloudinit/config/cc_rh_subscription.py b/cloudinit/config/cc_rh_subscription.py
index 530808c..1c67943 100644
--- a/cloudinit/config/cc_rh_subscription.py
+++ b/cloudinit/config/cc_rh_subscription.py
@@ -209,8 +209,7 @@ class SubscriptionManager(object):
209 cmd.append("--serverurl={0}".format(self.server_hostname))209 cmd.append("--serverurl={0}".format(self.server_hostname))
210210
211 try:211 try:
212 return_out, return_err = self._sub_man_cli(cmd,212 return_out = self._sub_man_cli(cmd, logstring_val=True)[0]
213 logstring_val=True)
214 except util.ProcessExecutionError as e:213 except util.ProcessExecutionError as e:
215 if e.stdout == "":214 if e.stdout == "":
216 self.log_warn("Registration failed due "215 self.log_warn("Registration failed due "
@@ -233,8 +232,7 @@ class SubscriptionManager(object):
233232
234 # Attempting to register the system only233 # Attempting to register the system only
235 try:234 try:
236 return_out, return_err = self._sub_man_cli(cmd,235 return_out = self._sub_man_cli(cmd, logstring_val=True)[0]
237 logstring_val=True)
238 except util.ProcessExecutionError as e:236 except util.ProcessExecutionError as e:
239 if e.stdout == "":237 if e.stdout == "":
240 self.log_warn("Registration failed due "238 self.log_warn("Registration failed due "
@@ -257,7 +255,7 @@ class SubscriptionManager(object):
257 .format(self.servicelevel)]255 .format(self.servicelevel)]
258256
259 try:257 try:
260 return_out, return_err = self._sub_man_cli(cmd)258 return_out = self._sub_man_cli(cmd)[0]
261 except util.ProcessExecutionError as e:259 except util.ProcessExecutionError as e:
262 if e.stdout.rstrip() != '':260 if e.stdout.rstrip() != '':
263 for line in e.stdout.split("\n"):261 for line in e.stdout.split("\n"):
@@ -275,7 +273,7 @@ class SubscriptionManager(object):
275 def _set_auto_attach(self):273 def _set_auto_attach(self):
276 cmd = ['attach', '--auto']274 cmd = ['attach', '--auto']
277 try:275 try:
278 return_out, return_err = self._sub_man_cli(cmd)276 return_out = self._sub_man_cli(cmd)[0]
279 except util.ProcessExecutionError as e:277 except util.ProcessExecutionError as e:
280 self.log_warn("Auto-attach failed with: {0}".format(e))278 self.log_warn("Auto-attach failed with: {0}".format(e))
281 return False279 return False
@@ -294,12 +292,12 @@ class SubscriptionManager(object):
294292
295 # Get all available pools293 # Get all available pools
296 cmd = ['list', '--available', '--pool-only']294 cmd = ['list', '--available', '--pool-only']
297 results, errors = self._sub_man_cli(cmd)295 results = self._sub_man_cli(cmd)[0]
298 available = (results.rstrip()).split("\n")296 available = (results.rstrip()).split("\n")
299297
300 # Get all consumed pools298 # Get all consumed pools
301 cmd = ['list', '--consumed', '--pool-only']299 cmd = ['list', '--consumed', '--pool-only']
302 results, errors = self._sub_man_cli(cmd)300 results = self._sub_man_cli(cmd)[0]
303 consumed = (results.rstrip()).split("\n")301 consumed = (results.rstrip()).split("\n")
304302
305 return available, consumed303 return available, consumed
@@ -311,14 +309,14 @@ class SubscriptionManager(object):
311 '''309 '''
312310
313 cmd = ['repos', '--list-enabled']311 cmd = ['repos', '--list-enabled']
314 return_out, return_err = self._sub_man_cli(cmd)312 return_out = self._sub_man_cli(cmd)[0]
315 active_repos = []313 active_repos = []
316 for repo in return_out.split("\n"):314 for repo in return_out.split("\n"):
317 if "Repo ID:" in repo:315 if "Repo ID:" in repo:
318 active_repos.append((repo.split(':')[1]).strip())316 active_repos.append((repo.split(':')[1]).strip())
319317
320 cmd = ['repos', '--list-disabled']318 cmd = ['repos', '--list-disabled']
321 return_out, return_err = self._sub_man_cli(cmd)319 return_out = self._sub_man_cli(cmd)[0]
322320
323 inactive_repos = []321 inactive_repos = []
324 for repo in return_out.split("\n"):322 for repo in return_out.split("\n"):
diff --git a/cloudinit/config/cc_snap.py b/cloudinit/config/cc_snap.py
index 34a53fd..202044c 100644
--- a/cloudinit/config/cc_snap.py
+++ b/cloudinit/config/cc_snap.py
@@ -204,12 +204,12 @@ def maybe_install_squashfuse(cloud):
204 return204 return
205 try:205 try:
206 cloud.distro.update_package_sources()206 cloud.distro.update_package_sources()
207 except Exception as e:207 except Exception:
208 util.logexc(LOG, "Package update failed")208 util.logexc(LOG, "Package update failed")
209 raise209 raise
210 try:210 try:
211 cloud.distro.install_packages(['squashfuse'])211 cloud.distro.install_packages(['squashfuse'])
212 except Exception as e:212 except Exception:
213 util.logexc(LOG, "Failed to install squashfuse")213 util.logexc(LOG, "Failed to install squashfuse")
214 raise214 raise
215215
diff --git a/cloudinit/config/cc_snappy.py b/cloudinit/config/cc_snappy.py
index bab80bb..15bee2d 100644
--- a/cloudinit/config/cc_snappy.py
+++ b/cloudinit/config/cc_snappy.py
@@ -213,7 +213,7 @@ def render_snap_op(op, name, path=None, cfgfile=None, config=None):
213213
214def read_installed_packages():214def read_installed_packages():
215 ret = []215 ret = []
216 for (name, date, version, dev) in read_pkg_data():216 for (name, _date, _version, dev) in read_pkg_data():
217 if dev:217 if dev:
218 ret.append(NAMESPACE_DELIM.join([name, dev]))218 ret.append(NAMESPACE_DELIM.join([name, dev]))
219 else:219 else:
@@ -222,7 +222,7 @@ def read_installed_packages():
222222
223223
224def read_pkg_data():224def read_pkg_data():
225 out, err = util.subp([SNAPPY_CMD, "list"])225 out, _err = util.subp([SNAPPY_CMD, "list"])
226 pkg_data = []226 pkg_data = []
227 for line in out.splitlines()[1:]:227 for line in out.splitlines()[1:]:
228 toks = line.split(sep=None, maxsplit=3)228 toks = line.split(sep=None, maxsplit=3)
diff --git a/cloudinit/config/cc_ubuntu_advantage.py b/cloudinit/config/cc_ubuntu_advantage.py
index 16b1868..903704f 100644
--- a/cloudinit/config/cc_ubuntu_advantage.py
+++ b/cloudinit/config/cc_ubuntu_advantage.py
@@ -149,12 +149,12 @@ def maybe_install_ua_tools(cloud):
149 return149 return
150 try:150 try:
151 cloud.distro.update_package_sources()151 cloud.distro.update_package_sources()
152 except Exception as e:152 except Exception:
153 util.logexc(LOG, "Package update failed")153 util.logexc(LOG, "Package update failed")
154 raise154 raise
155 try:155 try:
156 cloud.distro.install_packages(['ubuntu-advantage-tools'])156 cloud.distro.install_packages(['ubuntu-advantage-tools'])
157 except Exception as e:157 except Exception:
158 util.logexc(LOG, "Failed to install ubuntu-advantage-tools")158 util.logexc(LOG, "Failed to install ubuntu-advantage-tools")
159 raise159 raise
160160
diff --git a/cloudinit/config/schema.py b/cloudinit/config/schema.py
index ca7d0d5..76826e0 100644
--- a/cloudinit/config/schema.py
+++ b/cloudinit/config/schema.py
@@ -297,8 +297,8 @@ def get_schema():
297297
298 configs_dir = os.path.dirname(os.path.abspath(__file__))298 configs_dir = os.path.dirname(os.path.abspath(__file__))
299 potential_handlers = find_modules(configs_dir)299 potential_handlers = find_modules(configs_dir)
300 for (fname, mod_name) in potential_handlers.items():300 for (_fname, mod_name) in potential_handlers.items():
301 mod_locs, looked_locs = importer.find_module(301 mod_locs, _looked_locs = importer.find_module(
302 mod_name, ['cloudinit.config'], ['schema'])302 mod_name, ['cloudinit.config'], ['schema'])
303 if mod_locs:303 if mod_locs:
304 mod = importer.import_module(mod_locs[0])304 mod = importer.import_module(mod_locs[0])
diff --git a/cloudinit/distros/freebsd.py b/cloudinit/distros/freebsd.py
index 754d3df..03ee091 100644
--- a/cloudinit/distros/freebsd.py
+++ b/cloudinit/distros/freebsd.py
@@ -113,7 +113,7 @@ class Distro(distros.Distro):
113 n = re.search('\d+$', dev)113 n = re.search('\d+$', dev)
114 index = n.group(0)114 index = n.group(0)
115115
116 (out, err) = util.subp(['ifconfig', '-a'])116 (out, _err) = util.subp(['ifconfig', '-a'])
117 ifconfigoutput = [x for x in (out.strip()).splitlines()117 ifconfigoutput = [x for x in (out.strip()).splitlines()
118 if len(x.split()) > 0]118 if len(x.split()) > 0]
119 bsddev = 'NOT_FOUND'119 bsddev = 'NOT_FOUND'
diff --git a/cloudinit/distros/ubuntu.py b/cloudinit/distros/ubuntu.py
index fdc1f62..6815410 100644
--- a/cloudinit/distros/ubuntu.py
+++ b/cloudinit/distros/ubuntu.py
@@ -25,7 +25,7 @@ class Distro(debian.Distro):
25 def preferred_ntp_clients(self):25 def preferred_ntp_clients(self):
26 """The preferred ntp client is dependent on the version."""26 """The preferred ntp client is dependent on the version."""
27 if not self._preferred_ntp_clients:27 if not self._preferred_ntp_clients:
28 (name, version, codename) = util.system_info()['dist']28 (_name, _version, codename) = util.system_info()['dist']
29 # Xenial cloud-init only installed ntp, UbuntuCore has timesyncd.29 # Xenial cloud-init only installed ntp, UbuntuCore has timesyncd.
30 if codename == "xenial" and not util.system_is_snappy():30 if codename == "xenial" and not util.system_is_snappy():
31 self._preferred_ntp_clients = ['ntp']31 self._preferred_ntp_clients = ['ntp']
diff --git a/cloudinit/net/__init__.py b/cloudinit/net/__init__.py
index f69c0ef..8005454 100644
--- a/cloudinit/net/__init__.py
+++ b/cloudinit/net/__init__.py
@@ -295,7 +295,7 @@ def apply_network_config_names(netcfg, strict_present=True, strict_busy=True):
295295
296 def _version_2(netcfg):296 def _version_2(netcfg):
297 renames = []297 renames = []
298 for key, ent in netcfg.get('ethernets', {}).items():298 for ent in netcfg.get('ethernets', {}).values():
299 # only rename if configured to do so299 # only rename if configured to do so
300 name = ent.get('set-name')300 name = ent.get('set-name')
301 if not name:301 if not name:
diff --git a/cloudinit/net/cmdline.py b/cloudinit/net/cmdline.py
index 9e9fe0f..f89a0f7 100755
--- a/cloudinit/net/cmdline.py
+++ b/cloudinit/net/cmdline.py
@@ -65,7 +65,7 @@ def _klibc_to_config_entry(content, mac_addrs=None):
65 iface['mac_address'] = mac_addrs[name]65 iface['mac_address'] = mac_addrs[name]
6666
67 # Handle both IPv4 and IPv6 values67 # Handle both IPv4 and IPv6 values
68 for v, pre in (('ipv4', 'IPV4'), ('ipv6', 'IPV6')):68 for pre in ('IPV4', 'IPV6'):
69 # if no IPV4ADDR or IPV6ADDR, then go on.69 # if no IPV4ADDR or IPV6ADDR, then go on.
70 if pre + "ADDR" not in data:70 if pre + "ADDR" not in data:
71 continue71 continue
diff --git a/cloudinit/net/dhcp.py b/cloudinit/net/dhcp.py
index 087c0c0..12cf509 100644
--- a/cloudinit/net/dhcp.py
+++ b/cloudinit/net/dhcp.py
@@ -216,7 +216,7 @@ def networkd_get_option_from_leases(keyname, leases_d=None):
216 if leases_d is None:216 if leases_d is None:
217 leases_d = NETWORKD_LEASES_DIR217 leases_d = NETWORKD_LEASES_DIR
218 leases = networkd_load_leases(leases_d=leases_d)218 leases = networkd_load_leases(leases_d=leases_d)
219 for ifindex, data in sorted(leases.items()):219 for _ifindex, data in sorted(leases.items()):
220 if data.get(keyname):220 if data.get(keyname):
221 return data[keyname]221 return data[keyname]
222 return None222 return None
diff --git a/cloudinit/net/sysconfig.py b/cloudinit/net/sysconfig.py
index 39d89c4..7a7f509 100644
--- a/cloudinit/net/sysconfig.py
+++ b/cloudinit/net/sysconfig.py
@@ -364,7 +364,7 @@ class Renderer(renderer.Renderer):
364364
365 @classmethod365 @classmethod
366 def _render_subnet_routes(cls, iface_cfg, route_cfg, subnets):366 def _render_subnet_routes(cls, iface_cfg, route_cfg, subnets):
367 for i, subnet in enumerate(subnets, start=len(iface_cfg.children)):367 for _, subnet in enumerate(subnets, start=len(iface_cfg.children)):
368 for route in subnet.get('routes', []):368 for route in subnet.get('routes', []):
369 is_ipv6 = subnet.get('ipv6') or is_ipv6_addr(route['gateway'])369 is_ipv6 = subnet.get('ipv6') or is_ipv6_addr(route['gateway'])
370370
diff --git a/cloudinit/reporting/events.py b/cloudinit/reporting/events.py
index 4f62d2f..e5dfab3 100644
--- a/cloudinit/reporting/events.py
+++ b/cloudinit/reporting/events.py
@@ -192,7 +192,7 @@ class ReportEventStack(object):
192192
193 def _childrens_finish_info(self):193 def _childrens_finish_info(self):
194 for cand_result in (status.FAIL, status.WARN):194 for cand_result in (status.FAIL, status.WARN):
195 for name, (value, msg) in self.children.items():195 for _name, (value, _msg) in self.children.items():
196 if value == cand_result:196 if value == cand_result:
197 return (value, self.message)197 return (value, self.message)
198 return (self.result, self.message)198 return (self.result, self.message)
diff --git a/cloudinit/sources/DataSourceAliYun.py b/cloudinit/sources/DataSourceAliYun.py
index 22279d0..858e082 100644
--- a/cloudinit/sources/DataSourceAliYun.py
+++ b/cloudinit/sources/DataSourceAliYun.py
@@ -45,7 +45,7 @@ def _is_aliyun():
4545
46def parse_public_keys(public_keys):46def parse_public_keys(public_keys):
47 keys = []47 keys = []
48 for key_id, key_body in public_keys.items():48 for _key_id, key_body in public_keys.items():
49 if isinstance(key_body, str):49 if isinstance(key_body, str):
50 keys.append(key_body.strip())50 keys.append(key_body.strip())
51 elif isinstance(key_body, list):51 elif isinstance(key_body, list):
diff --git a/cloudinit/sources/DataSourceAzure.py b/cloudinit/sources/DataSourceAzure.py
index 0ee622e..a71197a 100644
--- a/cloudinit/sources/DataSourceAzure.py
+++ b/cloudinit/sources/DataSourceAzure.py
@@ -107,31 +107,24 @@ def find_dev_from_busdev(camcontrol_out, busdev):
107 return None107 return None
108108
109109
110def get_dev_storvsc_sysctl():110def execute_or_debug(cmd, fail_ret=None):
111 try:111 try:
112 sysctl_out, err = util.subp(['sysctl', 'dev.storvsc'])112 return util.subp(cmd)[0]
113 except util.ProcessExecutionError:113 except util.ProcessExecutionError:
114 LOG.debug("Fail to execute sysctl dev.storvsc")114 LOG.debug("Failed to execute: %s", ' '.join(cmd))
115 sysctl_out = ""115 return fail_ret
116 return sysctl_out116
117
118def get_dev_storvsc_sysctl():
119 return execute_or_debug(["sysctl", "dev.storvsc"], fail_ret="")
117120
118121
119def get_camcontrol_dev_bus():122def get_camcontrol_dev_bus():
120 try:123 return execute_or_debug(['camcontrol', 'devlist', '-b'])
121 camcontrol_b_out, err = util.subp(['camcontrol', 'devlist', '-b'])
122 except util.ProcessExecutionError:
123 LOG.debug("Fail to execute camcontrol devlist -b")
124 return None
125 return camcontrol_b_out
126124
127125
128def get_camcontrol_dev():126def get_camcontrol_dev():
129 try:127 return execute_or_debug(['camcontrol', 'devlist'])
130 camcontrol_out, err = util.subp(['camcontrol', 'devlist'])
131 except util.ProcessExecutionError:
132 LOG.debug("Fail to execute camcontrol devlist")
133 return None
134 return camcontrol_out
135128
136129
137def get_resource_disk_on_freebsd(port_id):130def get_resource_disk_on_freebsd(port_id):
@@ -474,7 +467,7 @@ class DataSourceAzure(sources.DataSource):
474 before we go into our polling loop."""467 before we go into our polling loop."""
475 try:468 try:
476 get_metadata_from_fabric(None, lease['unknown-245'])469 get_metadata_from_fabric(None, lease['unknown-245'])
477 except Exception as exc:470 except Exception:
478 LOG.warning(471 LOG.warning(
479 "Error communicating with Azure fabric; You may experience."472 "Error communicating with Azure fabric; You may experience."
480 "connectivity issues.", exc_info=True)473 "connectivity issues.", exc_info=True)
@@ -492,7 +485,7 @@ class DataSourceAzure(sources.DataSource):
492 jump back into the polling loop in order to retrieve the ovf_env."""485 jump back into the polling loop in order to retrieve the ovf_env."""
493 if not ret:486 if not ret:
494 return False487 return False
495 (md, self.userdata_raw, cfg, files) = ret488 (_md, self.userdata_raw, cfg, _files) = ret
496 path = REPROVISION_MARKER_FILE489 path = REPROVISION_MARKER_FILE
497 if (cfg.get('PreprovisionedVm') is True or490 if (cfg.get('PreprovisionedVm') is True or
498 os.path.isfile(path)):491 os.path.isfile(path)):
@@ -528,7 +521,7 @@ class DataSourceAzure(sources.DataSource):
528 self.ds_cfg['agent_command'])521 self.ds_cfg['agent_command'])
529 try:522 try:
530 fabric_data = metadata_func()523 fabric_data = metadata_func()
531 except Exception as exc:524 except Exception:
532 LOG.warning(525 LOG.warning(
533 "Error communicating with Azure fabric; You may experience."526 "Error communicating with Azure fabric; You may experience."
534 "connectivity issues.", exc_info=True)527 "connectivity issues.", exc_info=True)
diff --git a/cloudinit/sources/DataSourceMAAS.py b/cloudinit/sources/DataSourceMAAS.py
index 6ac8863..aa56add 100644
--- a/cloudinit/sources/DataSourceMAAS.py
+++ b/cloudinit/sources/DataSourceMAAS.py
@@ -204,7 +204,7 @@ def read_maas_seed_url(seed_url, read_file_or_url=None, timeout=None,
204 seed_url = seed_url[:-1]204 seed_url = seed_url[:-1]
205205
206 md = {}206 md = {}
207 for path, dictname, binary, optional in DS_FIELDS:207 for path, _dictname, binary, optional in DS_FIELDS:
208 if version is None:208 if version is None:
209 url = "%s/%s" % (seed_url, path)209 url = "%s/%s" % (seed_url, path)
210 else:210 else:
diff --git a/cloudinit/sources/DataSourceOVF.py b/cloudinit/sources/DataSourceOVF.py
index dc914a7..178ccb0 100644
--- a/cloudinit/sources/DataSourceOVF.py
+++ b/cloudinit/sources/DataSourceOVF.py
@@ -556,7 +556,7 @@ def search_file(dirpath, filename):
556 if not dirpath or not filename:556 if not dirpath or not filename:
557 return None557 return None
558558
559 for root, dirs, files in os.walk(dirpath):559 for root, _dirs, files in os.walk(dirpath):
560 if filename in files:560 if filename in files:
561 return os.path.join(root, filename)561 return os.path.join(root, filename)
562562
diff --git a/cloudinit/sources/DataSourceOpenStack.py b/cloudinit/sources/DataSourceOpenStack.py
index e55a763..fb166ae 100644
--- a/cloudinit/sources/DataSourceOpenStack.py
+++ b/cloudinit/sources/DataSourceOpenStack.py
@@ -86,7 +86,7 @@ class DataSourceOpenStack(openstack.SourceMixin, sources.DataSource):
86 md_urls.append(md_url)86 md_urls.append(md_url)
87 url2base[md_url] = url87 url2base[md_url] = url
8888
89 (max_wait, timeout, retries) = self._get_url_settings()89 (max_wait, timeout, _retries) = self._get_url_settings()
90 start_time = time.time()90 start_time = time.time()
91 avail_url = url_helper.wait_for_url(urls=md_urls, max_wait=max_wait,91 avail_url = url_helper.wait_for_url(urls=md_urls, max_wait=max_wait,
92 timeout=timeout)92 timeout=timeout)
@@ -106,7 +106,7 @@ class DataSourceOpenStack(openstack.SourceMixin, sources.DataSource):
106 except IOError:106 except IOError:
107 return False107 return False
108108
109 (max_wait, timeout, retries) = self._get_url_settings()109 (_max_wait, timeout, retries) = self._get_url_settings()
110110
111 try:111 try:
112 results = util.log_time(LOG.debug,112 results = util.log_time(LOG.debug,
diff --git a/cloudinit/sources/helpers/digitalocean.py b/cloudinit/sources/helpers/digitalocean.py
index 693f8d5..0e7ccca 100644
--- a/cloudinit/sources/helpers/digitalocean.py
+++ b/cloudinit/sources/helpers/digitalocean.py
@@ -41,10 +41,9 @@ def assign_ipv4_link_local(nic=None):
41 "address")41 "address")
4242
43 try:43 try:
44 (result, _err) = util.subp(ip_addr_cmd)44 util.subp(ip_addr_cmd)
45 LOG.debug("assigned ip4LL address '%s' to '%s'", addr, nic)45 LOG.debug("assigned ip4LL address '%s' to '%s'", addr, nic)
4646 util.subp(ip_link_cmd)
47 (result, _err) = util.subp(ip_link_cmd)
48 LOG.debug("brought device '%s' up", nic)47 LOG.debug("brought device '%s' up", nic)
49 except Exception:48 except Exception:
50 util.logexc(LOG, "ip4LL address assignment of '%s' to '%s' failed."49 util.logexc(LOG, "ip4LL address assignment of '%s' to '%s' failed."
@@ -75,7 +74,7 @@ def del_ipv4_link_local(nic=None):
75 ip_addr_cmd = ['ip', 'addr', 'flush', 'dev', nic]74 ip_addr_cmd = ['ip', 'addr', 'flush', 'dev', nic]
7675
77 try:76 try:
78 (result, _err) = util.subp(ip_addr_cmd)77 util.subp(ip_addr_cmd)
79 LOG.debug("removed ip4LL addresses from %s", nic)78 LOG.debug("removed ip4LL addresses from %s", nic)
8079
81 except Exception as e:80 except Exception as e:
diff --git a/cloudinit/sources/helpers/openstack.py b/cloudinit/sources/helpers/openstack.py
index 26f3168..a4cf066 100644
--- a/cloudinit/sources/helpers/openstack.py
+++ b/cloudinit/sources/helpers/openstack.py
@@ -638,7 +638,7 @@ def convert_net_json(network_json=None, known_macs=None):
638 known_macs = net.get_interfaces_by_mac()638 known_macs = net.get_interfaces_by_mac()
639639
640 # go through and fill out the link_id_info with names640 # go through and fill out the link_id_info with names
641 for link_id, info in link_id_info.items():641 for _link_id, info in link_id_info.items():
642 if info.get('name'):642 if info.get('name'):
643 continue643 continue
644 if info.get('mac') in known_macs:644 if info.get('mac') in known_macs:
diff --git a/cloudinit/sources/helpers/vmware/imc/config_nic.py b/cloudinit/sources/helpers/vmware/imc/config_nic.py
index 2d8900e..3ef8c62 100644
--- a/cloudinit/sources/helpers/vmware/imc/config_nic.py
+++ b/cloudinit/sources/helpers/vmware/imc/config_nic.py
@@ -73,7 +73,7 @@ class NicConfigurator(object):
73 The mac address(es) are in the lower case73 The mac address(es) are in the lower case
74 """74 """
75 cmd = ['ip', 'addr', 'show']75 cmd = ['ip', 'addr', 'show']
76 (output, err) = util.subp(cmd)76 output, _err = util.subp(cmd)
77 sections = re.split(r'\n\d+: ', '\n' + output)[1:]77 sections = re.split(r'\n\d+: ', '\n' + output)[1:]
7878
79 macPat = r'link/ether (([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2}))'79 macPat = r'link/ether (([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2}))'
diff --git a/cloudinit/sources/helpers/vmware/imc/config_passwd.py b/cloudinit/sources/helpers/vmware/imc/config_passwd.py
index 75cfbaa..8c91fa4 100644
--- a/cloudinit/sources/helpers/vmware/imc/config_passwd.py
+++ b/cloudinit/sources/helpers/vmware/imc/config_passwd.py
@@ -56,10 +56,10 @@ class PasswordConfigurator(object):
56 LOG.info('Expiring password.')56 LOG.info('Expiring password.')
57 for user in uidUserList:57 for user in uidUserList:
58 try:58 try:
59 out, err = util.subp(['passwd', '--expire', user])59 util.subp(['passwd', '--expire', user])
60 except util.ProcessExecutionError as e:60 except util.ProcessExecutionError as e:
61 if os.path.exists('/usr/bin/chage'):61 if os.path.exists('/usr/bin/chage'):
62 out, e = util.subp(['chage', '-d', '0', user])62 util.subp(['chage', '-d', '0', user])
63 else:63 else:
64 LOG.warning('Failed to expire password for %s with error: '64 LOG.warning('Failed to expire password for %s with error: '
65 '%s', user, e)65 '%s', user, e)
diff --git a/cloudinit/sources/helpers/vmware/imc/guestcust_util.py b/cloudinit/sources/helpers/vmware/imc/guestcust_util.py
index 4407525..a590f32 100644
--- a/cloudinit/sources/helpers/vmware/imc/guestcust_util.py
+++ b/cloudinit/sources/helpers/vmware/imc/guestcust_util.py
@@ -91,7 +91,7 @@ def enable_nics(nics):
9191
92 for attempt in range(0, enableNicsWaitRetries):92 for attempt in range(0, enableNicsWaitRetries):
93 logger.debug("Trying to connect interfaces, attempt %d", attempt)93 logger.debug("Trying to connect interfaces, attempt %d", attempt)
94 (out, err) = set_customization_status(94 (out, _err) = set_customization_status(
95 GuestCustStateEnum.GUESTCUST_STATE_RUNNING,95 GuestCustStateEnum.GUESTCUST_STATE_RUNNING,
96 GuestCustEventEnum.GUESTCUST_EVENT_ENABLE_NICS,96 GuestCustEventEnum.GUESTCUST_EVENT_ENABLE_NICS,
97 nics)97 nics)
@@ -104,7 +104,7 @@ def enable_nics(nics):
104 return104 return
105105
106 for count in range(0, enableNicsWaitCount):106 for count in range(0, enableNicsWaitCount):
107 (out, err) = set_customization_status(107 (out, _err) = set_customization_status(
108 GuestCustStateEnum.GUESTCUST_STATE_RUNNING,108 GuestCustStateEnum.GUESTCUST_STATE_RUNNING,
109 GuestCustEventEnum.GUESTCUST_EVENT_QUERY_NICS,109 GuestCustEventEnum.GUESTCUST_EVENT_QUERY_NICS,
110 nics)110 nics)
diff --git a/cloudinit/sources/tests/test_init.py b/cloudinit/sources/tests/test_init.py
index e7fda22..452e921 100644
--- a/cloudinit/sources/tests/test_init.py
+++ b/cloudinit/sources/tests/test_init.py
@@ -278,7 +278,7 @@ class TestDataSource(CiTestCase):
278 base_args = get_args(DataSource.get_hostname) # pylint: disable=W1505278 base_args = get_args(DataSource.get_hostname) # pylint: disable=W1505
279 # Import all DataSource subclasses so we can inspect them.279 # Import all DataSource subclasses so we can inspect them.
280 modules = util.find_modules(os.path.dirname(os.path.dirname(__file__)))280 modules = util.find_modules(os.path.dirname(os.path.dirname(__file__)))
281 for loc, name in modules.items():281 for _loc, name in modules.items():
282 mod_locs, _ = importer.find_module(name, ['cloudinit.sources'], [])282 mod_locs, _ = importer.find_module(name, ['cloudinit.sources'], [])
283 if mod_locs:283 if mod_locs:
284 importer.import_module(mod_locs[0])284 importer.import_module(mod_locs[0])
diff --git a/cloudinit/templater.py b/cloudinit/templater.py
index 9a087e1..7e7acb8 100644
--- a/cloudinit/templater.py
+++ b/cloudinit/templater.py
@@ -147,7 +147,7 @@ def render_string(content, params):
147 Warning: py2 str with non-ascii chars will cause UnicodeDecodeError."""147 Warning: py2 str with non-ascii chars will cause UnicodeDecodeError."""
148 if not params:148 if not params:
149 params = {}149 params = {}
150 template_type, renderer, content = detect_template(content)150 _template_type, renderer, content = detect_template(content)
151 return renderer(content, params)151 return renderer(content, params)
152152
153# vi: ts=4 expandtab153# vi: ts=4 expandtab
diff --git a/cloudinit/tests/helpers.py b/cloudinit/tests/helpers.py
index 999b1d7..996888e 100644
--- a/cloudinit/tests/helpers.py
+++ b/cloudinit/tests/helpers.py
@@ -358,7 +358,7 @@ def dir2dict(startdir, prefix=None):
358 flist = {}358 flist = {}
359 if prefix is None:359 if prefix is None:
360 prefix = startdir360 prefix = startdir
361 for root, dirs, files in os.walk(startdir):361 for root, _dirs, files in os.walk(startdir):
362 for fname in files:362 for fname in files:
363 fpath = os.path.join(root, fname)363 fpath = os.path.join(root, fname)
364 key = fpath[len(prefix):]364 key = fpath[len(prefix):]
diff --git a/cloudinit/tests/test_util.py b/cloudinit/tests/test_util.py
index 3f37dbb..76eed07 100644
--- a/cloudinit/tests/test_util.py
+++ b/cloudinit/tests/test_util.py
@@ -135,7 +135,7 @@ class TestGetHostnameFqdn(CiTestCase):
135 def test_get_hostname_fqdn_from_passes_metadata_only_to_cloud(self):135 def test_get_hostname_fqdn_from_passes_metadata_only_to_cloud(self):
136 """Calls to cloud.get_hostname pass the metadata_only parameter."""136 """Calls to cloud.get_hostname pass the metadata_only parameter."""
137 mycloud = FakeCloud('cloudhost', 'cloudhost.mycloud.com')137 mycloud = FakeCloud('cloudhost', 'cloudhost.mycloud.com')
138 hostname, fqdn = util.get_hostname_fqdn(138 _hn, _fqdn = util.get_hostname_fqdn(
139 cfg={}, cloud=mycloud, metadata_only=True)139 cfg={}, cloud=mycloud, metadata_only=True)
140 self.assertEqual(140 self.assertEqual(
141 [{'fqdn': True, 'metadata_only': True},141 [{'fqdn': True, 'metadata_only': True},
diff --git a/cloudinit/url_helper.py b/cloudinit/url_helper.py
index 03a573a..1de07b1 100644
--- a/cloudinit/url_helper.py
+++ b/cloudinit/url_helper.py
@@ -519,7 +519,7 @@ def oauth_headers(url, consumer_key, token_key, token_secret, consumer_secret,
519 resource_owner_secret=token_secret,519 resource_owner_secret=token_secret,
520 signature_method=oauth1.SIGNATURE_PLAINTEXT,520 signature_method=oauth1.SIGNATURE_PLAINTEXT,
521 timestamp=timestamp)521 timestamp=timestamp)
522 uri, signed_headers, body = client.sign(url)522 _uri, signed_headers, _body = client.sign(url)
523 return signed_headers523 return signed_headers
524524
525# vi: ts=4 expandtab525# vi: ts=4 expandtab
diff --git a/cloudinit/util.py b/cloudinit/util.py
index acdc0d8..d8b5e09 100644
--- a/cloudinit/util.py
+++ b/cloudinit/util.py
@@ -2214,7 +2214,7 @@ def parse_mtab(path):
2214def find_freebsd_part(label_part):2214def find_freebsd_part(label_part):
2215 if label_part.startswith("/dev/label/"):2215 if label_part.startswith("/dev/label/"):
2216 target_label = label_part[5:]2216 target_label = label_part[5:]
2217 (label_part, err) = subp(['glabel', 'status', '-s'])2217 (label_part, _err) = subp(['glabel', 'status', '-s'])
2218 for labels in label_part.split("\n"):2218 for labels in label_part.split("\n"):
2219 items = labels.split()2219 items = labels.split()
2220 if len(items) > 0 and items[0].startswith(target_label):2220 if len(items) > 0 and items[0].startswith(target_label):
diff --git a/tests/cloud_tests/bddeb.py b/tests/cloud_tests/bddeb.py
index b9cfcfa..f04d0cd 100644
--- a/tests/cloud_tests/bddeb.py
+++ b/tests/cloud_tests/bddeb.py
@@ -113,7 +113,7 @@ def bddeb(args):
113 @return_value: fail count113 @return_value: fail count
114 """114 """
115 LOG.info('preparing to build cloud-init deb')115 LOG.info('preparing to build cloud-init deb')
116 (res, failed) = run_stage('build deb', [partial(setup_build, args)])116 _res, failed = run_stage('build deb', [partial(setup_build, args)])
117 return failed117 return failed
118118
119# vi: ts=4 expandtab119# vi: ts=4 expandtab
diff --git a/tests/cloud_tests/collect.py b/tests/cloud_tests/collect.py
index d4f9135..1ba7285 100644
--- a/tests/cloud_tests/collect.py
+++ b/tests/cloud_tests/collect.py
@@ -25,7 +25,8 @@ def collect_script(instance, base_dir, script, script_name):
25 script.encode(), rcs=False,25 script.encode(), rcs=False,
26 description='collect: {}'.format(script_name))26 description='collect: {}'.format(script_name))
27 if err:27 if err:
28 LOG.debug("collect script %s had stderr: %s", script_name, err)28 LOG.debug("collect script %s exited '%s' and had stderr: %s",
29 script_name, err, exit)
29 if not isinstance(out, bytes):30 if not isinstance(out, bytes):
30 raise util.PlatformError(31 raise util.PlatformError(
31 "Collection of '%s' returned type %s, expected bytes: %s" %32 "Collection of '%s' returned type %s, expected bytes: %s" %
diff --git a/tests/cloud_tests/platforms/instances.py b/tests/cloud_tests/platforms/instances.py
index 3bad021..cc439d2 100644
--- a/tests/cloud_tests/platforms/instances.py
+++ b/tests/cloud_tests/platforms/instances.py
@@ -108,7 +108,7 @@ class Instance(TargetBase):
108 return client108 return client
109 except (ConnectionRefusedError, AuthenticationException,109 except (ConnectionRefusedError, AuthenticationException,
110 BadHostKeyException, ConnectionResetError, SSHException,110 BadHostKeyException, ConnectionResetError, SSHException,
111 OSError) as e:111 OSError):
112 retries -= 1112 retries -= 1
113 time.sleep(10)113 time.sleep(10)
114114
diff --git a/tests/cloud_tests/platforms/lxd/instance.py b/tests/cloud_tests/platforms/lxd/instance.py
index 0d957bc..1c17c78 100644
--- a/tests/cloud_tests/platforms/lxd/instance.py
+++ b/tests/cloud_tests/platforms/lxd/instance.py
@@ -152,9 +152,8 @@ class LXDInstance(Instance):
152 return fp.read()152 return fp.read()
153153
154 try:154 try:
155 stdout, stderr = subp(155 return subp(['lxc', 'console', '--show-log', self.name],
156 ['lxc', 'console', '--show-log', self.name], decode=False)156 decode=False)[0]
157 return stdout
158 except ProcessExecutionError as e:157 except ProcessExecutionError as e:
159 raise PlatformError(158 raise PlatformError(
160 "console log",159 "console log",
@@ -214,11 +213,10 @@ def _has_proper_console_support():
214 reason = "LXD Driver version not 3.x+ (%s)" % dver213 reason = "LXD Driver version not 3.x+ (%s)" % dver
215 else:214 else:
216 try:215 try:
217 stdout, stderr = subp(['lxc', 'console', '--help'],216 stdout = subp(['lxc', 'console', '--help'], decode=False)[0]
218 decode=False)
219 if not (b'console' in stdout and b'log' in stdout):217 if not (b'console' in stdout and b'log' in stdout):
220 reason = "no '--log' in lxc console --help"218 reason = "no '--log' in lxc console --help"
221 except ProcessExecutionError as e:219 except ProcessExecutionError:
222 reason = "no 'console' command in lxc client"220 reason = "no 'console' command in lxc client"
223221
224 if reason:222 if reason:
diff --git a/tests/cloud_tests/setup_image.py b/tests/cloud_tests/setup_image.py
index 6d24211..4e19570 100644
--- a/tests/cloud_tests/setup_image.py
+++ b/tests/cloud_tests/setup_image.py
@@ -25,10 +25,9 @@ def installed_package_version(image, package, ensure_installed=True):
25 else:25 else:
26 raise NotImplementedError26 raise NotImplementedError
2727
28 msg = 'query version for package: {}'.format(package)28 return image.execute(
29 (out, err, exit) = image.execute(29 cmd, description='query version for package: {}'.format(package),
30 cmd, description=msg, rcs=(0,) if ensure_installed else range(0, 256))30 rcs=(0,) if ensure_installed else range(0, 256))[0].strip()
31 return out.strip()
3231
3332
34def install_deb(args, image):33def install_deb(args, image):
@@ -54,7 +53,7 @@ def install_deb(args, image):
54 remote_path], description=msg)53 remote_path], description=msg)
55 # check installed deb version matches package54 # check installed deb version matches package
56 fmt = ['-W', "--showformat=${Version}"]55 fmt = ['-W', "--showformat=${Version}"]
57 (out, err, exit) = image.execute(['dpkg-deb'] + fmt + [remote_path])56 out = image.execute(['dpkg-deb'] + fmt + [remote_path])[0]
58 expected_version = out.strip()57 expected_version = out.strip()
59 found_version = installed_package_version(image, 'cloud-init')58 found_version = installed_package_version(image, 'cloud-init')
60 if expected_version != found_version:59 if expected_version != found_version:
@@ -85,7 +84,7 @@ def install_rpm(args, image):
85 image.execute(['rpm', '-U', remote_path], description=msg)84 image.execute(['rpm', '-U', remote_path], description=msg)
8685
87 fmt = ['--queryformat', '"%{VERSION}"']86 fmt = ['--queryformat', '"%{VERSION}"']
88 (out, err, exit) = image.execute(['rpm', '-q'] + fmt + [remote_path])87 (out, _err, _exit) = image.execute(['rpm', '-q'] + fmt + [remote_path])
89 expected_version = out.strip()88 expected_version = out.strip()
90 found_version = installed_package_version(image, 'cloud-init')89 found_version = installed_package_version(image, 'cloud-init')
91 if expected_version != found_version:90 if expected_version != found_version:
diff --git a/tests/cloud_tests/testcases/base.py b/tests/cloud_tests/testcases/base.py
index 7598d46..e3dcab3 100644
--- a/tests/cloud_tests/testcases/base.py
+++ b/tests/cloud_tests/testcases/base.py
@@ -159,7 +159,7 @@ class CloudTestCase(unittest.TestCase):
159 expected_net_keys = [159 expected_net_keys = [
160 'public-ipv4s', 'ipv4-associations', 'local-hostname',160 'public-ipv4s', 'ipv4-associations', 'local-hostname',
161 'public-hostname']161 'public-hostname']
162 for mac, mac_data in macs.items():162 for mac_data in macs.values():
163 for key in expected_net_keys:163 for key in expected_net_keys:
164 self.assertIn(key, mac_data)164 self.assertIn(key, mac_data)
165 self.assertIsNotNone(165 self.assertIsNotNone(
diff --git a/tests/cloud_tests/testcases/examples/including_user_groups.py b/tests/cloud_tests/testcases/examples/including_user_groups.py
index 93b7a82..4067348 100644
--- a/tests/cloud_tests/testcases/examples/including_user_groups.py
+++ b/tests/cloud_tests/testcases/examples/including_user_groups.py
@@ -42,7 +42,7 @@ class TestUserGroups(base.CloudTestCase):
4242
43 def test_user_root_in_secret(self):43 def test_user_root_in_secret(self):
44 """Test root user is in 'secret' group."""44 """Test root user is in 'secret' group."""
45 user, _, groups = self.get_data_file('root_groups').partition(":")45 _user, _, groups = self.get_data_file('root_groups').partition(":")
46 self.assertIn("secret", groups.split(),46 self.assertIn("secret", groups.split(),
47 msg="User root is not in group 'secret'")47 msg="User root is not in group 'secret'")
4848
diff --git a/tests/cloud_tests/testcases/modules/user_groups.py b/tests/cloud_tests/testcases/modules/user_groups.py
index 93b7a82..4067348 100644
--- a/tests/cloud_tests/testcases/modules/user_groups.py
+++ b/tests/cloud_tests/testcases/modules/user_groups.py
@@ -42,7 +42,7 @@ class TestUserGroups(base.CloudTestCase):
4242
43 def test_user_root_in_secret(self):43 def test_user_root_in_secret(self):
44 """Test root user is in 'secret' group."""44 """Test root user is in 'secret' group."""
45 user, _, groups = self.get_data_file('root_groups').partition(":")45 _user, _, groups = self.get_data_file('root_groups').partition(":")
46 self.assertIn("secret", groups.split(),46 self.assertIn("secret", groups.split(),
47 msg="User root is not in group 'secret'")47 msg="User root is not in group 'secret'")
4848
diff --git a/tests/cloud_tests/util.py b/tests/cloud_tests/util.py
index 3dd4996..06f7d86 100644
--- a/tests/cloud_tests/util.py
+++ b/tests/cloud_tests/util.py
@@ -358,7 +358,7 @@ class TargetBase(object):
358 # when sh is invoked with '-c', then the first argument is "$0"358 # when sh is invoked with '-c', then the first argument is "$0"
359 # which is commonly understood as the "program name".359 # which is commonly understood as the "program name".
360 # 'read_data' is the program name, and 'remote_path' is '$1'360 # 'read_data' is the program name, and 'remote_path' is '$1'
361 stdout, stderr, rc = self._execute(361 stdout, _stderr, rc = self._execute(
362 ["sh", "-c", 'exec cat "$1"', 'read_data', remote_path])362 ["sh", "-c", 'exec cat "$1"', 'read_data', remote_path])
363 if rc != 0:363 if rc != 0:
364 raise RuntimeError("Failed to read file '%s'" % remote_path)364 raise RuntimeError("Failed to read file '%s'" % remote_path)
diff --git a/tests/unittests/test__init__.py b/tests/unittests/test__init__.py
index 25878d7..f1ab02e 100644
--- a/tests/unittests/test__init__.py
+++ b/tests/unittests/test__init__.py
@@ -214,7 +214,7 @@ class TestCmdlineUrl(CiTestCase):
214 def test_no_key_found(self, m_read):214 def test_no_key_found(self, m_read):
215 cmdline = "ro mykey=http://example.com/foo root=foo"215 cmdline = "ro mykey=http://example.com/foo root=foo"
216 fpath = self.tmp_path("ccpath")216 fpath = self.tmp_path("ccpath")
217 lvl, msg = main.attempt_cmdline_url(217 lvl, _msg = main.attempt_cmdline_url(
218 fpath, network=True, cmdline=cmdline)218 fpath, network=True, cmdline=cmdline)
219219
220 m_read.assert_not_called()220 m_read.assert_not_called()
diff --git a/tests/unittests/test_datasource/test_azure.py b/tests/unittests/test_datasource/test_azure.py
index 3e8b791..88fe76c 100644
--- a/tests/unittests/test_datasource/test_azure.py
+++ b/tests/unittests/test_datasource/test_azure.py
@@ -214,7 +214,7 @@ scbus-1 on xpt0 bus 0
214 self.assertIn(tag, x)214 self.assertIn(tag, x)
215215
216 def tags_equal(x, y):216 def tags_equal(x, y):
217 for x_tag, x_val in x.items():217 for x_val in x.values():
218 y_val = y.get(x_val.tag)218 y_val = y.get(x_val.tag)
219 self.assertEqual(x_val.text, y_val.text)219 self.assertEqual(x_val.text, y_val.text)
220220
@@ -1216,7 +1216,7 @@ class TestAzureDataSourcePreprovisioning(CiTestCase):
1216 fake_resp.return_value = mock.MagicMock(status_code=200, text=content,1216 fake_resp.return_value = mock.MagicMock(status_code=200, text=content,
1217 content=content)1217 content=content)
1218 dsa = dsaz.DataSourceAzure({}, distro=None, paths=self.paths)1218 dsa = dsaz.DataSourceAzure({}, distro=None, paths=self.paths)
1219 md, ud, cfg, d = dsa._reprovision()1219 md, _ud, cfg, _d = dsa._reprovision()
1220 self.assertEqual(md['local-hostname'], hostname)1220 self.assertEqual(md['local-hostname'], hostname)
1221 self.assertEqual(cfg['system_info']['default_user']['name'], username)1221 self.assertEqual(cfg['system_info']['default_user']['name'], username)
1222 self.assertEqual(fake_resp.call_args_list,1222 self.assertEqual(fake_resp.call_args_list,
diff --git a/tests/unittests/test_datasource/test_maas.py b/tests/unittests/test_datasource/test_maas.py
index 6e4031c..c84d067 100644
--- a/tests/unittests/test_datasource/test_maas.py
+++ b/tests/unittests/test_datasource/test_maas.py
@@ -53,7 +53,7 @@ class TestMAASDataSource(CiTestCase):
53 my_d = os.path.join(self.tmp, "valid_extra")53 my_d = os.path.join(self.tmp, "valid_extra")
54 populate_dir(my_d, data)54 populate_dir(my_d, data)
5555
56 ud, md, vd = DataSourceMAAS.read_maas_seed_dir(my_d)56 ud, md, _vd = DataSourceMAAS.read_maas_seed_dir(my_d)
5757
58 self.assertEqual(userdata, ud)58 self.assertEqual(userdata, ud)
59 for key in ('instance-id', 'local-hostname'):59 for key in ('instance-id', 'local-hostname'):
@@ -149,7 +149,7 @@ class TestMAASDataSource(CiTestCase):
149 'meta-data/local-hostname': 'test-hostname',149 'meta-data/local-hostname': 'test-hostname',
150 'meta-data/vendor-data': yaml.safe_dump(expected_vd).encode(),150 'meta-data/vendor-data': yaml.safe_dump(expected_vd).encode(),
151 }151 }
152 ud, md, vd = self.mock_read_maas_seed_url(152 _ud, md, vd = self.mock_read_maas_seed_url(
153 valid, "http://example.com/foo")153 valid, "http://example.com/foo")
154154
155 self.assertEqual(valid['meta-data/instance-id'], md['instance-id'])155 self.assertEqual(valid['meta-data/instance-id'], md['instance-id'])
diff --git a/tests/unittests/test_datasource/test_nocloud.py b/tests/unittests/test_datasource/test_nocloud.py
index 70d50de..cdbd1e1 100644
--- a/tests/unittests/test_datasource/test_nocloud.py
+++ b/tests/unittests/test_datasource/test_nocloud.py
@@ -51,9 +51,6 @@ class TestNoCloudDataSource(CiTestCase):
51 class PsuedoException(Exception):51 class PsuedoException(Exception):
52 pass52 pass
5353
54 def my_find_devs_with(*args, **kwargs):
55 raise PsuedoException
56
57 self.mocks.enter_context(54 self.mocks.enter_context(
58 mock.patch.object(util, 'find_devs_with',55 mock.patch.object(util, 'find_devs_with',
59 side_effect=PsuedoException))56 side_effect=PsuedoException))
diff --git a/tests/unittests/test_handler/test_handler_apt_source_v3.py b/tests/unittests/test_handler/test_handler_apt_source_v3.py
index 7bb1b7c..e486862 100644
--- a/tests/unittests/test_handler/test_handler_apt_source_v3.py
+++ b/tests/unittests/test_handler/test_handler_apt_source_v3.py
@@ -528,7 +528,7 @@ class TestAptSourceConfig(t_help.FilesystemMockingTestCase):
528528
529 expected = sorted([npre + suff for opre, npre, suff in files])529 expected = sorted([npre + suff for opre, npre, suff in files])
530 # create files530 # create files
531 for (opre, npre, suff) in files:531 for (opre, _npre, suff) in files:
532 fpath = os.path.join(apt_lists_d, opre + suff)532 fpath = os.path.join(apt_lists_d, opre + suff)
533 util.write_file(fpath, content=fpath)533 util.write_file(fpath, content=fpath)
534534
diff --git a/tests/unittests/test_handler/test_handler_ntp.py b/tests/unittests/test_handler/test_handler_ntp.py
index 02676aa..17c5355 100644
--- a/tests/unittests/test_handler/test_handler_ntp.py
+++ b/tests/unittests/test_handler/test_handler_ntp.py
@@ -76,7 +76,7 @@ class TestNtp(FilesystemMockingTestCase):
76 template = TIMESYNCD_TEMPLATE76 template = TIMESYNCD_TEMPLATE
77 else:77 else:
78 template = NTP_TEMPLATE78 template = NTP_TEMPLATE
79 (confpath, template_fn) = self._generate_template(template=template)79 (confpath, _template_fn) = self._generate_template(template=template)
80 ntpconfig = copy.deepcopy(dcfg[client])80 ntpconfig = copy.deepcopy(dcfg[client])
81 ntpconfig['confpath'] = confpath81 ntpconfig['confpath'] = confpath
82 ntpconfig['template_name'] = os.path.basename(confpath)82 ntpconfig['template_name'] = os.path.basename(confpath)
diff --git a/tests/unittests/test_templating.py b/tests/unittests/test_templating.py
index 1080e13..20c87ef 100644
--- a/tests/unittests/test_templating.py
+++ b/tests/unittests/test_templating.py
@@ -50,12 +50,12 @@ class TestTemplates(test_helpers.CiTestCase):
50 def test_detection(self):50 def test_detection(self):
51 blob = "## template:cheetah"51 blob = "## template:cheetah"
5252
53 (template_type, renderer, contents) = templater.detect_template(blob)53 (template_type, _renderer, contents) = templater.detect_template(blob)
54 self.assertIn("cheetah", template_type)54 self.assertIn("cheetah", template_type)
55 self.assertEqual("", contents.strip())55 self.assertEqual("", contents.strip())
5656
57 blob = "blahblah $blah"57 blob = "blahblah $blah"
58 (template_type, renderer, contents) = templater.detect_template(blob)58 (template_type, _renderer, _contents) = templater.detect_template(blob)
59 self.assertIn("cheetah", template_type)59 self.assertIn("cheetah", template_type)
60 self.assertEqual(blob, contents)60 self.assertEqual(blob, contents)
6161
diff --git a/tests/unittests/test_util.py b/tests/unittests/test_util.py
index 5010190..5637c4e 100644
--- a/tests/unittests/test_util.py
+++ b/tests/unittests/test_util.py
@@ -772,11 +772,11 @@ class TestSubp(helpers.CiTestCase):
772772
773 def test_subp_reads_env(self):773 def test_subp_reads_env(self):
774 with mock.patch.dict("os.environ", values={'FOO': 'BAR'}):774 with mock.patch.dict("os.environ", values={'FOO': 'BAR'}):
775 out, err = util.subp(self.printenv + ['FOO'], capture=True)775 out, _err = util.subp(self.printenv + ['FOO'], capture=True)
776 self.assertEqual('FOO=BAR', out.splitlines()[0])776 self.assertEqual('FOO=BAR', out.splitlines()[0])
777777
778 def test_subp_env_and_update_env(self):778 def test_subp_env_and_update_env(self):
779 out, err = util.subp(779 out, _err = util.subp(
780 self.printenv + ['FOO', 'HOME', 'K1', 'K2'], capture=True,780 self.printenv + ['FOO', 'HOME', 'K1', 'K2'], capture=True,
781 env={'FOO': 'BAR'},781 env={'FOO': 'BAR'},
782 update_env={'HOME': '/myhome', 'K2': 'V2'})782 update_env={'HOME': '/myhome', 'K2': 'V2'})
@@ -786,7 +786,7 @@ class TestSubp(helpers.CiTestCase):
786 def test_subp_update_env(self):786 def test_subp_update_env(self):
787 extra = {'FOO': 'BAR', 'HOME': '/root', 'K1': 'V1'}787 extra = {'FOO': 'BAR', 'HOME': '/root', 'K1': 'V1'}
788 with mock.patch.dict("os.environ", values=extra):788 with mock.patch.dict("os.environ", values=extra):
789 out, err = util.subp(789 out, _err = util.subp(
790 self.printenv + ['FOO', 'HOME', 'K1', 'K2'], capture=True,790 self.printenv + ['FOO', 'HOME', 'K1', 'K2'], capture=True,
791 update_env={'HOME': '/myhome', 'K2': 'V2'})791 update_env={'HOME': '/myhome', 'K2': 'V2'})
792792

Subscribers

People subscribed via source and target branches