summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorPetr Viktorin <pviktori@redhat.com>2015-08-11 13:51:14 +0200
committerJan Cholasta <jcholast@redhat.com>2015-09-01 11:42:01 +0200
commit3bf91eab25c602a6fad2665456f57e8629c5a6f4 (patch)
tree52f713e898a385d57a914d539a7da9a20fc20166
parentdd16cc98b0d67f1448bf9de25f8adce512b1431c (diff)
downloadfreeipa-3bf91eab25c602a6fad2665456f57e8629c5a6f4.tar.gz
freeipa-3bf91eab25c602a6fad2665456f57e8629c5a6f4.tar.xz
freeipa-3bf91eab25c602a6fad2665456f57e8629c5a6f4.zip
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists, iterkeys()/itervalues()/iteritems(), which return iterators, and viewkeys()/viewvalues()/viewitems() which return views. Python 3 has only keys()/values()/items(), which return views. To get iterators, one can use iter() or a for loop/comprehension; for lists there's the list() constructor. When iterating through the entire dict, without modifying the dict, the difference between Python 2's items() and iteritems() is negligible, especially on small dicts (the main overhead is extra memory, not CPU time). In the interest of simpler code, this patch changes many instances of iteritems() to items(), iterkeys() to keys() etc. In other cases, helpers like six.itervalues are used. Reviewed-By: Christian Heimes <cheimes@redhat.com> Reviewed-By: Jan Cholasta <jcholast@redhat.com>
-rwxr-xr-xchecks/check-ra.py3
-rwxr-xr-xdaemons/dnssec/ipa-dnskeysync-replica2
-rwxr-xr-xdaemons/dnssec/ipa-ods-exporter8
-rwxr-xr-xinstall/tools/ipa-csreplica-manage3
-rwxr-xr-xinstall/tools/ipa-replica-manage4
-rwxr-xr-xipa-client/ipa-install/ipa-client-install2
-rw-r--r--ipalib/cli.py7
-rw-r--r--ipalib/config.py2
-rw-r--r--ipalib/errors.py2
-rw-r--r--ipalib/frontend.py4
-rw-r--r--ipalib/messages.py2
-rw-r--r--ipalib/plugable.py6
-rw-r--r--ipalib/plugins/aci.py2
-rw-r--r--ipalib/plugins/baseldap.py50
-rw-r--r--ipalib/plugins/batch.py2
-rw-r--r--ipalib/plugins/config.py4
-rw-r--r--ipalib/plugins/dns.py16
-rw-r--r--ipalib/plugins/otptoken.py2
-rw-r--r--ipalib/plugins/permission.py4
-rw-r--r--ipalib/plugins/service.py5
-rw-r--r--ipalib/plugins/stageuser.py6
-rw-r--r--ipalib/request.py4
-rw-r--r--ipalib/rpc.py4
-rw-r--r--ipalib/util.py2
-rw-r--r--ipaplatform/base/services.py4
-rw-r--r--ipaplatform/redhat/tasks.py4
-rw-r--r--ipapython/config.py2
-rw-r--r--ipapython/dnssec/abshsm.py18
-rw-r--r--ipapython/dnssec/ldapkeydb.py6
-rwxr-xr-xipapython/dnssec/localhsm.py20
-rw-r--r--ipapython/dogtag.py2
-rw-r--r--ipapython/graph.py2
-rw-r--r--ipapython/install/cli.py2
-rw-r--r--ipapython/install/core.py2
-rw-r--r--ipapython/install/util.py4
-rw-r--r--ipapython/ipaldap.py16
-rw-r--r--ipapython/ipautil.py29
-rw-r--r--ipaserver/install/ipa_restore.py2
-rw-r--r--ipaserver/install/plugins/update_managed_permissions.py4
-rw-r--r--ipaserver/install/plugins/update_referint.py2
-rw-r--r--ipaserver/install/schemaupdate.py2
-rw-r--r--ipaserver/install/server/install.py3
-rw-r--r--ipaserver/install/upgradeinstance.py4
-rw-r--r--ipaserver/rpcserver.py4
-rw-r--r--ipatests/test_ipalib/test_backend.py14
-rw-r--r--ipatests/test_ipalib/test_config.py2
-rw-r--r--ipatests/test_ipalib/test_errors.py8
-rw-r--r--ipatests/test_ipalib/test_frontend.py2
-rw-r--r--ipatests/test_ipalib/test_parameters.py4
-rw-r--r--ipatests/test_ipapython/test_dn.py4
-rw-r--r--ipatests/test_ipapython/test_ipautil.py29
-rw-r--r--ipatests/test_ipaserver/test_ldap.py2
-rw-r--r--ipatests/test_webui/ui_driver.py2
-rw-r--r--ipatests/test_xmlrpc/ldaptracker.py2
-rw-r--r--ipatests/test_xmlrpc/test_pwpolicy_plugin.py3
-rw-r--r--ipatests/util.py4
56 files changed, 182 insertions, 172 deletions
diff --git a/checks/check-ra.py b/checks/check-ra.py
index b95a1bace..95e018bff 100755
--- a/checks/check-ra.py
+++ b/checks/check-ra.py
@@ -72,8 +72,7 @@ api.finalize()
ra = api.Backend.ra
def assert_equal(trial, reference):
- keys = reference.keys()
- keys.sort()
+ keys = sorted(reference)
for key in keys:
reference_val = reference[key]
trial_val = trial[key]
diff --git a/daemons/dnssec/ipa-dnskeysync-replica b/daemons/dnssec/ipa-dnskeysync-replica
index d21626808..77b962414 100755
--- a/daemons/dnssec/ipa-dnskeysync-replica
+++ b/daemons/dnssec/ipa-dnskeysync-replica
@@ -60,7 +60,7 @@ def update_metadata_set(log, source_set, target_set):
def find_unwrapping_key(log, localhsm, wrapping_key_uri):
wrap_keys = localhsm.find_keys(uri=wrapping_key_uri)
# find usable unwrapping key with matching ID
- for key_id, key in wrap_keys.iteritems():
+ for key_id, key in wrap_keys.items():
unwrap_keys = localhsm.find_keys(id=key_id, cka_unwrap=True)
if len(unwrap_keys) > 0:
return unwrap_keys.popitem()[1]
diff --git a/daemons/dnssec/ipa-ods-exporter b/daemons/dnssec/ipa-ods-exporter
index e7d30014e..0a8287779 100755
--- a/daemons/dnssec/ipa-ods-exporter
+++ b/daemons/dnssec/ipa-ods-exporter
@@ -96,7 +96,7 @@ def sql2datetimes(row):
'retire': 'idnsSecKeyInactive',
'dead': 'idnsSecKeyDelete'}
times = {}
- for column, key in row2key_map.iteritems():
+ for column, key in row2key_map.items():
if row[column] is not None:
times[key] = sql2datetime(row[column])
return times
@@ -257,7 +257,7 @@ def master2ldap_master_keys_sync(log, ldapkeydb, localhsm):
log.debug('master keys in LDAP after flush: %s', hex_set(ldapkeydb.master_keys))
# synchronize master key metadata to LDAP
- for mkey_id, mkey_local in localhsm.master_keys.iteritems():
+ for mkey_id, mkey_local in localhsm.master_keys.items():
log.debug('synchronizing master key metadata: 0x%s', hexlify(mkey_id))
sync_pkcs11_metadata(log, mkey_local, ldapkeydb.master_keys[mkey_id])
@@ -265,7 +265,7 @@ def master2ldap_master_keys_sync(log, ldapkeydb, localhsm):
enabled_replica_key_ids = set(localhsm.replica_pubkeys_wrap.keys())
log.debug('enabled replica key ids: %s', hex_set(enabled_replica_key_ids))
- for mkey_id, mkey_ldap in ldapkeydb.master_keys.iteritems():
+ for mkey_id, mkey_ldap in ldapkeydb.master_keys.items():
log.debug('processing master key data: 0x%s', hexlify(mkey_id))
# check that all active replicas have own copy of master key
@@ -273,7 +273,7 @@ def master2ldap_master_keys_sync(log, ldapkeydb, localhsm):
for wrapped_entry in mkey_ldap.wrapped_entries:
matching_keys = localhsm.find_keys(
uri=wrapped_entry.single_value['ipaWrappingKey'])
- for matching_key in matching_keys.itervalues():
+ for matching_key in matching_keys.values():
assert matching_key['ipk11label'].startswith(u'dnssec-replica:'), \
'Wrapped key "%s" refers to PKCS#11 URI "%s" which is ' \
'not a know DNSSEC replica key: label "%s" does not start ' \
diff --git a/install/tools/ipa-csreplica-manage b/install/tools/ipa-csreplica-manage
index eec8bb2c8..8cf621ec3 100755
--- a/install/tools/ipa-csreplica-manage
+++ b/install/tools/ipa-csreplica-manage
@@ -23,7 +23,6 @@ import sys
import os
from ipapython.ipa_log_manager import *
-
from ipaserver.install import (replication, installutils, bindinstance,
cainstance, certs)
from ipalib import api, errors
@@ -112,7 +111,7 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose):
conn.unbind()
if not replica:
- for k, p in peers.iteritems():
+ for k, p in peers.items():
print '%s: %s' % (k, p[0])
return
diff --git a/install/tools/ipa-replica-manage b/install/tools/ipa-replica-manage
index f26c6ab60..9688dc4e7 100755
--- a/install/tools/ipa-replica-manage
+++ b/install/tools/ipa-replica-manage
@@ -183,12 +183,12 @@ def list_replicas(realm, host, replica, dirman_passwd, verbose, nolookup=False):
peers[ent.single_value['cn']] = config_string.split(':')
if not replica:
- for k, p in peers.iteritems():
+ for k, p in peers.items():
print '%s: %s' % (k, p[0])
return
# ok we are being ask for info about a specific replica
- for k, p in peers.iteritems():
+ for k, p in peers.items():
if replica == k:
is_replica = True
if p[0] == 'winsync':
diff --git a/ipa-client/ipa-install/ipa-client-install b/ipa-client/ipa-install/ipa-client-install
index bce9f3ce1..b6e6fa02e 100755
--- a/ipa-client/ipa-install/ipa-client-install
+++ b/ipa-client/ipa-install/ipa-client-install
@@ -1427,7 +1427,7 @@ def configure_sshd_config(fstore, options):
for candidate in candidates:
args = ['sshd', '-t', '-f', paths.DEV_NULL]
- for item in candidate.iteritems():
+ for item in candidate.items():
args.append('-o')
args.append('%s=%s' % item)
diff --git a/ipalib/cli.py b/ipalib/cli.py
index 9c6d570f7..afad07937 100644
--- a/ipalib/cli.py
+++ b/ipalib/cli.py
@@ -764,9 +764,8 @@ class help(frontend.Local):
self._builtins.append(c)
# compute maximum topic length
- self._mtl = max(
- len(s) for s in (self._topics.keys() + [c.name for c in self._builtins])
- )
+ topics = list(self._topics) + [c.name for c in self._builtins]
+ self._mtl = max(len(s) for s in topics)
super(help, self)._on_finalize()
@@ -1126,7 +1125,7 @@ class cli(backend.Executioner):
"""
Decode param values if appropriate.
"""
- for (key, value) in kw.iteritems():
+ for (key, value) in kw.items():
yield (key, self.Backend.textui.decode(value))
def build_parser(self, cmd):
diff --git a/ipalib/config.py b/ipalib/config.py
index 90933b7a2..144127467 100644
--- a/ipalib/config.py
+++ b/ipalib/config.py
@@ -330,7 +330,7 @@ class Env(object):
:param kw: Variables provides as keyword arguments.
"""
i = 0
- for (key, value) in kw.iteritems():
+ for (key, value) in kw.items():
if key not in self:
self[key] = value
i += 1
diff --git a/ipalib/errors.py b/ipalib/errors.py
index e7b016674..2f7c77c1c 100644
--- a/ipalib/errors.py
+++ b/ipalib/errors.py
@@ -117,7 +117,7 @@ class PrivateError(StandardError):
def __init__(self, **kw):
self.msg = self.format % kw
self.kw = kw
- for (key, value) in kw.iteritems():
+ for (key, value) in kw.items():
assert not hasattr(self, key), 'conflicting kwarg %s.%s = %r' % (
self.__class__.__name__, key, value,
)
diff --git a/ipalib/frontend.py b/ipalib/frontend.py
index 16ec9cce8..8cc0dd7b2 100644
--- a/ipalib/frontend.py
+++ b/ipalib/frontend.py
@@ -614,7 +614,7 @@ class Command(HasParam):
{'last': u'DOE', 'first': u'john'}
"""
return dict(
- (k, self.params[k].normalize(v)) for (k, v) in kw.iteritems()
+ (k, self.params[k].normalize(v)) for (k, v) in kw.items()
)
def convert(self, **kw):
@@ -634,7 +634,7 @@ class Command(HasParam):
{'two': u'2', 'one': 1}
"""
return dict(
- (k, self.params[k].convert(v)) for (k, v) in kw.iteritems()
+ (k, self.params[k].convert(v)) for (k, v) in kw.items()
)
def __convert_iter(self, kw):
diff --git a/ipalib/messages.py b/ipalib/messages.py
index 4615cbc2b..c932b30f7 100644
--- a/ipalib/messages.py
+++ b/ipalib/messages.py
@@ -85,7 +85,7 @@ def process_message_arguments(obj, format=None, message=None, **kw):
obj.forwarded = True
obj.msg = message
obj.strerror = message
- for (key, value) in kw.iteritems():
+ for (key, value) in kw.items():
assert not hasattr(obj, key), 'conflicting kwarg %s.%s = %r' % (
name, key, value,
)
diff --git a/ipalib/plugable.py b/ipalib/plugable.py
index 17c78dce6..3f65f6736 100644
--- a/ipalib/plugable.py
+++ b/ipalib/plugable.py
@@ -659,7 +659,7 @@ class API(ReadOnly):
sub_d = self.__plugins.get(base, {})
members = []
- for klass in sub_d.itervalues():
+ for klass in sub_d.values():
try:
instance = plugins[klass]
except KeyError:
@@ -673,7 +673,7 @@ class API(ReadOnly):
assert not hasattr(self, name)
setattr(self, name, NameSpace(members))
- for klass, instance in plugins.iteritems():
+ for klass, instance in plugins.items():
if not production_mode:
assert instance.api is self
if klass.finalize_early or not self.env.plugins_on_demand:
@@ -682,7 +682,7 @@ class API(ReadOnly):
assert islocked(instance)
self.__finalized = True
- self.plugins = tuple((k, tuple(v)) for k, v in plugin_info.iteritems())
+ self.plugins = tuple((k, tuple(v)) for k, v in plugin_info.items())
if not production_mode:
lock(self)
diff --git a/ipalib/plugins/aci.py b/ipalib/plugins/aci.py
index 0ff28b84e..cdc8f7092 100644
--- a/ipalib/plugins/aci.py
+++ b/ipalib/plugins/aci.py
@@ -223,7 +223,7 @@ def _make_aci(ldap, current, aciname, kw):
if 'aciprefix' not in kw:
raise errors.ValidationError(name='aciprefix', error=_('ACI prefix is required'))
- if sum(valid.itervalues()) == 0:
+ if sum(valid.values()) == 0:
raise errors.ValidationError(name='target', error=_('at least one of: type, filter, subtree, targetgroup, attrs or memberof are required'))
if valid['filter'] + valid['memberof'] > 1:
diff --git a/ipalib/plugins/baseldap.py b/ipalib/plugins/baseldap.py
index a8525e81e..59d39c403 100644
--- a/ipalib/plugins/baseldap.py
+++ b/ipalib/plugins/baseldap.py
@@ -232,7 +232,7 @@ def entry_from_entry(entry, newentry):
"""
# Wipe out the current data
- for e in entry.keys():
+ for e in list(entry):
del entry[e]
# Re-populate it with new wentry
@@ -242,7 +242,7 @@ def entry_from_entry(entry, newentry):
def entry_to_dict(entry, **options):
if options.get('raw', False):
result = {}
- for attr in entry.iterkeys():
+ for attr in entry:
if attr.lower() == 'attributelevelrights':
value = entry[attr]
elif entry.conn.get_attribute_type(attr) is str:
@@ -256,7 +256,7 @@ def entry_to_dict(entry, **options):
pass
result[attr] = value
else:
- result = dict((k.lower(), v) for (k, v) in entry.iteritems())
+ result = dict((k.lower(), v) for (k, v) in entry.items())
if options.get('all', False):
result['dn'] = entry.dn
return result
@@ -793,10 +793,10 @@ class LDAPObject(Object):
attrs = self.api.Backend.ldap2.schema.attribute_types(objectclasses)
attrlist = []
# Go through the MUST first
- for (oid, attr) in attrs[0].iteritems():
+ for (oid, attr) in attrs[0].items():
attrlist.append(attr.names[0].lower())
# And now the MAY
- for (oid, attr) in attrs[1].iteritems():
+ for (oid, attr) in attrs[1].items():
attrlist.append(attr.names[0].lower())
json_dict['aciattrs'] = attrlist
attrlist.sort()
@@ -809,7 +809,7 @@ class LDAPObject(Object):
# addattr can cause parameters to have more than one value even if not defined
# as multivalue, make sure this isn't the case
def _check_single_value_attrs(params, entry_attrs):
- for (a, v) in entry_attrs.iteritems():
+ for (a, v) in entry_attrs.items():
if isinstance(v, (list, tuple)) and len(v) > 1:
if a in params and not params[a].multivalue:
raise errors.OnlyOneValueAllowed(attr=a)
@@ -817,7 +817,7 @@ def _check_single_value_attrs(params, entry_attrs):
# setattr or --option='' can cause parameters to be empty that are otherwise
# required, make sure we enforce that.
def _check_empty_attrs(params, entry_attrs):
- for (a, v) in entry_attrs.iteritems():
+ for (a, v) in entry_attrs.items():
if v is None or (isinstance(v, six.string_types) and len(v) == 0):
if a in params and params[a].required:
raise errors.RequirementError(name=a)
@@ -839,7 +839,7 @@ def _check_limit_object_class(attributes, attrs, allow_only):
return
limitattrs = deepcopy(attrs)
# Go through the MUST first
- for (oid, attr) in attributes[0].iteritems():
+ for (oid, attr) in attributes[0].items():
if attr.names[0].lower() in limitattrs:
if not allow_only:
raise errors.ObjectclassViolation(
@@ -847,7 +847,7 @@ def _check_limit_object_class(attributes, attrs, allow_only):
attribute=attr.names[0].lower()))
limitattrs.remove(attr.names[0].lower())
# And now the MAY
- for (oid, attr) in attributes[1].iteritems():
+ for (oid, attr) in attributes[1].items():
if attr.names[0].lower() in limitattrs:
if not allow_only:
raise errors.ObjectclassViolation(
@@ -1015,9 +1015,9 @@ last, after all sets and adds."""),
setdict = self._convert_2_dict(ldap, options.get('setattr', []))
deldict = self._convert_2_dict(ldap, options.get('delattr', []))
- setattrs = set(setdict.keys())
- addattrs = set(adddict.keys())
- delattrs = set(deldict.keys())
+ setattrs = set(setdict)
+ addattrs = set(adddict)
+ delattrs = set(deldict)
if dn is None:
direct_add = addattrs
@@ -1029,7 +1029,7 @@ last, after all sets and adds."""),
direct_del = setattrs & delattrs
needldapattrs = list((addattrs | delattrs) - setattrs)
- for attr, val in setdict.iteritems():
+ for attr, val in setdict.items():
entry_attrs[attr] = val
for attr in direct_add:
@@ -1063,7 +1063,7 @@ last, after all sets and adds."""),
# Provide a nice error message when user tries to delete an
# attribute that does not exist on the entry (and user is not
# adding it)
- names = set(n.lower() for n in old_entry.keys())
+ names = set(n.lower() for n in old_entry)
del_nonexisting = delattrs - (names | setattrs | addattrs)
if del_nonexisting:
raise errors.ValidationError(name=del_nonexisting.pop(),
@@ -1229,8 +1229,8 @@ class LDAPCreate(BaseLDAPCommand, crud.Create):
*keys, **options)
_check_single_value_attrs(self.params, entry_attrs)
- _check_limit_object_class(self.api.Backend.ldap2.schema.attribute_types(self.obj.limit_object_classes), entry_attrs.keys(), allow_only=True)
- _check_limit_object_class(self.api.Backend.ldap2.schema.attribute_types(self.obj.disallow_object_classes), entry_attrs.keys(), allow_only=False)
+ _check_limit_object_class(self.api.Backend.ldap2.schema.attribute_types(self.obj.limit_object_classes), list(entry_attrs), allow_only=True)
+ _check_limit_object_class(self.api.Backend.ldap2.schema.attribute_types(self.obj.disallow_object_classes), list(entry_attrs), allow_only=False)
try:
self._exc_wrapper(keys, options, ldap.add_entry)(entry_attrs)
@@ -1469,8 +1469,8 @@ class LDAPUpdate(LDAPQuery, crud.Update):
self, ldap, entry_attrs.dn, entry_attrs, attrs_list,
*keys, **options)
- _check_limit_object_class(self.api.Backend.ldap2.schema.attribute_types(self.obj.limit_object_classes), entry_attrs.keys(), allow_only=True)
- _check_limit_object_class(self.api.Backend.ldap2.schema.attribute_types(self.obj.disallow_object_classes), entry_attrs.keys(), allow_only=False)
+ _check_limit_object_class(self.api.Backend.ldap2.schema.attribute_types(self.obj.limit_object_classes), list(entry_attrs), allow_only=True)
+ _check_limit_object_class(self.api.Backend.ldap2.schema.attribute_types(self.obj.disallow_object_classes), list(entry_attrs), allow_only=False)
rdnupdate = False
try:
@@ -1505,7 +1505,7 @@ class LDAPUpdate(LDAPQuery, crud.Update):
# mean an error occurred, just that there were no other updates to
# perform.
update = self._exc_wrapper(keys, options, ldap.get_entry)(
- entry_attrs.dn, entry_attrs.keys())
+ entry_attrs.dn, list(entry_attrs))
update.update(entry_attrs)
self._exc_wrapper(keys, options, ldap.update_entry)(update)
@@ -1727,7 +1727,7 @@ class LDAPAddMember(LDAPModMember):
assert isinstance(dn, DN)
completed = 0
- for (attr, objs) in member_dns.iteritems():
+ for (attr, objs) in member_dns.items():
for ldap_obj_name in objs:
for m_dn in member_dns[attr][ldap_obj_name]:
assert isinstance(m_dn, DN)
@@ -1828,8 +1828,8 @@ class LDAPRemoveMember(LDAPModMember):
assert isinstance(dn, DN)
completed = 0
- for (attr, objs) in member_dns.iteritems():
- for ldap_obj_name, m_dns in objs.iteritems():
+ for (attr, objs) in member_dns.items():
+ for ldap_obj_name, m_dns in objs.items():
for m_dn in m_dns:
assert isinstance(m_dn, DN)
if not m_dn:
@@ -2376,7 +2376,7 @@ class LDAPModAttribute(LDAPQuery):
try:
update = self._exc_wrapper(keys, options, ldap.get_entry)(
- entry_attrs.dn, entry_attrs.keys())
+ entry_attrs.dn, list(entry_attrs))
self._update_attrs(update, entry_attrs)
self._exc_wrapper(keys, options, ldap.update_entry)(update)
@@ -2425,7 +2425,7 @@ class LDAPAddAttribute(LDAPModAttribute):
msg_summary = _('added attribute value to entry %(value)')
def _update_attrs(self, update, entry_attrs):
- for name, value in entry_attrs.iteritems():
+ for name, value in entry_attrs.items():
old_value = set(update.get(name, []))
value_to_add = set(value)
@@ -2442,7 +2442,7 @@ class LDAPRemoveAttribute(LDAPModAttribute):
msg_summary = _('removed attribute values from entry %(value)')
def _update_attrs(self, update, entry_attrs):
- for name, value in entry_attrs.iteritems():
+ for name, value in entry_attrs.items():
old_value = set(update.get(name, []))
value_to_remove = set(value)
diff --git a/ipalib/plugins/batch.py b/ipalib/plugins/batch.py
index 9b9ab6544..ddf24839d 100644
--- a/ipalib/plugins/batch.py
+++ b/ipalib/plugins/batch.py
@@ -97,7 +97,7 @@ class batch(Command):
if name not in self.Command:
raise errors.CommandError(name=name)
a, kw = arg['params']
- newkw = dict((str(k), v) for k, v in kw.iteritems())
+ newkw = dict((str(k), v) for k, v in kw.items())
params = api.Command[name].args_options_2_params(*a, **newkw)
newkw.setdefault('version', options['version'])
diff --git a/ipalib/plugins/config.py b/ipalib/plugins/config.py
index 6267313d5..c8153c311 100644
--- a/ipalib/plugins/config.py
+++ b/ipalib/plugins/config.py
@@ -256,8 +256,8 @@ class config_mod(LDAPUpdate):
if 'ipagroupsearchfields' in entry_attrs:
kw['ipagroupsearchfields'] = 'ipagroupobjectclasses'
if kw:
- config = ldap.get_ipa_config(kw.values())
- for (k, v) in kw.iteritems():
+ config = ldap.get_ipa_config(list(kw.values()))
+ for (k, v) in kw.items():
allowed_attrs = ldap.get_allowed_attributes(config[v])
fields = entry_attrs[k].split(',')
for a in fields:
diff --git a/ipalib/plugins/dns.py b/ipalib/plugins/dns.py
index 10c4987af..6044d3823 100644
--- a/ipalib/plugins/dns.py
+++ b/ipalib/plugins/dns.py
@@ -1641,7 +1641,7 @@ def _create_idn_filter(cmd, ldap, *args, **options):
search_kw = {}
attr_extra_filters = []
- for attr, value in cmd.args_options_2_entry(**options).iteritems():
+ for attr, value in cmd.args_options_2_entry(**options).items():
if not isinstance(value, list):
value = [value]
for i, v in enumerate(value):
@@ -3245,11 +3245,11 @@ class dnsrecord(LDAPObject):
"""
rrattrs = {}
if old_entry is not None:
- old_rrattrs = dict((key, value) for key, value in old_entry.iteritems()
+ old_rrattrs = dict((key, value) for key, value in old_entry.items()
if key in self.params and
isinstance(self.params[key], DNSRecord))
rrattrs.update(old_rrattrs)
- new_rrattrs = dict((key, value) for key, value in entry_attrs.iteritems()
+ new_rrattrs = dict((key, value) for key, value in entry_attrs.items()
if key in self.params and
isinstance(self.params[key], DNSRecord))
rrattrs.update(new_rrattrs)
@@ -3267,7 +3267,7 @@ class dnsrecord(LDAPObject):
'(RFC 2136, section 1.1.5)'))
if any(rrvalue is not None
and rrattr != 'cnamerecord'
- for rrattr, rrvalue in rrattrs.iteritems()):
+ for rrattr, rrvalue in rrattrs.items()):
raise errors.ValidationError(name='cnamerecord',
error=_('CNAME record is not allowed to coexist '
'with any other record (RFC 1034, section 3.6.2)'))
@@ -3327,7 +3327,7 @@ class dnsrecord(LDAPObject):
# all records were deleted => name should not exist in DNS
return None
- for attr, value in entry_attrs.iteritems():
+ for attr, value in entry_attrs.items():
if not attr.endswith(record_attr_suf):
continue
@@ -3444,7 +3444,7 @@ class dnsrecord(LDAPObject):
# name should not exist => ask for A record and check result
ldap_rrsets = {dns.rdatatype.from_text('A'): None}
- for rdtype, ldap_rrset in ldap_rrsets.iteritems():
+ for rdtype, ldap_rrset in ldap_rrsets.items():
try:
self.wait_for_modified_attr(ldap_rrset, rdtype, dns_name)
@@ -3479,7 +3479,7 @@ class dnsrecord(LDAPObject):
:param entries:
Dict {(dns_domain, dns_name): entry_for_wait_for_modified_attrs}
'''
- for entry_name, entry in entries.iteritems():
+ for entry_name, entry in entries.items():
dns_domain = entry_name[0]
dns_name = entry_name[1].derelativize(dns_domain)
self.wait_for_modified_attrs(entry, dns_name, dns_domain)
@@ -3691,7 +3691,7 @@ class dnsrecord_add(LDAPCreate):
# already merged in pre_callback
ldap = self.obj.backend
entry_attrs = self.obj.get_record_entry_attrs(call_args[0])
- update = ldap.get_entry(entry_attrs.dn, entry_attrs.keys())
+ update = ldap.get_entry(entry_attrs.dn, list(entry_attrs))
update.update(entry_attrs)
ldap.update_entry(update, **call_kwargs)
return
diff --git a/ipalib/plugins/otptoken.py b/ipalib/plugins/otptoken.py
index eb3e3f977..3c2cb9309 100644
--- a/ipalib/plugins/otptoken.py
+++ b/ipalib/plugins/otptoken.py
@@ -161,7 +161,7 @@ class otptoken(LDAPObject):
doc=_('Type of the token'),
default=u'totp',
autofill=True,
- values=tuple(TOKEN_TYPES.keys() + [x.upper() for x in TOKEN_TYPES]),
+ values=tuple(list(TOKEN_TYPES) + [x.upper() for x in TOKEN_TYPES]),
flags=('virtual_attribute', 'no_update'),
),
Str('description?',
diff --git a/ipalib/plugins/permission.py b/ipalib/plugins/permission.py
index 9544cd292..7a2e14c72 100644
--- a/ipalib/plugins/permission.py
+++ b/ipalib/plugins/permission.py
@@ -1148,7 +1148,7 @@ class permission_mod(baseldap.LDAPUpdate):
# Since `entry` only contains the attributes we are currently changing,
# it cannot be used directly to generate an ACI.
# First we need to copy the original data into it.
- for key, value in old_entry.iteritems():
+ for key, value in old_entry.items():
if (key not in options and
key != 'cn' and
key not in self.obj.attribute_members):
@@ -1355,7 +1355,7 @@ class permission_find(baseldap.LDAPSearch):
for entry in entries:
if options.get('pkey_only'):
- for opt_name in entry.keys():
+ for opt_name in list(entry):
if opt_name != self.obj.primary_key.name:
del entry[opt_name]
else:
diff --git a/ipalib/plugins/service.py b/ipalib/plugins/service.py
index 6d0299164..d20f52876 100644
--- a/ipalib/plugins/service.py
+++ b/ipalib/plugins/service.py
@@ -22,6 +22,7 @@
import base64
import os
+
from ipalib import api, errors, util
from ipalib import Str, Flag, Bytes, StrEnum, Bool
from ipalib.plugable import Registry
@@ -315,7 +316,7 @@ def check_required_principal(ldap, hostname, service):
def update_krbticketflags(ldap, entry_attrs, attrs_list, options, existing):
add = remove = 0
- for (name, value) in _ticket_flags_map.iteritems():
+ for (name, value) in _ticket_flags_map.items():
if name not in options:
continue
if options[name]:
@@ -356,7 +357,7 @@ def set_kerberos_attrs(entry_attrs, options):
all_opt = options.get('all', False)
- for (name, value) in _ticket_flags_map.iteritems():
+ for (name, value) in _ticket_flags_map.items():
if name in options or all_opt:
entry_attrs[name] = bool(ticket_flags & value)
diff --git a/ipalib/plugins/stageuser.py b/ipalib/plugins/stageuser.py
index f3788538a..2a232d1e3 100644
--- a/ipalib/plugins/stageuser.py
+++ b/ipalib/plugins/stageuser.py
@@ -639,7 +639,7 @@ class stageuser_activate(LDAPQuery):
)
except errors.NotFound:
self.obj.handle_not_found(*args)
- entry_attrs = dict((k.lower(), v) for (k, v) in entry_attrs.iteritems())
+ entry_attrs = dict((k.lower(), v) for (k, v) in entry_attrs.items())
# Check it does not exist an active entry with the same RDN
active_dn = DN(staging_dn[0], api.env.container_user, api.env.basedn)
@@ -660,7 +660,7 @@ class stageuser_activate(LDAPQuery):
# Time to build the new entry
result_entry = {'dn' : active_dn}
new_entry_attrs = self.__dict_new_entry()
- for (attr, values) in entry_attrs.iteritems():
+ for (attr, values) in entry_attrs.items():
self.__merge_values(args, options, entry_attrs, new_entry_attrs, attr)
result_entry[attr] = values
@@ -670,7 +670,7 @@ class stageuser_activate(LDAPQuery):
if result_entry['description'] == NO_UPG_MAGIC:
del result_entry['description']
- for (k,v) in new_entry_attrs.iteritems():
+ for (k, v) in new_entry_attrs.items():
self.log.debug("new entry: k=%r and v=%r)" % (k, v))
self._build_new_entry(ldap, staging_dn, entry_attrs, new_entry_attrs)
diff --git a/ipalib/request.py b/ipalib/request.py
index a83b35403..5a6baba42 100644
--- a/ipalib/request.py
+++ b/ipalib/request.py
@@ -51,8 +51,8 @@ def destroy_context():
"""
Delete all attributes on thread-local `request.context`.
"""
- # need to use .values(), 'cos value.disconnect modifies the dict
- for value in context.__dict__.values():
+ # need to use a list of values, 'cos value.disconnect modifies the dict
+ for value in list(context.__dict__.values()):
if isinstance(value, Connection):
value.disconnect()
context.__dict__.clear()
diff --git a/ipalib/rpc.py b/ipalib/rpc.py
index 0dc897a08..b76d27885 100644
--- a/ipalib/rpc.py
+++ b/ipalib/rpc.py
@@ -159,7 +159,7 @@ def xml_wrap(value, version):
return tuple(xml_wrap(v, version) for v in value)
if isinstance(value, dict):
return dict(
- (k, xml_wrap(v, version)) for (k, v) in value.iteritems()
+ (k, xml_wrap(v, version)) for (k, v) in value.items()
)
if type(value) is str:
return Binary(value)
@@ -213,7 +213,7 @@ def xml_unwrap(value, encoding='UTF-8'):
return DNSName(value['__dns_name__'])
else:
return dict(
- (k, xml_unwrap(v, encoding)) for (k, v) in value.iteritems()
+ (k, xml_unwrap(v, encoding)) for (k, v) in value.items()
)
if type(value) is str:
return value.decode(encoding)
diff --git a/ipalib/util.py b/ipalib/util.py
index e38ddbbdc..3b8e59216 100644
--- a/ipalib/util.py
+++ b/ipalib/util.py
@@ -51,7 +51,7 @@ def json_serialize(obj):
if isinstance(obj, (list, tuple)):
return [json_serialize(o) for o in obj]
if isinstance(obj, dict):
- return dict((k, json_serialize(v)) for (k, v) in obj.iteritems())
+ return {k: json_serialize(v) for (k, v) in obj.items()}
if isinstance(obj, (bool, float, int, long, unicode, NoneType)):
return obj
if isinstance(obj, str):
diff --git a/ipaplatform/base/services.py b/ipaplatform/base/services.py
index 56e959e91..6dcb26bb9 100644
--- a/ipaplatform/base/services.py
+++ b/ipaplatform/base/services.py
@@ -28,6 +28,8 @@ import json
import time
import collections
+import six
+
import ipalib
from ipapython import ipautil
from ipaplatform.paths import paths
@@ -78,7 +80,7 @@ class KnownServices(collections.Mapping):
return len(self.__d)
def __call__(self):
- return self.__d.itervalues()
+ return six.itervalues(self.__d)
def __getattr__(self, name):
try:
diff --git a/ipaplatform/redhat/tasks.py b/ipaplatform/redhat/tasks.py
index 5ae2be16f..b211a31ee 100644
--- a/ipaplatform/redhat/tasks.py
+++ b/ipaplatform/redhat/tasks.py
@@ -361,7 +361,7 @@ class RedHatTaskNamespace(BaseTaskNamespace):
def set_selinux_booleans(self, required_settings, backup_func=None):
def get_setsebool_args(changes):
args = [paths.SETSEBOOL, "-P"]
- args.extend(["%s=%s" % update for update in changes.iteritems()])
+ args.extend(["%s=%s" % update for update in changes.items()])
return args
@@ -370,7 +370,7 @@ class RedHatTaskNamespace(BaseTaskNamespace):
updated_vars = {}
failed_vars = {}
- for setting, state in required_settings.iteritems():
+ for setting, state in required_settings.items():
if state is None:
continue
try:
diff --git a/ipapython/config.py b/ipapython/config.py
index d586d66d6..76168f29e 100644
--- a/ipapython/config.py
+++ b/ipapython/config.py
@@ -105,7 +105,7 @@ class IPAOptionParser(OptionParser):
all_opts_dict = dict([ (o.dest, o) for o in self._get_all_options() if hasattr(o, 'sensitive') ])
safe_opts_dict = {}
- for option, value in opts.__dict__.iteritems():
+ for option, value in opts.__dict__.items():
if all_opts_dict[option].sensitive != True:
safe_opts_dict[option] = value
diff --git a/ipapython/dnssec/abshsm.py b/ipapython/dnssec/abshsm.py
index 80292e5a7..156bcf32c 100644
--- a/ipapython/dnssec/abshsm.py
+++ b/ipapython/dnssec/abshsm.py
@@ -41,7 +41,7 @@ attrs_id2name = {
_ipap11helper.CKA_WRAP_WITH_TRUSTED: 'ipk11wrapwithtrusted',
}
-attrs_name2id = dict(zip(attrs_id2name.values(), attrs_id2name.keys()))
+attrs_name2id = {v: k for k, v in attrs_id2name.items()}
# attribute:
# http://www.freeipa.org/page/V4/PKCS11_in_LDAP/Schema#ipk11KeyType
@@ -53,7 +53,7 @@ keytype_name2id = {
"aes": _ipap11helper.KEY_TYPE_AES,
}
-keytype_id2name = dict(zip(keytype_name2id.values(), keytype_name2id.keys()))
+keytype_id2name = {v: k for k, v in keytype_name2id.items()}
wrappingmech_name2id = {
"rsaPkcs": _ipap11helper.MECH_RSA_PKCS,
@@ -62,8 +62,7 @@ wrappingmech_name2id = {
"aesKeyWrapPad": _ipap11helper.MECH_AES_KEY_WRAP_PAD
}
-wrappingmech_id2name = dict(zip(wrappingmech_name2id.values(),
- wrappingmech_name2id.keys()))
+wrappingmech_id2name = {v: k for k, v in wrappingmech_name2id.items()}
bool_attr_names = set([
@@ -105,8 +104,7 @@ modifiable_attrs_id2name = {
_ipap11helper.CKA_WRAP: 'ipk11wrap',
}
-modifiable_attrs_name2id = dict(zip(modifiable_attrs_id2name.values(),
- modifiable_attrs_id2name.keys()))
+modifiable_attrs_name2id = {v: k for k, v in modifiable_attrs_id2name.items()}
def sync_pkcs11_metadata(log, source, target):
"""sync ipk11 metadata from source object to target object"""
@@ -148,7 +146,7 @@ def ldap2p11helper_api_params(ldap_key):
"ipk11wrapwithtrusted": "cka_wrap_with_trusted"
}
- for ldap_name, p11h_name in direct_param_map.iteritems():
+ for ldap_name, p11h_name in direct_param_map.items():
if ldap_name in ldap_key:
unwrap_params[p11h_name] = ldap_key[ldap_name]
@@ -159,7 +157,7 @@ def ldap2p11helper_api_params(ldap_key):
"ipawrappingmech": ("wrapping_mech", wrappingmech_name2id),
}
- for ldap_name, rules in indirect_param_map.iteritems():
+ for ldap_name, rules in indirect_param_map.items():
p11h_name, mapping = rules
if ldap_name in ldap_key:
unwrap_params[p11h_name] = mapping[ldap_key[ldap_name]]
@@ -170,7 +168,7 @@ def ldap2p11helper_api_params(ldap_key):
class AbstractHSM(object):
def _filter_replica_keys(self, all_keys):
replica_keys = {}
- for key_id, key in all_keys.iteritems():
+ for key_id, key in all_keys.items():
if not key['ipk11label'].startswith('dnssec-replica:'):
continue
replica_keys[key_id] = key
@@ -178,7 +176,7 @@ class AbstractHSM(object):
def _filter_zone_keys(self, all_keys):
zone_keys = {}
- for key_id, key in all_keys.iteritems():
+ for key_id, key in all_keys.items():
if key['ipk11label'] == u'dnssec-master' \
or key['ipk11label'].startswith('dnssec-replica:'):
continue
diff --git a/ipapython/dnssec/ldapkeydb.py b/ipapython/dnssec/ldapkeydb.py
index 86a7d0ac1..806999375 100644
--- a/ipapython/dnssec/ldapkeydb.py
+++ b/ipapython/dnssec/ldapkeydb.py
@@ -128,7 +128,7 @@ class Key(collections.MutableMapping):
def __iter__(self):
"""generates list of ipa names of all PKCS#11 attributes present in the object"""
- for ipa_name in self.entry.keys():
+ for ipa_name in list(self.entry.keys()):
lowercase = ipa_name.lower()
if lowercase in attrs_name2id:
yield lowercase
@@ -247,7 +247,7 @@ class LdapKeyDB(AbstractHSM):
for cache in [self.cache_masterkeys, self.cache_replica_pubkeys_wrap,
self.cache_zone_keypairs]:
if cache:
- for key in cache.itervalues():
+ for key in cache.values():
self._update_key(key)
def flush(self):
@@ -326,7 +326,7 @@ class LdapKeyDB(AbstractHSM):
keys = self._get_key_dict(MasterKey,
'(&(objectClass=ipk11SecretKey)(|(ipk11UnWrap=TRUE)(!(ipk11UnWrap=*)))(ipk11Label=dnssec-master))')
- for key in keys.itervalues():
+ for key in keys.values():
prefix = 'dnssec-master'
assert key['ipk11label'] == prefix, \
'secret key dn="%s" ipk11id=0x%s ipk11label="%s" with ipk11UnWrap = TRUE does not have '\
diff --git a/ipapython/dnssec/localhsm.py b/ipapython/dnssec/localhsm.py
index 412b55df9..d3b4ae15c 100755
--- a/ipapython/dnssec/localhsm.py
+++ b/ipapython/dnssec/localhsm.py
@@ -69,7 +69,7 @@ class Key(collections.MutableMapping):
def __iter__(self):
"""generates list of ipa names of all attributes present in the object"""
- for pkcs11_id, ipa_name in attrs_id2name.iteritems():
+ for pkcs11_id, ipa_name in attrs_id2name.items():
try:
self.p11.get_attribute(self.handle, pkcs11_id)
except _ipap11helper.NotFound:
@@ -84,11 +84,7 @@ class Key(collections.MutableMapping):
return cnt
def __str__(self):
- d = {}
- for ipa_name, value in self.iteritems():
- d[ipa_name] = value
-
- return str(d)
+ return str(dict(self))
def __repr__(self):
return self.__str__()
@@ -139,7 +135,7 @@ class LocalHSM(AbstractHSM):
"""Get all usable DNSSEC master keys"""
keys = self.find_keys(objclass=_ipap11helper.KEY_CLASS_SECRET_KEY, label=u'dnssec-master', cka_unwrap=True)
- for key in keys.itervalues():
+ for key in keys.values():
prefix = 'dnssec-master'
assert key['ipk11label'] == prefix, \
'secret key ipk11id=0x%s ipk11label="%s" with ipk11UnWrap = TRUE does not have '\
@@ -198,34 +194,34 @@ if __name__ == '__main__':
print 'replica public keys: CKA_WRAP = TRUE'
print '===================================='
- for pubkey_id, pubkey in localhsm.replica_pubkeys_wrap.iteritems():
+ for pubkey_id, pubkey in localhsm.replica_pubkeys_wrap.items():
print hexlify(pubkey_id)
pprint(pubkey)
print ''
print 'replica public keys: all'
print '========================'
- for pubkey_id, pubkey in localhsm.replica_pubkeys.iteritems():
+ for pubkey_id, pubkey in localhsm.replica_pubkeys.items():
print hexlify(pubkey_id)
pprint(pubkey)
print ''
print 'master keys'
print '==========='
- for mkey_id, mkey in localhsm.master_keys.iteritems():
+ for mkey_id, mkey in localhsm.master_keys.items():
print hexlify(mkey_id)
pprint(mkey)
print ''
print 'zone public keys'
print '================'
- for key_id, key in localhsm.zone_pubkeys.iteritems():
+ for key_id, key in localhsm.zone_pubkeys.items():
print hexlify(key_id)
pprint(key)
print ''
print 'zone private keys'
print '================='
- for key_id, key in localhsm.zone_privkeys.iteritems():
+ for key_id, key in localhsm.zone_privkeys.items():
print hexlify(key_id)
pprint(key)
diff --git a/ipapython/dogtag.py b/ipapython/dogtag.py
index fc4154719..fe951cf5b 100644
--- a/ipapython/dogtag.py
+++ b/ipapython/dogtag.py
@@ -320,7 +320,7 @@ def _httplib_request(
headers = headers or {}
if (
method == 'POST'
- and 'content-type' not in (str(k).lower() for k in headers.viewkeys())
+ and 'content-type' not in (str(k).lower() for k in headers)
):
headers['content-type'] = 'application/x-www-form-urlencoded'
diff --git a/ipapython/graph.py b/ipapython/graph.py
index e27249466..b4373abea 100644
--- a/ipapython/graph.py
+++ b/ipapython/graph.py
@@ -44,7 +44,7 @@ class Graph():
# delete _adjacencies
del self._adj[vertex]
- for key, _adj in self._adj.iteritems():
+ for key, _adj in self._adj.items():
_adj[:] = [v for v in _adj if v != vertex]
# delete edges
diff --git a/ipapython/install/cli.py b/ipapython/install/cli.py
index 1ba9a815c..54ca58d26 100644
--- a/ipapython/install/cli.py
+++ b/ipapython/install/cli.py
@@ -145,7 +145,7 @@ class ConfigureTool(admintool.AdminTool):
help="unattended (un)installation never prompts the user",
)
- for group, opt_group in groups.iteritems():
+ for group, opt_group in groups.items():
parser.add_option_group(opt_group)
super(ConfigureTool, cls).add_options(parser,
diff --git a/ipapython/install/core.py b/ipapython/install/core.py
index c313c278e..dac8883fe 100644
--- a/ipapython/install/core.py
+++ b/ipapython/install/core.py
@@ -229,7 +229,7 @@ class Configurable(object):
setattr(self, name, value)
if kwargs:
- extra = sorted(kwargs.keys())
+ extra = sorted(kwargs)
raise TypeError(
"{0}() got {1} unexpected keyword arguments: {2}".format(
type(self).__name__,
diff --git a/ipapython/install/util.py b/ipapython/install/util.py
index 58da7bb77..12530d45a 100644
--- a/ipapython/install/util.py
+++ b/ipapython/install/util.py
@@ -8,6 +8,8 @@ Utilities.
import sys
+import six
+
def raise_exc_info(exc_info):
"""
@@ -155,7 +157,7 @@ class InnerClassMeta(type):
except KeyError:
cls, name, value = None, None, None
for cls in obj_type.__mro__:
- for name, value in cls.__dict__.iteritems():
+ for name, value in six.iteritems(cls.__dict__):
if value is self:
break
if value is self:
diff --git a/ipapython/ipaldap.py b/ipapython/ipaldap.py
index 124ab3c20..66622ef61 100644
--- a/ipapython/ipaldap.py
+++ b/ipapython/ipaldap.py
@@ -279,7 +279,7 @@ class LDAPEntry(collections.MutableMapping):
def __repr__(self):
data = dict(self._raw)
- data.update((k, v) for k, v in self._nice.iteritems() if v is not None)
+ data.update((k, v) for k, v in self._nice.items() if v is not None)
return '%s(%r, %r)' % (type(self).__name__, self._dn, data)
def copy(self):
@@ -495,7 +495,7 @@ class LDAPEntry(collections.MutableMapping):
def generate_modlist(self):
modlist = []
- names = set(self.iterkeys())
+ names = set(self)
names.update(self._orig)
for name in names:
new = self.raw.get(name, [])
@@ -548,7 +548,7 @@ class LDAPEntryView(collections.MutableMapping):
self._entry.clear()
def __iter__(self):
- return self._entry.iterkeys()
+ return iter(self._entry)
def __len__(self):
return len(self._entry)
@@ -842,7 +842,7 @@ class LDAPClient(object):
elif isinstance(val, tuple):
return tuple(self.encode(m) for m in val)
elif isinstance(val, dict):
- dct = dict((self.encode(k), self.encode(v)) for k, v in val.iteritems())
+ dct = dict((self.encode(k), self.encode(v)) for k, v in val.items())
return dct
elif isinstance(val, datetime.datetime):
return val.strftime(LDAP_GENERALIZED_TIME_FORMAT)
@@ -875,7 +875,7 @@ class LDAPClient(object):
elif isinstance(val, tuple):
return tuple(self.decode(m, attr) for m in val)
elif isinstance(val, dict):
- dct = dict((unicode_from_utf8(k), self.decode(v, k)) for k, v in val.iteritems())
+ dct = dict((unicode_from_utf8(k), self.decode(v, k)) for k, v in val.items())
return dct
elif val is None:
return None
@@ -1234,7 +1234,7 @@ class LDAPClient(object):
make_filter_rules = rules
flts = []
if attrs_list is None:
- for (k, v) in entry_attrs.iteritems():
+ for (k, v) in entry_attrs.items():
flts.append(
self.make_filter_from_attr(
k, v, make_filter_rules, exact,
@@ -1436,11 +1436,11 @@ class LDAPClient(object):
This should be called as add_entry(entry).
"""
# remove all [] values (python-ldap hates 'em)
- attrs = dict((k, v) for k, v in entry.raw.iteritems() if v)
+ attrs = dict((k, v) for k, v in entry.raw.items() if v)
with self.error_handler():
attrs = self.encode(attrs)
- self.conn.add_s(str(entry.dn), attrs.items())
+ self.conn.add_s(str(entry.dn), list(attrs.items()))
entry.reset_modlist()
diff --git a/ipapython/ipautil.py b/ipapython/ipautil.py
index 80ce83506..b6cbe50e9 100644
--- a/ipapython/ipautil.py
+++ b/ipapython/ipautil.py
@@ -545,13 +545,13 @@ class CIDict(dict):
for key in keys():
self.__setitem__(key, new[key], seen)
seen = set()
- for key, value in kwargs.iteritems():
+ for key, value in kwargs.items():
self.__setitem__(key, value, seen)
def __contains__(self, key):
return super(CIDict, self).__contains__(key.lower())
- if sys.version_info < (3, 0):
+ if six.PY2:
def has_key(self, key):
return super(CIDict, self).has_key(key.lower())
@@ -562,29 +562,38 @@ class CIDict(dict):
return failobj
def __iter__(self):
- return self._keys.itervalues()
+ return six.itervalues(self._keys)
def keys(self):
- return list(self.iterkeys())
+ if six.PY2:
+ return list(self.iterkeys())
+ else:
+ return self.iterkeys()
def items(self):
- return list(self.iteritems())
+ if six.PY2:
+ return list(self.iteritems())
+ else:
+ return self.iteritems()
def values(self):
- return list(self.itervalues())
+ if six.PY2:
+ return list(self.itervalues())
+ else:
+ return self.itervalues()
def copy(self):
"""Returns a shallow copy of this CIDict"""
- return CIDict(self.items())
+ return CIDict(list(self.items()))
def iteritems(self):
- return ((k, self[k]) for k in self._keys.itervalues())
+ return ((k, self[k]) for k in six.itervalues(self._keys))
def iterkeys(self):
- return self._keys.itervalues()
+ return six.itervalues(self._keys)
def itervalues(self):
- return (v for k, v in self.iteritems())
+ return (v for k, v in six.iteritems(self))
def setdefault(self, key, value=None):
try:
diff --git a/ipaserver/install/ipa_restore.py b/ipaserver/install/ipa_restore.py
index 0620d24df..e8820b99e 100644
--- a/ipaserver/install/ipa_restore.py
+++ b/ipaserver/install/ipa_restore.py
@@ -104,7 +104,7 @@ class RemoveRUVParser(ldif.LDIFParser):
objectclass = None
nsuniqueid = None
- for name, value in entry.iteritems():
+ for name, value in entry.items():
name = name.lower()
if name == 'objectclass':
objectclass = [x.lower() for x in value]
diff --git a/ipaserver/install/plugins/update_managed_permissions.py b/ipaserver/install/plugins/update_managed_permissions.py
index 563dbb0d6..79af64c38 100644
--- a/ipaserver/install/plugins/update_managed_permissions.py
+++ b/ipaserver/install/plugins/update_managed_permissions.py
@@ -399,10 +399,10 @@ class update_managed_permissions(Updater):
"""
for obj in sorted(self.api.Object(), key=lambda o: o.name):
managed_permissions = getattr(obj, 'managed_permissions', {})
- for name, template in sorted(managed_permissions.iteritems()):
+ for name, template in sorted(managed_permissions.items()):
yield name, template, obj
- for name, template in sorted(NONOBJECT_PERMISSIONS.iteritems()):
+ for name, template in sorted(NONOBJECT_PERMISSIONS.items()):
yield name, template, None
diff --git a/ipaserver/install/plugins/update_referint.py b/ipaserver/install/plugins/update_referint.py
index c5c80359e..aefe28ce0 100644
--- a/ipaserver/install/plugins/update_referint.py
+++ b/ipaserver/install/plugins/update_referint.py
@@ -63,7 +63,7 @@ class update_referint(Updater):
entry['nsslapd-pluginArg2'] = None
# nsslapd-pluginArg3..N -> referint-membership-attr [3..N]
- for key in entry.keys():
+ for key in list(entry):
if key.lower().startswith('nsslapd-pluginarg'):
arg_val = entry.single_value[key]
if arg_val:
diff --git a/ipaserver/install/schemaupdate.py b/ipaserver/install/schemaupdate.py
index f98d0e949..432c44d42 100644
--- a/ipaserver/install/schemaupdate.py
+++ b/ipaserver/install/schemaupdate.py
@@ -56,7 +56,7 @@ def _get_oid_dependency_order(schema, cls):
# remove top_node from tree, it breaks ordering
# we don't need this, tree from file is not consistent
del tree[top_node]
- unordered_oids = tree.keys()
+ unordered_oids = set(tree)
# split into two groups, parents and child nodes, and iterate until
# child nodes are not empty
diff --git a/ipaserver/install/server/install.py b/ipaserver/install/server/install.py
index 967538334..3feaf8fce 100644
--- a/ipaserver/install/server/install.py
+++ b/ipaserver/install/server/install.py
@@ -34,6 +34,7 @@ from ipaserver.install.installutils import (
IPA_MODULES, BadHostError, get_fqdn, get_server_ip_address,
is_ipa_configured, load_pkcs12, read_password, verify_fqdn)
from ipaserver.plugins.ldap2 import ldap2
+
try:
from ipaserver.install import adtrustinstance
_server_trust_ad_installed = True
@@ -342,7 +343,7 @@ def install_check(installer):
sys.exit("Directory Manager password required")
try:
cache_vars = read_cache(dm_password)
- for name, value in cache_vars.iteritems():
+ for name, value in cache_vars.items():
if name not in options.__dict__:
options.__dict__[name] = value
if cache_vars.get('external_ca', False):
diff --git a/ipaserver/install/upgradeinstance.py b/ipaserver/install/upgradeinstance.py
index 10f7c2ce0..684a3dd99 100644
--- a/ipaserver/install/upgradeinstance.py
+++ b/ipaserver/install/upgradeinstance.py
@@ -123,7 +123,7 @@ class ModifyLDIF(ldif.LDIFParser):
def handle(self, dn, entry):
if dn in self.remove_dict:
- for name, value in self.remove_dict[dn].iteritems():
+ for name, value in self.remove_dict[dn].items():
if value is None:
attribute = []
else:
@@ -135,7 +135,7 @@ class ModifyLDIF(ldif.LDIFParser):
del entry[name]
if dn in self.add_dict:
- for name, value in self.add_dict[dn].iteritems():
+ for name, value in self.add_dict[dn].items():
attribute = entry.setdefault(name, [])
attribute.extend([v for v in value if v not in attribute])
diff --git a/ipaserver/rpcserver.py b/ipaserver/rpcserver.py
index df75d98bb..3b0fee534 100644
--- a/ipaserver/rpcserver.py
+++ b/ipaserver/rpcserver.py
@@ -201,7 +201,7 @@ def params_2_args_options(params):
def nicify_query(query, encoding='utf-8'):
if not query:
return
- for (key, value) in query.iteritems():
+ for (key, value) in query.items():
if len(value) == 0:
yield (key, None)
elif len(value) == 1:
@@ -493,7 +493,7 @@ class jsonserver(WSGIExecutioner, HTTP_Status):
options = params[1]
if not isinstance(options, dict):
raise JSONError(error=_('params[1] (aka options) must be a dict'))
- options = dict((str(k), v) for (k, v) in options.iteritems())
+ options = dict((str(k), v) for (k, v) in options.items())
return (method, args, options, _id)
class AuthManagerKerb(AuthManager):
diff --git a/ipatests/test_ipalib/test_backend.py b/ipatests/test_ipalib/test_backend.py
index 163c4f272..756d434e3 100644
--- a/ipatests/test_ipalib/test_backend.py
+++ b/ipatests/test_ipalib/test_backend.py
@@ -223,12 +223,12 @@ class test_Executioner(ClassChecker):
# Test that CommandError is raised:
conn = Connection('The connection.', Disconnect('someconn'))
context.someconn = conn
- print str(context.__dict__.keys())
+ print str(list(context.__dict__))
e = raises(errors.CommandError, o.execute, 'nope')
assert e.name == 'nope'
assert conn.disconnect.called is True # Make sure destroy_context() was called
- print str(context.__dict__.keys())
- assert context.__dict__.keys() == []
+ print str(list(context.__dict__))
+ assert list(context.__dict__) == []
# Test with echo command:
arg1 = unicode_str
@@ -247,7 +247,7 @@ class test_Executioner(ClassChecker):
result=(arg1, arg2, options)
)
assert conn.disconnect.called is True # Make sure destroy_context() was called
- assert context.__dict__.keys() == []
+ assert list(context.__dict__) == []
conn = Connection('The connection.', Disconnect('someconn'))
context.someconn = conn
@@ -255,7 +255,7 @@ class test_Executioner(ClassChecker):
result=(arg1, arg2, options)
)
assert conn.disconnect.called is True # Make sure destroy_context() was called
- assert context.__dict__.keys() == []
+ assert list(context.__dict__) == []
# Test with good command:
conn = Connection('The connection.', Disconnect('someconn'))
@@ -264,14 +264,14 @@ class test_Executioner(ClassChecker):
assert e.name == 'nurse'
assert e.error == u'Not naughty!'
assert conn.disconnect.called is True # Make sure destroy_context() was called
- assert context.__dict__.keys() == []
+ assert list(context.__dict__) == []
# Test with bad command:
conn = Connection('The connection.', Disconnect('someconn'))
context.someconn = conn
e = raises(errors.InternalError, o.execute, 'bad')
assert conn.disconnect.called is True # Make sure destroy_context() was called
- assert context.__dict__.keys() == []
+ assert list(context.__dict__) == []
# Test with option 'name':
conn = Connection('The connection.', Disconnect('someconn'))
diff --git a/ipatests/test_ipalib/test_config.py b/ipatests/test_ipalib/test_config.py
index b4d71e558..f414d55e4 100644
--- a/ipatests/test_ipalib/test_config.py
+++ b/ipatests/test_ipalib/test_config.py
@@ -345,7 +345,7 @@ class test_Env(ClassChecker):
expected.update(dict(group1))
assert list(o) == sorted(expected)
assert expected['key2'] == 'value 2' # And not 'Value 2'
- for (key, value) in expected.iteritems():
+ for (key, value) in expected.items():
assert getattr(o, key) is value
assert o[key] is value
assert o._merge(**expected) == (0, 6)
diff --git a/ipatests/test_ipalib/test_errors.py b/ipatests/test_ipalib/test_errors.py
index 203935113..938b9fcec 100644
--- a/ipatests/test_ipalib/test_errors.py
+++ b/ipatests/test_ipalib/test_errors.py
@@ -47,14 +47,14 @@ class PrivateExceptionTester(object):
klass = property(__get_klass)
def new(self, **kw):
- for (key, value) in kw.iteritems():
+ for (key, value) in kw.items():
assert not hasattr(self.klass, key), key
inst = self.klass(**kw)
assert isinstance(inst, StandardError)
assert isinstance(inst, errors.PrivateError)
assert isinstance(inst, self.klass)
assert not isinstance(inst, errors.PublicError)
- for (key, value) in kw.iteritems():
+ for (key, value) in kw.items():
assert getattr(inst, key) is value
assert str(inst) == self.klass.format % kw
assert inst.message == str(inst)
@@ -212,14 +212,14 @@ class PublicExceptionTester(object):
assert str(e) == TYPE_ERROR % ('message', unicode, 'The message', str)
# Test the instance:
- for (key, value) in kw.iteritems():
+ for (key, value) in kw.items():
assert not hasattr(self.klass, key), key
inst = self.klass(format=format, message=message, **kw)
for required_class in self.required_classes:
assert isinstance(inst, required_class)
assert isinstance(inst, self.klass)
assert not isinstance(inst, errors.PrivateError)
- for (key, value) in kw.iteritems():
+ for (key, value) in kw.items():
assert getattr(inst, key) is value
return inst
diff --git a/ipatests/test_ipalib/test_frontend.py b/ipatests/test_ipalib/test_frontend.py
index 76f500fe2..3798c4ed8 100644
--- a/ipatests/test_ipalib/test_frontend.py
+++ b/ipatests/test_ipalib/test_frontend.py
@@ -430,7 +430,7 @@ class test_Command(ClassChecker):
)
o = self.subcls(api)
o.finalize()
- for (key, value) in o.convert(**kw).iteritems():
+ for (key, value) in o.convert(**kw).items():
assert_equal(unicode(kw[key]), value)
def test_normalize(self):
diff --git a/ipatests/test_ipalib/test_parameters.py b/ipatests/test_ipalib/test_parameters.py
index b466a4f22..a1273448e 100644
--- a/ipatests/test_ipalib/test_parameters.py
+++ b/ipatests/test_ipalib/test_parameters.py
@@ -699,7 +699,7 @@ class test_Data(ClassChecker):
]
for kw in permutations:
o = self.cls('my_data', **kw)
- for (key, value) in kw.iteritems():
+ for (key, value) in kw.items():
assert getattr(o, key) == value
e = raises(ValueError, self.cls, 'my_data', length=5, **kw)
assert str(e) == \
@@ -760,7 +760,7 @@ class test_Bytes(ClassChecker):
assert len(o.class_rules) == len(kw)
assert len(o.rules) == 0
assert len(o.all_rules) == len(kw)
- for (key, value) in kw.iteritems():
+ for (key, value) in kw.items():
assert getattr(o, key) == value
e = raises(ValueError, self.cls, 'my_bytes', length=5, **kw)
assert str(e) == \
diff --git a/ipatests/test_ipapython/test_dn.py b/ipatests/test_ipapython/test_dn.py
index dae7d016e..69ccbde8e 100644
--- a/ipatests/test_ipapython/test_dn.py
+++ b/ipatests/test_ipapython/test_dn.py
@@ -239,7 +239,7 @@ class TestAVA(unittest.TestCase):
self.assertEqual(len(d), 2)
self.assertEqual(len(s), 2)
- self.assertEqual(sorted(d.keys()), sorted([ava1_a, ava2_a]))
+ self.assertEqual(sorted(d), sorted([ava1_a, ava2_a]))
self.assertEqual(sorted(s), sorted([ava1_a, ava2_a]))
self.assertTrue(ava1_a in d)
@@ -1119,7 +1119,7 @@ class TestDN(unittest.TestCase):
self.assertEqual(len(d), 2)
self.assertEqual(len(s), 2)
- self.assertEqual(sorted(d.keys()), sorted([dn1_a, dn2_a]))
+ self.assertEqual(sorted(d), sorted([dn1_a, dn2_a]))
self.assertEqual(sorted(s), sorted([dn1_a, dn2_a]))
self.assertTrue(dn1_a in d)
diff --git a/ipatests/test_ipapython/test_ipautil.py b/ipatests/test_ipapython/test_ipautil.py
index 112759b01..ee0f559cf 100644
--- a/ipatests/test_ipapython/test_ipautil.py
+++ b/ipatests/test_ipapython/test_ipautil.py
@@ -24,6 +24,7 @@ import sys
import nose
import pytest
+import six
from ipapython import ipautil
@@ -132,9 +133,13 @@ class TestCIDict(object):
self.cidict.clear()
nose.tools.assert_equal(0, len(self.cidict))
assert self.cidict == {}
- assert self.cidict.keys() == []
- assert self.cidict.values() == []
- assert self.cidict.items() == []
+ assert list(self.cidict) == []
+ assert list(self.cidict.values()) == []
+ assert list(self.cidict.items()) == []
+ if six.PY2:
+ assert self.cidict.keys() == []
+ assert self.cidict.values() == []
+ assert self.cidict.items() == []
assert self.cidict._keys == {}
def test_copy(self):
@@ -145,7 +150,7 @@ class TestCIDict(object):
assert "key1" in copy
nose.tools.assert_equal("val1", copy["Key1"])
- @pytest.mark.skipif(sys.version_info >= (3, 0), reason="Python 2 only")
+ @pytest.mark.skipif(not six.PY2, reason="Python 2 only")
def test_haskey(self):
assert self.cidict.has_key("KEY1")
assert self.cidict.has_key("key2")
@@ -161,15 +166,15 @@ class TestCIDict(object):
assert "Key4" not in self.cidict
def test_items(self):
- items = self.cidict.items()
+ items = list(self.cidict.items())
nose.tools.assert_equal(3, len(items))
items_set = set(items)
assert ("Key1", "val1") in items_set
assert ("key2", "val2") in items_set
assert ("KEY3", "VAL3") in items_set
- assert self.cidict.items() == list(self.cidict.iteritems()) == zip(
- self.cidict.iterkeys(), self.cidict.itervalues())
+ assert list(self.cidict.items()) == list(self.cidict.iteritems()) == zip(
+ self.cidict.keys(), self.cidict.values())
def test_iter(self):
items = []
@@ -207,24 +212,24 @@ class TestCIDict(object):
assert "VAL3" in values_set
def test_keys(self):
- keys = self.cidict.keys()
+ keys = list(self.cidict.keys())
nose.tools.assert_equal(3, len(keys))
keys_set = set(keys)
assert "Key1" in keys_set
assert "key2" in keys_set
assert "KEY3" in keys_set
- assert self.cidict.keys() == list(self.cidict.iterkeys())
+ assert list(self.cidict.keys()) == list(self.cidict.iterkeys())
def test_values(self):
- values = self.cidict.values()
+ values = list(self.cidict.values())
nose.tools.assert_equal(3, len(values))
values_set = set(values)
assert "val1" in values_set
assert "val2" in values_set
assert "VAL3" in values_set
- assert self.cidict.values() == list(self.cidict.itervalues())
+ assert list(self.cidict.values()) == list(self.cidict.itervalues())
def test_update(self):
newdict = { "KEY2": "newval2",
@@ -232,7 +237,7 @@ class TestCIDict(object):
self.cidict.update(newdict)
nose.tools.assert_equal(4, len(self.cidict))
- items = self.cidict.items()
+ items = list(self.cidict.items())
nose.tools.assert_equal(4, len(items))
items_set = set(items)
assert ("Key1", "val1") in items_set
diff --git a/ipatests/test_ipaserver/test_ldap.py b/ipatests/test_ipaserver/test_ldap.py
index 28e84fb70..f50c19a92 100644
--- a/ipatests/test_ipaserver/test_ldap.py
+++ b/ipatests/test_ipaserver/test_ldap.py
@@ -211,7 +211,7 @@ class test_LDAPEntry(object):
def test_popitem(self):
e = self.entry
assert e.popitem() == ('cn', self.cn1)
- e.keys() == []
+ list(e) == []
def test_setdefault(self):
e = self.entry
diff --git a/ipatests/test_webui/ui_driver.py b/ipatests/test_webui/ui_driver.py
index 16af5ff16..d097a5490 100644
--- a/ipatests/test_webui/ui_driver.py
+++ b/ipatests/test_webui/ui_driver.py
@@ -154,7 +154,7 @@ class UI_driver(object):
c = self.config
# override with environmental variables
- for k, v in ENV_MAP.iteritems():
+ for k, v in ENV_MAP.items():
val = os.environ.get(k)
if val is not None:
c[v] = val
diff --git a/ipatests/test_xmlrpc/ldaptracker.py b/ipatests/test_xmlrpc/ldaptracker.py
index 9cc44f8a6..bf753a5c5 100644
--- a/ipatests/test_xmlrpc/ldaptracker.py
+++ b/ipatests/test_xmlrpc/ldaptracker.py
@@ -122,7 +122,7 @@ class Tracker(object):
args_repr = ', '.join(
[repr(a) for a in args] +
- ['%s=%r' % item for item in options.items()])
+ ['%s=%r' % item for item in list(options.items())])
try:
result = cmd(*args, **options)
except Exception as e:
diff --git a/ipatests/test_xmlrpc/test_pwpolicy_plugin.py b/ipatests/test_xmlrpc/test_pwpolicy_plugin.py
index 5a8ac1030..3739aa893 100644
--- a/ipatests/test_xmlrpc/test_pwpolicy_plugin.py
+++ b/ipatests/test_xmlrpc/test_pwpolicy_plugin.py
@@ -30,7 +30,6 @@ from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import (XMLRPC_test, assert_attr_equal,
Declarative)
-
class test_pwpolicy(XMLRPC_test):
"""
Test the `pwpolicy` plugin.
@@ -195,7 +194,7 @@ class test_pwpolicy(XMLRPC_test):
# Test that returned values match the arguments
# Only test the second and third results; the first one was modified
for entry, expected in (result[1], self.kw2), (result[2], self.kw3):
- for name, value in expected.iteritems():
+ for name, value in expected.items():
assert_attr_equal(entry, name, str(value))
def test_c_pwpolicy_find_pkey_only(self):
diff --git a/ipatests/util.py b/ipatests/util.py
index 03c5488f1..5a6595a62 100644
--- a/ipatests/util.py
+++ b/ipatests/util.py
@@ -468,7 +468,7 @@ def get_api(**kw):
home = TempHome()
api = ipalib.create_api(mode='unit_test')
api.env.in_tree = True
- for (key, value) in kw.iteritems():
+ for (key, value) in kw.items():
api.env[key] = value
return (api, home)
@@ -483,7 +483,7 @@ def create_test_api(**kw):
home = TempHome()
api = ipalib.create_api(mode='unit_test')
api.env.in_tree = True
- for (key, value) in kw.iteritems():
+ for (key, value) in kw.items():
api.env[key] = value
return (api, home)