URL: https://github.com/freeipa/freeipa/pull/144 Author: mbasti-rh Title: #144: Pylint: remove unused values - the last part Action: opened
PR body: """ """ To pull the PR as Git branch: git remote add ghfreeipa https://github.com/freeipa/freeipa git fetch ghfreeipa pull/144/head:pr144 git checkout pr144
From 47787bfd63b81f8d8850930aa4ee10bac87bda93 Mon Sep 17 00:00:00 2001 From: Martin Basti <mba...@redhat.com> Date: Thu, 6 Oct 2016 20:28:59 +0200 Subject: [PATCH 1/2] Pylint: remove unused variables in tests --- ipatests/pytest_plugins/integration.py | 6 ++---- ipatests/test_install/test_updates.py | 14 ++++++-------- ipatests/test_integration/tasks.py | 6 +----- ipatests/test_ipalib/test_frontend.py | 26 ++++++++++++-------------- ipatests/test_ipalib/test_parameters.py | 14 ++++++-------- ipatests/test_ipalib/test_rpc.py | 18 ++++++++---------- ipatests/test_ipaserver/test_rpcserver.py | 6 ++---- ipatests/test_ipaserver/test_serverroles.py | 9 ++++----- 8 files changed, 41 insertions(+), 58 deletions(-) diff --git a/ipatests/pytest_plugins/integration.py b/ipatests/pytest_plugins/integration.py index ab10548..f946a07 100644 --- a/ipatests/pytest_plugins/integration.py +++ b/ipatests/pytest_plugins/integration.py @@ -34,8 +34,6 @@ from ipatests.test_integration.config import Config from ipatests.test_integration.env_config import get_global_config -# pylint: disable=unused-variable - log = log_mgr.get_logger(__name__) @@ -117,7 +115,7 @@ def collect_logs(name, logs_dict, logfile_dir=None, beakerlib_plugin=None): # $HOSTNAME-$FILENAME (with '/' replaced by '-') beakerlib_plugin.run_beakerlib_command(['pushd', topdirname]) try: - for dirpath, dirnames, filenames in os.walk(topdirname): + for dirpath, _dirnames, filenames in os.walk(topdirname): for filename in filenames: fullname = os.path.relpath( os.path.join(dirpath, filename), topdirname) @@ -171,7 +169,7 @@ def mh(request, class_integration_logs): {role: 1 for role in cls.required_extra_roles}) domain_descriptions = [domain_description] - for i in range(cls.num_ad_domains): + for _i in range(cls.num_ad_domains): domain_descriptions.append({ 'type': 'AD', 'hosts': {'ad': 1, 'ad_subdomain': 1}, diff --git a/ipatests/test_install/test_updates.py b/ipatests/test_install/test_updates.py index e6761ad..4053d35 100644 --- a/ipatests/test_install/test_updates.py +++ b/ipatests/test_install/test_updates.py @@ -34,8 +34,6 @@ from ipaplatform.paths import paths from ipapython.dn import DN -# pylint: disable=unused-variable - """ The updater works through files only so this is just a thin-wrapper controlling which file we test at any given point. @@ -93,11 +91,11 @@ def test_0_reset(self): self.assertTrue(modified) with self.assertRaises(errors.NotFound): - entries = self.ld.get_entries( + self.ld.get_entries( self.container_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*']) with self.assertRaises(errors.NotFound): - entries = self.ld.get_entries( + self.ld.get_entries( self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*']) def test_1_add(self): @@ -233,11 +231,11 @@ def test_7_cleanup(self): self.assertTrue(modified) with self.assertRaises(errors.NotFound): - entries = self.ld.get_entries( + self.ld.get_entries( self.container_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*']) with self.assertRaises(errors.NotFound): - entries = self.ld.get_entries( + self.ld.get_entries( self.user_dn, self.ld.SCOPE_BASE, 'objectclass=*', ['*']) def test_8_badsyntax(self): @@ -245,7 +243,7 @@ def test_8_badsyntax(self): Test the updater with an unknown keyword (test_8_badsyntax) """ with self.assertRaises(BadSyntax): - modified = self.updater.update( + self.updater.update( [os.path.join(self.testdir, "8_badsyntax.update")]) def test_9_badsyntax(self): @@ -253,5 +251,5 @@ def test_9_badsyntax(self): Test the updater with an incomplete line (test_9_badsyntax) """ with self.assertRaises(BadSyntax): - modified = self.updater.update( + self.updater.update( [os.path.join(self.testdir, "9_badsyntax.update")]) diff --git a/ipatests/test_integration/tasks.py b/ipatests/test_integration/tasks.py index 6c26626..7c96227 100644 --- a/ipatests/test_integration/tasks.py +++ b/ipatests/test_integration/tasks.py @@ -44,8 +44,6 @@ from ipalib.constants import DOMAIN_SUFFIX_NAME from ipalib.constants import DOMAIN_LEVEL_0 -# pylint: disable=unused-variable - log = log_mgr.get_logger(__name__) @@ -156,7 +154,6 @@ def backup_file(host, filename): host.run_command('echo %s >> %s' % ( ipautil.shell_quote(filename), ipautil.shell_quote(rmname))) - contents = host.get_file_contents(rmname) host.transport.mkdir_recursive(os.path.dirname(rmname)) return False @@ -980,7 +977,7 @@ def double_circle_topo(master, replicas, site_size=6): yield a, b # create agreement to one server in two next sites - for (c, d, _ignore) in [sites[(i+n) % num_sites] for n in [1, 2]]: + for c, _d, _ignore in [sites[(i+n) % num_sites] for n in [1, 2]]: yield b, c if site_size > 2: @@ -1023,7 +1020,6 @@ def install_clients(servers, clients): def _entries_to_ldif(entries): """Format LDAP entries as LDIF""" - lines = [] io = StringIO() writer = LDIFWriter(io) for entry in entries: diff --git a/ipatests/test_ipalib/test_frontend.py b/ipatests/test_ipalib/test_frontend.py index f160b7f..7413408 100644 --- a/ipatests/test_ipalib/test_frontend.py +++ b/ipatests/test_ipalib/test_frontend.py @@ -36,8 +36,6 @@ from ipalib.parameters import Str from ipapython.version import API_VERSION -# pylint: disable=unused-variable - if six.PY3: unicode = str @@ -459,7 +457,7 @@ def run(self, *args, **options): kw = dict(option0=u'some value') - (api, home) = create_test_api() + api, _home = create_test_api() api.finalize() o = my_cmd(api) o.finalize() @@ -583,7 +581,7 @@ def run(self, *args, **kw): args = ('one', 'two') kw = dict(three=('three1', 'three2'), four='four') - (api, home) = create_test_api() + api, _home = create_test_api() api.finalize() o = my_cmd(api) o.finalize() @@ -622,7 +620,7 @@ def forward(self, *args, **kw): kw = dict(how_are='you', on_this='fine day?', version=API_VERSION) # Test in server context: - (api, home) = create_test_api(in_server=True) + api, _home = create_test_api(in_server=True) api.finalize() o = my_cmd(api) if six.PY2: @@ -633,7 +631,7 @@ def forward(self, *args, **kw): assert ('execute', args, kw) == out # Test in non-server context - (api, home) = create_test_api(in_server=False) + api, _home = create_test_api(in_server=False) api.finalize() o = my_cmd(api) if six.PY2: @@ -668,7 +666,7 @@ def forward(self, *args, **kw): expected = [TestMessage().to_dict()] # Test in server context: - (api, home) = create_test_api(in_server=True) + api, _home = create_test_api(in_server=True) api.finalize() o = my_cmd(api) if six.PY2: @@ -678,7 +676,7 @@ def forward(self, *args, **kw): assert {'name': 'execute', 'messages': expected} == o.run(*args, **kw) # Test in non-server context - (api, home) = create_test_api(in_server=False) + api, _home = create_test_api(in_server=False) api.finalize() o = my_cmd(api) if six.PY2: @@ -859,7 +857,7 @@ def execute(self, *args, **options): return dict(result=('execute', args, options)) # Test when in_server=False: - (api, home) = create_test_api(in_server=False) + api, _home = create_test_api(in_server=False) api.add_plugin(example) api.finalize() cmd = api.Command.example @@ -877,7 +875,7 @@ def execute(self, *args, **options): ) # Test when in_server=True (should always call execute): - (api, home) = create_test_api(in_server=True) + api, _home = create_test_api(in_server=True) api.add_plugin(example) api.finalize() cmd = api.Command.example @@ -1001,7 +999,7 @@ def test_primary_key(self): """ Test the `ipalib.frontend.Object.primary_key` attribute. """ - (api, home) = create_test_api() + api, _home = create_test_api() api.finalize() # Test with no primary keys: @@ -1047,7 +1045,7 @@ def test_backend(self): """ Test the `ipalib.frontend.Object.backend` attribute. """ - (api, home) = create_test_api() + api, _home = create_test_api() class ldap(backend.Backend): whatever = 'It worked!' api.add_plugin(ldap) @@ -1079,7 +1077,7 @@ def test_params_minus(self): """ class example(self.cls): takes_params = ('one', 'two', 'three', 'four') - (api, home) = create_test_api() + api, _home = create_test_api() api.finalize() o = example(api) p = o.params @@ -1137,7 +1135,7 @@ def get_api(self, args=tuple(), options=tuple()): """ Return a finalized `ipalib.plugable.API` instance. """ - (api, home) = create_test_api() + api, _home = create_test_api() class user(frontend.Object): takes_params = ( 'givenname', diff --git a/ipatests/test_ipalib/test_parameters.py b/ipatests/test_ipalib/test_parameters.py index 64259d1..a23f97d 100644 --- a/ipatests/test_ipalib/test_parameters.py +++ b/ipatests/test_ipalib/test_parameters.py @@ -43,8 +43,6 @@ from ipalib.errors import ValidationError, ConversionError from ipalib import _ -# pylint: disable=unused-variable - if six.PY3: unicode = str long = int @@ -253,7 +251,7 @@ class Subclass(self.cls): ('extra4', callable, lambda whatever: whatever + 7), ) o = Subclass('my_param') # Test with no **kw: - for (key, kind, default) in o.kwargs: + for key, kind, _default in o.kwargs: # Test with a type invalid for all: value = object() kw = {key: value} @@ -353,7 +351,7 @@ def test_clone(self): assert clone is not orig assert type(clone) is self.cls assert clone.name is orig.name - for (key, kind, default) in self.cls.kwargs: + for key, _kind, _default in self.cls.kwargs: assert getattr(clone, key) == getattr(orig, key) # Test with a param spec: @@ -363,7 +361,7 @@ def test_clone(self): assert clone.param_spec == 'my_param*' assert clone is not orig assert type(clone) is self.cls - for (key, kind, default) in self.cls.kwargs: + for key, _kind, _default in self.cls.kwargs: assert getattr(clone, key) == getattr(orig, key) # Test with overrides: @@ -390,7 +388,7 @@ def test_clone_rename(self): assert clone is not orig assert type(clone) is self.cls assert clone.name == new_name - for (key, kind, default) in self.cls.kwargs: + for key, _kind, _default in self.cls.kwargs: if key in ('cli_name', 'label', 'doc', 'cli_metavar'): continue assert getattr(clone, key) is getattr(orig, key) @@ -449,7 +447,7 @@ def test_convert_scalar(self): assert o._convert_scalar(None) is None assert dummy.called() is False # Test with incorrect type - e = raises(errors.ConversionError, o._convert_scalar, 'hello') + raises(errors.ConversionError, o._convert_scalar, 'hello') def test_validate(self): """ @@ -1511,7 +1509,7 @@ def test_init(self): u'periodical yearly month 4 day 1-31 0800-1400', u'periodic weekly day 8 0800-1400', ): - e = raises(ValidationError, o._rule_required, None, value) + raises(ValidationError, o._rule_required, None, value) def test_create_param(): """ diff --git a/ipatests/test_ipalib/test_rpc.py b/ipatests/test_ipalib/test_rpc.py index de63b2a..cfa1515 100644 --- a/ipatests/test_ipalib/test_rpc.py +++ b/ipatests/test_ipalib/test_rpc.py @@ -34,8 +34,6 @@ from ipalib import rpc, errors, api, request from ipapython.version import API_VERSION -# pylint: disable=unused-variable - if six.PY3: unicode = str @@ -44,7 +42,7 @@ def dump_n_load(value): - (param, method) = loads( + param, _method = loads( dumps((value,), allow_none=True) ) return param[0] @@ -115,7 +113,7 @@ def test_xml_wrap(): u = f(u'hello', API_VERSION) assert type(u) is unicode assert u == u'hello' - value = f([dict(one=False, two=u'hello'), None, b'hello'], API_VERSION) + f([dict(one=False, two=u'hello'), None, b'hello'], API_VERSION) def test_xml_unwrap(): @@ -211,7 +209,7 @@ def test_forward(self): class user_add(Command): pass - (o, api, home) = self.instance('Backend', user_add, in_server=False) + o, _api, _home = self.instance('Backend', user_add, in_server=False) args = (binary_bytes, utf8_bytes, unicode_str) kw = dict(one=binary_bytes, two=utf8_bytes, three=unicode_str) params = [args, kw] @@ -281,7 +279,7 @@ def test_list_methods(self): def test_list_methods_many_params(self): try: - result = api.Backend.xmlclient.conn.system.listMethods('foo') + api.Backend.xmlclient.conn.system.listMethods('foo') except Fault as f: print(f) assert f.faultCode == 3003 @@ -301,7 +299,7 @@ def test_ping_help(self): def test_signature_no_params(self): try: - result = api.Backend.xmlclient.conn.system.methodSignature() + api.Backend.xmlclient.conn.system.methodSignature() except Fault as f: print(f) assert f.faultCode == 3007 @@ -311,7 +309,7 @@ def test_signature_no_params(self): def test_signature_many_params(self): try: - result = api.Backend.xmlclient.conn.system.methodSignature('a', 'b') + api.Backend.xmlclient.conn.system.methodSignature('a', 'b') except Fault as f: print(f) assert f.faultCode == 3004 @@ -322,7 +320,7 @@ def test_signature_many_params(self): def test_help_no_params(self): try: - result = api.Backend.xmlclient.conn.system.methodHelp() + api.Backend.xmlclient.conn.system.methodHelp() except Fault as f: print(f) assert f.faultCode == 3007 @@ -332,7 +330,7 @@ def test_help_no_params(self): def test_help_many_params(self): try: - result = api.Backend.xmlclient.conn.system.methodHelp('a', 'b') + api.Backend.xmlclient.conn.system.methodHelp('a', 'b') except Fault as f: print(f) assert f.faultCode == 3004 diff --git a/ipatests/test_ipaserver/test_rpcserver.py b/ipatests/test_ipaserver/test_rpcserver.py index 858264e..6cc2472 100644 --- a/ipatests/test_ipaserver/test_rpcserver.py +++ b/ipatests/test_ipaserver/test_rpcserver.py @@ -30,8 +30,6 @@ from ipalib import errors from ipaserver import rpcserver -# pylint: disable=unused-variable - if six.PY3: unicode = str @@ -196,7 +194,7 @@ class test_xmlserver(PluginTester): _plugin = rpcserver.xmlserver def test_marshaled_dispatch(self): # FIXME - (o, api, home) = self.instance('Backend', in_server=True) + self.instance('Backend', in_server=True) class test_jsonserver(PluginTester): @@ -210,7 +208,7 @@ def test_unmarshal(self): """ Test the `ipaserver.rpcserver.jsonserver.unmarshal` method. """ - (o, api, home) = self.instance('Backend', in_server=True) + o, _api, _home = self.instance('Backend', in_server=True) # Test with invalid JSON-data: e = raises(errors.JSONError, o.unmarshal, 'this wont work') diff --git a/ipatests/test_ipaserver/test_serverroles.py b/ipatests/test_ipaserver/test_serverroles.py index 63ed5f8..0118105 100644 --- a/ipatests/test_ipaserver/test_serverroles.py +++ b/ipatests/test_ipaserver/test_serverroles.py @@ -15,7 +15,6 @@ from ipapython.dn import DN from ipatests.util import MockLDAP -# pylint: disable=unused-variable def _make_service_entry_mods(enabled=True, other_config=None): mods = { @@ -308,7 +307,7 @@ def _remove_svc_master_entries(self, master_dn): if entries: entries.sort(key=lambda x: len(x[0]), reverse=True) - for entry_dn, attrs in entries: + for entry_dn, _attrs in entries: self.ldap.del_entry(str(entry_dn)) def _add_ipamaster_services(self, master_dn): @@ -320,7 +319,7 @@ def _add_ipamaster_services(self, master_dn): self.ldap.add_entry(str(svc_dn), _make_service_entry_mods()) def _add_members(self, dn, fqdn, member_attrs): - entry, attrs = self.ldap.connection.search_s( + _entry, attrs = self.ldap.connection.search_s( str(dn), ldap.SCOPE_SUBTREE)[0] mods = [] value = attrs.get('member', []) @@ -344,7 +343,7 @@ def _add_members(self, dn, fqdn, member_attrs): self.ldap.connection.modify_s(str(dn), mods) def _remove_members(self, dn, fqdn, member_attrs): - entry, attrs = self.ldap.connection.search_s( + _entry, attrs = self.ldap.connection.search_s( str(dn), ldap.SCOPE_SUBTREE)[0] mods = [] for a in member_attrs: @@ -574,7 +573,7 @@ def configured_role(request): @pytest.fixture(params=list(role_provider_iter(master_data)), ids=['{} providers'.format(role_name) - for role_name, m in + for role_name, _m in role_provider_iter(master_data)]) def role_providers(request): return request.param From fc09cc68e49e5423d11bab0d09d7cdcd61a624f9 Mon Sep 17 00:00:00 2001 From: Martin Basti <mba...@redhat.com> Date: Fri, 7 Oct 2016 15:07:49 +0200 Subject: [PATCH 2/2] Pylint: fix the rest of unused local variables --- ipaclient/plugins/cert.py | 2 -- ipalib/certstore.py | 12 +++++------- ipalib/frontend.py | 16 +--------------- ipalib/parameters.py | 6 +----- ipalib/rpc.py | 16 +++++++--------- ipalib/util.py | 12 ++++-------- ipapython/certdb.py | 8 +++----- ipapython/certmonger.py | 10 ++++------ ipapython/cookie.py | 11 ++++++----- ipapython/dnssec/localhsm.py | 4 +--- ipapython/ipaldap.py | 12 +++--------- ipapython/ipautil.py | 14 ++++++-------- ipapython/p11helper.py | 16 +++++++--------- ipapython/sysrestore.py | 15 +++++---------- 14 files changed, 53 insertions(+), 101 deletions(-) diff --git a/ipaclient/plugins/cert.py b/ipaclient/plugins/cert.py index 5e791ce..1075972 100644 --- a/ipaclient/plugins/cert.py +++ b/ipaclient/plugins/cert.py @@ -27,8 +27,6 @@ from ipalib.plugable import Registry from ipalib.text import _ -# pylint: disable=unused-variable - register = Registry() diff --git a/ipalib/certstore.py b/ipalib/certstore.py index d71cbd9..d17cb2b 100644 --- a/ipalib/certstore.py +++ b/ipalib/certstore.py @@ -29,8 +29,6 @@ from ipapython.certdb import get_ca_nickname from ipalib import errors, x509 -# pylint: disable=unused-variable - def _parse_cert(dercert): try: subject = x509.get_subject(dercert, x509.DER) @@ -108,7 +106,7 @@ def clean_old_config(ldap, base_dn, dn, config_ipa, config_compat): return try: - result, truncated = ldap.find_entries( + result, _truncated = ldap.find_entries( base_dn=DN(('cn', 'certificates'), ('cn', 'ipa'), ('cn', 'etc'), base_dn), filter='(|(ipaConfigString=ipaCA)(ipaConfigString=compatCA))', @@ -162,7 +160,7 @@ def update_ca_cert(ldap, base_dn, dercert, trusted=None, ext_key_usage=None, subject, issuer_serial, public_key = _parse_cert(dercert) filter = ldap.make_filter({'ipaCertSubject': subject}) - result, truncated = ldap.find_entries( + result, _truncated = ldap.find_entries( base_dn=DN(('cn', 'certificates'), ('cn', 'ipa'), ('cn', 'etc'), base_dn), filter=filter, @@ -247,7 +245,7 @@ def make_compat_ca_certs(certs, realm, ipa_ca_subject): result = [] for cert in certs: - subject, issuer_serial, public_key_info = _parse_cert(cert) + subject, _issuer_serial, _public_key_info = _parse_cert(cert) subject = DN(subject) if ipa_ca_subject is not None and subject == DN(ipa_ca_subject): @@ -285,7 +283,7 @@ def get_ca_certs(ldap, base_dn, compat_realm, compat_ipa_ca, if filter_subject: filter = ldap.make_filter({'ipaCertSubject': filter_subject}) filters.append(filter) - result, truncated = ldap.find_entries( + result, _truncated = ldap.find_entries( base_dn=container_dn, filter=ldap.combine_filters(filters, ldap.MATCH_ALL), attrs_list=['cn', 'ipaCertSubject', 'ipaCertIssuerSerial', @@ -323,7 +321,7 @@ def get_ca_certs(ldap, base_dn, compat_realm, compat_ipa_ca, cert = entry.single_value['cACertificate;binary'] try: - subject, issuer_serial, public_key_info = _parse_cert(cert) + subject, _issuer_serial, _public_key_info = _parse_cert(cert) except ValueError: pass else: diff --git a/ipalib/frontend.py b/ipalib/frontend.py index ca06f6f..c94d174 100644 --- a/ipalib/frontend.py +++ b/ipalib/frontend.py @@ -40,8 +40,6 @@ from ipalib.request import context, context_frame from ipalib.util import classproperty, json_serialize -# pylint: disable=unused-variable - if six.PY3: unicode = str @@ -777,10 +775,8 @@ def verify_client_version(self, client_version): if len(ver.version) < 2: raise VersionError(cver=ver.version, sver=server_ver.version, server= self.env.xmlrpc_uri) client_major = ver.version[0] - client_minor = ver.version[1] server_major = server_ver.version[0] - server_minor = server_ver.version[1] if server_major != client_major: raise VersionError(cver=client_version, sver=API_VERSION, server=self.env.xmlrpc_uri) @@ -1279,18 +1275,8 @@ def get_params(self): This method gets called by `HasParam._create_param_namespace()`. """ for spec in self._get_param_iterable('params'): - if type(spec) is str: - key = spec.rstrip('?*+') - else: - assert isinstance(spec, Param) - key = spec.name + assert isinstance(spec, (str, Param)) yield create_param(spec) - def get_key(p): - if p.param.required: - if p.param.default_from is None: - return 0 - return 1 - return 2 json_friendly_attributes = ( 'name', 'takes_params', diff --git a/ipalib/parameters.py b/ipalib/parameters.py index 77a6136..b13d4f5 100644 --- a/ipalib/parameters.py +++ b/ipalib/parameters.py @@ -119,7 +119,6 @@ from ipapython.dn import DN from ipapython.dnsutil import DNSName -# pylint: disable=unused-variable def _is_null(value): return not value and value != 0 # NOTE: False == 0 @@ -946,7 +945,7 @@ def sort_key(self, value): def __json__(self): json_dict = {} - for (a, k, d) in self.kwargs: + for a, k, _d in self.kwargs: if k in (callable, DefaultFrom): continue elif isinstance(getattr(self, a), frozenset): @@ -1786,7 +1785,6 @@ def _check_Y_spec(self, ts, index): if ts[index] == 'month': index += 1 self._check_interval(ts[index], self._check_month_num) - month_num = int(ts[index]) index = self._check_M_spec(ts, index + 1) elif ts[index] == 'week': self._check_interval(ts[index + 1], self._check_woty) @@ -1940,8 +1938,6 @@ def __init__(self, name, *rules, **kw): def _convert_scalar(self, value, index=None): if isinstance(value, unicode): - error = None - try: validate_idna_domain(value) except ValueError as e: diff --git a/ipalib/rpc.py b/ipalib/rpc.py index 4fb560b..19ce0cc 100644 --- a/ipalib/rpc.py +++ b/ipalib/rpc.py @@ -70,8 +70,6 @@ from ipalib.capabilities import VERSION_WITHOUT_CAPABILITIES from ipalib import api -# pylint: disable=unused-variable - # The XMLRPC client is in "six.moves.xmlrpc_client", but pylint # cannot handle that try: @@ -491,7 +489,7 @@ def get_connection_dbdir(self): return None def make_connection(self, host): - host, self._extra_headers, x509 = self.get_host_info(host) + host, self._extra_headers, _x509 = self.get_host_info(host) if self._connection and host == self._connection[0]: return self._connection[1] @@ -595,7 +593,7 @@ def _auth_complete(self, response): header = response.getheader('www-authenticate', '') token = None for field in header.split(','): - k, _, v = field.strip().partition(' ') + k, _dummy, v = field.strip().partition(' ') if k.lower() == 'negotiate': try: token = base64.b64decode(v.encode('ascii')) @@ -751,14 +749,14 @@ def get_url_list(self, rpc_uri): Create a list of urls consisting of the available IPA servers. """ # the configured URL defines what we use for the discovered servers - (scheme, netloc, path, params, query, fragment + (_scheme, _netloc, path, _params, _query, _fragment ) = urllib.parse.urlparse(rpc_uri) servers = [] name = '_ldap._tcp.%s.' % self.env.domain try: answers = resolver.query(name, rdatatype.SRV) - except DNSException as e: + except DNSException: answers = [] for answer in answers: @@ -791,13 +789,13 @@ def get_session_cookie_from_persistent_storage(self, principal): # (possibly with more than one cookie). try: cookie_string = read_persistent_client_session_data(principal) - except Exception as e: + except Exception: return None # Search for the session cookie within the cookie string try: session_cookie = Cookie.get_named_cookie_from_string(cookie_string, COOKIE_NAME) - except Exception as e: + except Exception: return None return session_cookie @@ -914,7 +912,7 @@ def create_connection(self, ccache=None, verbose=None, fallback=None, try: command = getattr(serverproxy, 'ping') try: - response = command([], {}) + command([], {}) except Fault as e: e = decode_fault(e) if e.faultCode in errors_by_code: diff --git a/ipalib/util.py b/ipalib/util.py index 4df6847..1c00cd7 100644 --- a/ipalib/util.py +++ b/ipalib/util.py @@ -51,8 +51,6 @@ from ipapython.dnsutil import resolve_ip_addresses from ipapython.ipa_log_manager import root_logger -# pylint: disable=unused-variable - if six.PY3: unicode = str @@ -176,7 +174,7 @@ def normalize_zonemgr(zonemgr): return zonemgr if '@' in zonemgr: # local-part needs to be normalized - name, at, domain = zonemgr.partition('@') + name, _at, domain = zonemgr.partition('@') name = name.replace('.', '\\.') zonemgr = u''.join((name, u'.', domain)) @@ -542,7 +540,7 @@ def get_reverse_zone_default(ip_address): def validate_rdn_param(ugettext, value): try: - rdn = RDN(value) + RDN(value) except Exception as e: return str(e) return None @@ -794,8 +792,6 @@ def detect_dns_zone_realm_type(api, domain): domain_suffix = DNSName(domain) kerberos_record_name = kerberos_prefix + domain_suffix - response = None - try: result = resolver.query(kerberos_record_name, rdatatype.TXT) answer = result.response.answer @@ -813,7 +809,7 @@ def detect_dns_zone_realm_type(api, domain): else: return 'foreign' - except DNSException as e: + except DNSException: pass # Try to detect AD specific record in the zone. @@ -827,7 +823,7 @@ def detect_dns_zone_realm_type(api, domain): result = resolver.query(ad_specific_record_name, rdatatype.SRV) return 'foreign' - except DNSException as e: + except DNSException: pass # If we could not detect type with certainity, return unknown diff --git a/ipapython/certdb.py b/ipapython/certdb.py index 850ba59..06666c0 100644 --- a/ipapython/certdb.py +++ b/ipapython/certdb.py @@ -30,8 +30,6 @@ from ipapython import ipautil from ipalib import x509 -# pylint: disable=unused-variable - CA_NICKNAME_FMT = "%s IPA CA" @@ -359,7 +357,7 @@ def import_files(self, files, db_password_filename, import_keys=False, server_certs = self.find_server_certs() if key_nickname: - for nickname, trust_flags in server_certs: + for nickname, _trust_flags in server_certs: if nickname == key_nickname: break else: @@ -422,7 +420,7 @@ def trust_root_cert(self, root_nickname, trust_flags=None): try: self.run_certutil(["-M", "-n", root_nickname, "-t", trust_flags]) - except ipautil.CalledProcessError as e: + except ipautil.CalledProcessError: raise RuntimeError( "Setting trust on %s failed" % root_nickname) @@ -434,7 +432,7 @@ def get_cert(self, nickname, pem=False): raise RuntimeError("Failed to get %s" % nickname) cert = result.output if not pem: - (cert, start) = find_cert_from_txt(cert, start=0) + cert, _start = find_cert_from_txt(cert, start=0) cert = x509.strip_header(cert) cert = base64.b64decode(cert) return cert diff --git a/ipapython/certmonger.py b/ipapython/certmonger.py index 8c3faf0..765f9e8 100644 --- a/ipapython/certmonger.py +++ b/ipapython/certmonger.py @@ -34,8 +34,6 @@ from ipaplatform.paths import paths from ipaplatform import services -# pylint: disable=unused-variable - DBUS_CM_PATH = '/org/fedorahosted/certmonger' DBUS_CM_IF = 'org.fedorahosted.certmonger' DBUS_CM_NAME = 'org.fedorahosted.certmonger' @@ -88,7 +86,7 @@ def _start_private_conn(self): sock_filename = os.path.join(tempfile.mkdtemp(), 'certmonger') self._proc = subprocess.Popen([paths.CERTMONGER, '-n', '-L', '-P', sock_filename]) - for t in range(0, self.timeout, 5): + for _t in range(0, self.timeout, 5): if os.path.exists(sock_filename): return "unix:path=%s" % sock_filename time.sleep(5) @@ -101,7 +99,7 @@ def _stop_private_conn(self): if retcode is not None: return self._proc.terminate() - for t in range(0, self.timeout, 5): + for _t in range(0, self.timeout, 5): retcode = self._proc.poll() if retcode is not None: return @@ -140,7 +138,7 @@ def __init__(self): root_logger.error("Failed to start certmonger: %s" % e) raise - for t in range(0, self.timeout, 5): + for _t in range(0, self.timeout, 5): try: self._bus.get_name_owner(DBUS_CM_NAME) break @@ -535,7 +533,7 @@ def check_state(dirs): def wait_for_request(request_id, timeout=120): - for i in range(0, timeout, 5): + for _i in range(0, timeout, 5): state = get_request_value(request_id, 'status') root_logger.debug("certmonger request is in state %r", state) if state in ('CA_REJECTED', 'CA_UNREACHABLE', 'CA_UNCONFIGURED', diff --git a/ipapython/cookie.py b/ipapython/cookie.py index eaf6a37..97f24b2 100644 --- a/ipapython/cookie.py +++ b/ipapython/cookie.py @@ -27,8 +27,6 @@ from ipapython.ipa_log_manager import log_mgr -# pylint: disable=unused-variable - ''' Core Python has two cookie libraries, Cookie.py targeted to server side and cookielib.py targeted to client side. So why this module and @@ -542,7 +540,7 @@ def set_defaults_from_url(self, url): received from. ''' - scheme, domain, path, params, query, fragment = urlparse(url) + _scheme, domain, path, _params, _query, _fragment = urlparse(url) if self.domain is None: self.domain = domain.lower() @@ -599,7 +597,7 @@ def domain_valid(url_domain, cookie_domain): from ipalib.util import validate_domain_name try: validate_domain_name(url_domain) - except Exception as e: + except Exception: return False if cookie_domain is None: @@ -644,7 +642,10 @@ def path_valid(url_path, cookie_path): cookie_name = self.key - url_scheme, url_domain, url_path, url_params, url_query, url_fragment = urlparse(url) + ( + url_scheme, url_domain, url_path, + _url_params, _url_query, _url_fragment + ) = urlparse(url) cookie_expiration = self.get_expiration() if cookie_expiration is not None: diff --git a/ipapython/dnssec/localhsm.py b/ipapython/dnssec/localhsm.py index 338adda..d02fc75 100755 --- a/ipapython/dnssec/localhsm.py +++ b/ipapython/dnssec/localhsm.py @@ -18,8 +18,6 @@ keytype_id2name, keytype_name2id, ldap2p11helper_api_params) -# pylint: disable=unused-variable - private_key_api_params = set(["label", "id", "data", "unwrapping_key", "wrapping_mech", "key_type", "cka_always_authenticate", "cka_copyable", "cka_decrypt", "cka_derive", "cka_extractable", "cka_modifiable", @@ -81,7 +79,7 @@ def __iter__(self): def __len__(self): cnt = 0 - for attr in self: + for _attr in self: cnt += 1 return cnt diff --git a/ipapython/ipaldap.py b/ipapython/ipaldap.py index 2dfc5b3..c6f0aaa 100644 --- a/ipapython/ipaldap.py +++ b/ipapython/ipaldap.py @@ -44,8 +44,6 @@ from ipapython.dnsutil import DNSName from ipapython.kerberos import Principal -# pylint: disable=unused-variable - if six.PY3: unicode = str @@ -890,7 +888,7 @@ def decode(self, val, attr): return DNSName.from_text(val) else: return target_type(val) - except Exception as e: + except Exception: msg = 'unable to convert the attribute %r value %r to type %s' % (attr, val, target_type) self.log.error(msg) raise ValueError(msg) @@ -1206,10 +1204,6 @@ def make_filter_from_attr( False - forbid trailing filter wildcard when exact=False """ if isinstance(value, (list, tuple)): - if rules == cls.MATCH_NONE: - make_filter_rules = cls.MATCH_ANY - else: - make_filter_rules = rules flts = [ cls.make_filter_from_attr( attr, v, exact=exact, @@ -1384,7 +1378,7 @@ def find_entries(self, filter=None, attrs_list=None, base_dn=None, ) while True: result = self.conn.result3(id, 0) - objtype, res_list, res_id, res_ctrls = result + objtype, res_list, _res_id, res_ctrls = result res_list = self._convert_result(res_list) if not res_list: break @@ -1682,7 +1676,7 @@ def do_bind(self, dm_password="", autobind=AUTOBIND_AUTO, timeout=DEFAULT_TIMEOU pw_name = pwd.getpwuid(os.geteuid()).pw_name self.do_external_bind(pw_name, timeout=timeout) return - except errors.NotFound as e: + except errors.NotFound: if autobind == AUTOBIND_ENABLED: # autobind was required and failed, raise # exception that it failed diff --git a/ipapython/ipautil.py b/ipapython/ipautil.py index 41544a1..b0aa262 100644 --- a/ipapython/ipautil.py +++ b/ipapython/ipautil.py @@ -54,8 +54,6 @@ from ipaplatform.paths import paths from ipapython.dn import DN -# pylint: disable=unused-variable - SHARE_DIR = paths.USR_SHARE_IPA_DIR PLUGINS_SHARE_DIR = paths.IPA_PLUGINS @@ -115,7 +113,7 @@ def __init__(self, addr): # netaddr.IPAddress doesn't handle zone indices in textual # IPv6 addresses. Try removing zone index and parse the # address again. - addr, sep, foo = addr.partition('%') + addr, sep, _foo = addr.partition('%') if sep != '%': raise addr = netaddr.IPAddress(addr, flags=self.netaddr_ip_flags) @@ -933,7 +931,7 @@ def user_input(prompt, default = None, allow_empty = True): def host_port_open(host, port, socket_type=socket.SOCK_STREAM, socket_timeout=None): for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket_type): - af, socktype, proto, canonname, sa = res + af, socktype, proto, _canonname, sa = res try: try: s = socket.socket(af, socktype, proto) @@ -951,7 +949,7 @@ def host_port_open(host, port, socket_type=socket.SOCK_STREAM, socket_timeout=No s.recv(512) return True - except socket.error as e: + except socket.error: pass finally: if s: @@ -976,7 +974,7 @@ def bind_port_responder(port, socket_type=socket.SOCK_STREAM, socket_timeout=Non last_socket_error = e continue for res in addr_infos: - af, socktype, proto, canonname, sa = res + af, socktype, proto, _canonname, sa = res try: s = socket.socket(af, socktype, proto) except socket.error as e: @@ -1003,14 +1001,14 @@ def bind_port_responder(port, socket_type=socket.SOCK_STREAM, socket_timeout=Non while True: if socket_type == socket.SOCK_STREAM: s.listen(1) - connection, client_address = s.accept() + connection, _client_address = s.accept() try: if responder_data: connection.sendall(responder_data) finally: connection.close() elif socket_type == socket.SOCK_DGRAM: - data, addr = s.recvfrom(1) + _data, addr = s.recvfrom(1) if responder_data: s.sendto(responder_data, addr) diff --git a/ipapython/p11helper.py b/ipapython/p11helper.py index 0001b6a..5963c6d 100644 --- a/ipapython/p11helper.py +++ b/ipapython/p11helper.py @@ -12,8 +12,6 @@ from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa from cffi import FFI -# pylint: disable=unused-variable - if six.PY3: unicode = str @@ -931,7 +929,7 @@ def generate_master_key(self, label, id, key_length=16, cka_copyable=True, raise DuplicationError("Master key with same ID already exists") # Process keyword boolean arguments - (cka_copyable_ptr, cka_decrypt_ptr, cka_derive_ptr, cka_encrypt_ptr, + (_cka_copyable_ptr, cka_decrypt_ptr, cka_derive_ptr, cka_encrypt_ptr, cka_extractable_ptr, cka_modifiable_ptr, cka_private_ptr, cka_sensitive_ptr, cka_sign_ptr, cka_unwrap_ptr, cka_verify_ptr, cka_wrap_ptr, cka_wrap_with_trusted_ptr,) = convert_py2bool(attrs) @@ -1041,14 +1039,14 @@ def generate_replica_key_pair(self, label, id, modulus_bits=2048, modulus_bits_ptr = new_ptr(CK_ULONG, modulus_bits) # Process keyword boolean arguments - (pub_cka_copyable_ptr, pub_cka_derive_ptr, pub_cka_encrypt_ptr, + (_pub_cka_copyable_ptr, pub_cka_derive_ptr, pub_cka_encrypt_ptr, pub_cka_modifiable_ptr, pub_cka_private_ptr, pub_cka_trusted_ptr, pub_cka_verify_ptr, pub_cka_verify_recover_ptr, pub_cka_wrap_ptr, ) = convert_py2bool(attrs_pub) - (priv_cka_always_authenticate_ptr, priv_cka_copyable_ptr, + (priv_cka_always_authenticate_ptr, _priv_cka_copyable_ptr, priv_cka_decrypt_ptr, priv_cka_derive_ptr, priv_cka_extractable_ptr, priv_cka_modifiable_ptr, priv_cka_private_ptr, priv_cka_sensitive_ptr, - priv_cka_sign_ptr, priv_cka_sign_recover_ptr, priv_cka_unwrap_ptr, + priv_cka_sign_ptr, _priv_cka_sign_recover_ptr, priv_cka_unwrap_ptr, priv_cka_wrap_with_trusted_ptr,) = convert_py2bool(attrs_priv) # 65537 (RFC 6376 section 3.3.1) @@ -1486,7 +1484,7 @@ def import_wrapped_secret_key(self, label, id, data, unwrapping_key, raise DuplicationError("Secret key with same ID already exists") # Process keyword boolean arguments - (cka_copyable_ptr, cka_decrypt_ptr, cka_derive_ptr, cka_encrypt_ptr, + (_cka_copyable_ptr, cka_decrypt_ptr, cka_derive_ptr, cka_encrypt_ptr, cka_extractable_ptr, cka_modifiable_ptr, cka_private_ptr, cka_sensitive_ptr, cka_sign_ptr, cka_unwrap_ptr, cka_verify_ptr, cka_wrap_ptr, cka_wrap_with_trusted_ptr,) = convert_py2bool(attrs) @@ -1572,10 +1570,10 @@ def import_wrapped_private_key(self, label, id, data, unwrapping_key, raise DuplicationError("Secret key with same ID already exists") # Process keyword boolean arguments - (cka_always_authenticate_ptr, cka_copyable_ptr, cka_decrypt_ptr, + (cka_always_authenticate_ptr, _cka_copyable_ptr, cka_decrypt_ptr, cka_derive_ptr, cka_extractable_ptr, cka_modifiable_ptr, cka_private_ptr, cka_sensitive_ptr, cka_sign_ptr, - cka_sign_recover_ptr, cka_unwrap_ptr, cka_wrap_with_trusted_ptr, + _cka_sign_recover_ptr, cka_unwrap_ptr, cka_wrap_with_trusted_ptr, ) = convert_py2bool(attrs_priv) template = new_array(CK_ATTRIBUTE, ( diff --git a/ipapython/sysrestore.py b/ipapython/sysrestore.py index 4e3cccb..2a8f448 100644 --- a/ipapython/sysrestore.py +++ b/ipapython/sysrestore.py @@ -35,8 +35,6 @@ from ipaplatform.tasks import tasks from ipaplatform.paths import paths -# pylint: disable=unused-variable - if six.PY3: unicode = str @@ -118,10 +116,10 @@ def backup_file(self, path): root_logger.debug(" -> Not backing up - '%s' doesn't exist", path) return - (reldir, backupfile) = os.path.split(path) + _reldir, backupfile = os.path.split(path) filename = "" - for i in range(8): + for _i in range(8): h = "%02x" % self.random.randint(0,255) filename += h filename += "-"+backupfile @@ -145,8 +143,8 @@ def has_file(self, path): Returns #True if the file exists in the file store, #False otherwise """ result = False - for (key, value) in self.files.items(): - (mode,uid,gid,filepath) = value.split(',', 3) + for _key, value in self.files.items(): + _mode, _uid, _gid, filepath = value.split(',', 3) if (filepath == path): result = True break @@ -264,13 +262,10 @@ def untrack_file(self, path): if not os.path.isabs(path): raise ValueError("Absolute path required") - mode = None - uid = None - gid = None filename = None for (key, value) in self.files.items(): - (mode,uid,gid,filepath) = value.split(',', 3) + _mode, _uid, _gid, filepath = value.split(',', 3) if (filepath == path): filename = key break
-- Manage your subscription for the Freeipa-devel mailing list: https://www.redhat.com/mailman/listinfo/freeipa-devel Contribute to FreeIPA: http://www.freeipa.org/page/Contribute/Code