Replace dict.has_key with the 'in' operator

The deprecated has_key method will be removed from dicts in Python 3.

For custom dict-like classes, has_key() is kept on Python 2,
but disabled for Python 3.

Reviewed-By: Tomas Babej <tbabej@redhat.com>
This commit is contained in:
Petr Viktorin
2015-07-30 17:29:39 +02:00
committed by Tomas Babej
parent 8b88caa110
commit 6a741b51da
14 changed files with 56 additions and 55 deletions

View File

@@ -78,10 +78,10 @@ def assert_equal(trial, reference):
reference_val = reference[key]
trial_val = trial[key]
if reference_decode.has_key(key):
if key in reference_decode:
reference_val = reference_decode[key](reference_val)
if trial_decode.has_key(key):
if key in trial_decode:
trial_val = trial_decode[key](trial_val)
assert reference_val == trial_val, \

View File

@@ -69,7 +69,7 @@ def application(environ, start_response):
return wsgi_redirect(start_response, 'index.html')
form_data = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
if not form_data.has_key('username') or not form_data.has_key('password'):
if 'username' not in form_data or 'password' not in form_data:
return wsgi_redirect(start_response, 'invalid.html')
# API object only for configuration, finalize() not needed

View File

@@ -280,7 +280,7 @@ def containsAny(str, set):
def _visit_pyfiles(list, dirname, names):
"""Helper for getFilesForName()."""
# get extension for python source files
if not globals().has_key('_py_ext'):
if '_py_ext' not in globals():
global _py_ext
_py_ext = [triple[0] for triple in imp.get_suffixes()
if triple[2] == imp.PY_SOURCE][0]

View File

@@ -401,7 +401,7 @@ class API(ReadOnly):
else:
level = 'warning'
if log_mgr.handlers.has_key('console'):
if 'console' in log_mgr.handlers:
log_mgr.remove_handler('console')
log_mgr.create_log_handlers([dict(name='console',
stream=sys.stderr,

View File

@@ -692,7 +692,7 @@ class SessionAuthManager(object):
def unregister(self, name):
self.debug('SessionAuthManager.unregister: name=%s', name)
if not self.auth_managers.has_key(name):
if name not in self.auth_managers:
raise KeyError('cannot unregister auth manager named "%s", does not exist',
name)
del self.auth_managers[name]
@@ -1259,7 +1259,7 @@ def release_ipa_ccache(ccache_name):
do we'll remove them.
'''
if os.environ.has_key('KRB5CCNAME'):
if 'KRB5CCNAME' in os.environ:
if ccache_name != os.environ['KRB5CCNAME']:
root_logger.error('release_ipa_ccache: ccache_name (%s) != KRB5CCNAME environment variable (%s)',
ccache_name, os.environ['KRB5CCNAME'])

View File

@@ -185,7 +185,7 @@ def standard_logging_setup(filename=None, verbose=False, debug=False,
format=LOGGING_FORMAT_STANDARD_FILE)
handlers.append(file_handler)
if log_mgr.handlers.has_key('console'):
if 'console' in log_mgr.handlers:
log_mgr.remove_handler('console')
level = 'error'
if verbose:

View File

@@ -544,8 +544,9 @@ class CIDict(dict):
def __contains__(self, key):
return super(CIDict, self).__contains__(key.lower())
def has_key(self, key):
return super(CIDict, self).has_key(key.lower())
if sys.version_info < (3, 0):
def has_key(self, key):
return super(CIDict, self).has_key(key.lower())
def get(self, key, failobj=None):
try:

View File

@@ -1148,7 +1148,7 @@ class LogManager(object):
stream = cfg.get("stream")
log_handler = cfg.get("log_handler")
if filename:
if cfg.has_key("stream"):
if "stream" in cfg:
raise ValueError("both filename and stream are specified, must be one or the other, config: %s" % cfg)
path = os.path.abspath(filename)
filemode = cfg.get('filemode', 'a')

View File

@@ -370,10 +370,10 @@ class StateFile:
self._load()
if not self.modules.has_key(module):
if module not in self.modules:
self.modules[module] = {}
if not self.modules.has_key(key):
if key not in self.modules:
self.modules[module][key] = value
self.save()
@@ -387,7 +387,7 @@ class StateFile:
"""
self._load()
if not self.modules.has_key(module):
if module not in self.modules:
return None
return self.modules[module].get(key, None)
@@ -429,7 +429,7 @@ class StateFile:
Can be used to determine if a service is configured.
"""
if self.modules.has_key(module):
if module in self.modules:
return True
else:
return False

View File

@@ -1442,14 +1442,14 @@ class ra(rabase.rabase):
# Return command result
cmd_result = {}
if parse_result.has_key('serial_numbers') and len(parse_result['serial_numbers']) > 0:
if 'serial_numbers' in parse_result and len(parse_result['serial_numbers']) > 0:
# see module documentation concerning serial numbers and XMLRPC
cmd_result['serial_number'] = unicode(parse_result['serial_numbers'][0])
if parse_result.has_key('request_id'):
if 'request_id' in parse_result:
cmd_result['request_id'] = parse_result['request_id']
if parse_result.has_key('cert_request_status'):
if 'cert_request_status' in parse_result:
cmd_result['cert_request_status'] = parse_result['cert_request_status']
return cmd_result
@@ -1529,15 +1529,15 @@ class ra(rabase.rabase):
# Return command result
cmd_result = {}
if parse_result.has_key('certificate'):
if 'certificate' in parse_result:
cmd_result['certificate'] = parse_result['certificate']
if parse_result.has_key('serial_number'):
if 'serial_number' in parse_result:
# see module documentation concerning serial numbers and XMLRPC
cmd_result['serial_number'] = unicode(parse_result['serial_number'])
cmd_result['serial_number_hex'] = u'0x%X' % int(cmd_result['serial_number'])
if parse_result.has_key('revocation_reason'):
if 'revocation_reason' in parse_result:
cmd_result['revocation_reason'] = parse_result['revocation_reason']
return cmd_result
@@ -1604,18 +1604,18 @@ class ra(rabase.rabase):
return cmd_result
request = parse_result['requests'][0]
if request.has_key('serial_number'):
if 'serial_number' in request:
# see module documentation concerning serial numbers and XMLRPC
cmd_result['serial_number'] = unicode(request['serial_number'])
cmd_result['serial_number_hex'] = u'0x%X' % request['serial_number']
if request.has_key('certificate'):
if 'certificate' in request:
cmd_result['certificate'] = request['certificate']
if request.has_key('request_id'):
if 'request_id' in request:
cmd_result['request_id'] = request['request_id']
if request.has_key('subject'):
if 'subject' in request:
cmd_result['subject'] = request['subject']
return cmd_result
@@ -1739,7 +1739,7 @@ class ra(rabase.rabase):
# Return command result
cmd_result = {}
if parse_result.has_key('error_string'):
if 'error_string' in parse_result:
cmd_result['error_string'] = parse_result['error_string']
if parse_result.get('unrevoked') == 'yes':

View File

@@ -517,7 +517,7 @@ class AuthManagerKerb(AuthManager):
of the login mechanisms.
'''
if session_data.has_key('ccache_data'):
if 'ccache_data' in session_data:
self.debug('AuthManager.logout.%s: deleting ccache_data', self.name)
del session_data['ccache_data']
else:
@@ -823,7 +823,7 @@ class jsonserver_session(jsonserver, KerberosSession):
# logout command removes the ccache data from the session
# data to invalidate the session credentials.
if session_data.has_key('ccache_data'):
if 'ccache_data' in session_data:
session_data['ccache_data'] = load_ccache_data(ipa_ccache_name)
# The request is finished with the ccache, destroy it.
@@ -1259,7 +1259,7 @@ class xmlserver_session(xmlserver, KerberosSession):
# logout command removes the ccache data from the session
# data to invalidate the session credentials.
if session_data.has_key('ccache_data'):
if 'ccache_data' in session_data:
session_data['ccache_data'] = load_ccache_data(ipa_ccache_name)
# The request is finished with the ccache, destroy it.

View File

@@ -1,6 +1,7 @@
#!/usr/bin/python2
import unittest
from ipapython.dn import *
def expected_class(klass, component):
@@ -248,13 +249,6 @@ class TestAVA(unittest.TestCase):
self.assertFalse(ava3_a in d)
self.assertFalse(ava3_b in d)
self.assertTrue(d.has_key(ava1_a))
self.assertTrue(d.has_key(ava1_b))
self.assertTrue(d.has_key(ava2_a))
self.assertTrue(d.has_key(ava2_b))
self.assertFalse(d.has_key(ava3_a))
self.assertFalse(d.has_key(ava3_b))
self.assertTrue(ava1_a in s)
self.assertTrue(ava1_b in s)
self.assertTrue(ava2_a in s)
@@ -1135,13 +1129,6 @@ class TestDN(unittest.TestCase):
self.assertFalse(dn3_a in d)
self.assertFalse(dn3_b in d)
self.assertTrue(d.has_key(dn1_a))
self.assertTrue(d.has_key(dn1_b))
self.assertTrue(d.has_key(dn2_a))
self.assertTrue(d.has_key(dn2_b))
self.assertFalse(d.has_key(dn3_a))
self.assertFalse(d.has_key(dn3_b))
self.assertTrue(dn1_a in s)
self.assertTrue(dn1_b in s)
self.assertTrue(dn2_a in s)

View File

@@ -20,7 +20,10 @@
Test the `ipapython/ipautil.py` module.
"""
import sys
import nose
import pytest
from ipapython import ipautil
@@ -116,13 +119,13 @@ class TestCIDict(object):
nose.tools.assert_equal("newval4", self.cidict["key4"])
def test_del(self):
assert self.cidict.has_key("Key1")
assert "Key1" in self.cidict
del(self.cidict["Key1"])
assert not self.cidict.has_key("Key1")
assert "Key1" not in self.cidict
assert self.cidict.has_key("key2")
assert "key2" in self.cidict
del(self.cidict["KEY2"])
assert not self.cidict.has_key("key2")
assert "key2" not in self.cidict
def test_clear(self):
nose.tools.assert_equal(3, len(self.cidict))
@@ -138,10 +141,11 @@ class TestCIDict(object):
copy = self.cidict.copy()
assert copy == self.cidict
nose.tools.assert_equal(3, len(copy))
assert copy.has_key("Key1")
assert copy.has_key("key1")
assert "Key1" in copy
assert "key1" in copy
nose.tools.assert_equal("val1", copy["Key1"])
@pytest.mark.skipif(sys.version_info >= (3, 0), reason="Python 2 only")
def test_haskey(self):
assert self.cidict.has_key("KEY1")
assert self.cidict.has_key("key2")
@@ -269,22 +273,22 @@ class TestCIDict(object):
def test_setdefault(self):
nose.tools.assert_equal("val1", self.cidict.setdefault("KEY1", "default"))
assert not self.cidict.has_key("KEY4")
assert "KEY4" not in self.cidict
nose.tools.assert_equal("default", self.cidict.setdefault("KEY4", "default"))
assert self.cidict.has_key("KEY4")
assert "KEY4" in self.cidict
nose.tools.assert_equal("default", self.cidict["key4"])
assert not self.cidict.has_key("KEY5")
assert "KEY5" not in self.cidict
nose.tools.assert_equal(None, self.cidict.setdefault("KEY5"))
assert self.cidict.has_key("KEY5")
assert "KEY5" in self.cidict
nose.tools.assert_equal(None, self.cidict["key5"])
def test_pop(self):
nose.tools.assert_equal("val1", self.cidict.pop("KEY1", "default"))
assert not self.cidict.has_key("key1")
assert "key1" not in self.cidict
nose.tools.assert_equal("val2", self.cidict.pop("KEY2"))
assert not self.cidict.has_key("key2")
assert "key2" not in self.cidict
nose.tools.assert_equal("default", self.cidict.pop("key4", "default"))
with nose.tools.assert_raises(KeyError):

View File

@@ -26,7 +26,9 @@
# The DM password needs to be set in ~/.ipa/.dmpw
import os
import sys
import pytest
import nose
from nose.tools import assert_raises # pylint: disable=E0611
import nss.nss as nss
@@ -238,12 +240,19 @@ class test_LDAPEntry(object):
assert not e
assert 'cn' not in e
@pytest.mark.skipif(sys.version_info >= (3, 0), reason="Python 2 only")
def test_has_key(self):
e = self.entry
assert not e.has_key('xyz')
assert e.has_key('cn')
assert e.has_key('COMMONNAME')
def test_in(self):
e = self.entry
assert 'xyz' not in e
assert 'cn' in e
assert 'COMMONNAME' in e
def test_get(self):
e = self.entry
assert e.get('cn') == self.cn1