Use six.string_types instead of "basestring"

Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
This commit is contained in:
Petr Viktorin
2015-08-10 18:29:33 +02:00
committed by Jan Cholasta
parent 404177f7a3
commit dd16cc98b0
22 changed files with 114 additions and 71 deletions

View File

@@ -20,6 +20,8 @@
import shlex
import re
import six
# The Python re module doesn't do nested parenthesis
# Break the ACI into 3 pieces: target, name, permissions/bind_rules
@@ -159,7 +161,7 @@ class ACI:
raise SyntaxError, "invalid permission: '%s'" % p
if not self.name:
raise SyntaxError, "name must be set"
if not isinstance(self.name, basestring):
if not isinstance(self.name, six.string_types):
raise SyntaxError, "name must be a string"
if not isinstance(self.target, dict) or len(self.target) == 0:
raise SyntaxError, "target must be a non-empty dictionary"

View File

@@ -23,6 +23,8 @@ Foundational classes and functions.
import re
import six
from ipalib.constants import NAME_REGEX, NAME_ERROR
from ipalib.constants import TYPE_ERROR, SET_ERROR, DEL_ERROR, OVERRIDE_ERROR
@@ -466,7 +468,7 @@ class NameSpace(ReadOnly):
:param key: The name or index of a member, or a slice object.
"""
key = getattr(key, '__name__', key)
if isinstance(key, basestring):
if isinstance(key, six.string_types):
return self.__map[key]
if type(key) in (int, slice):
return self.__members[key]

View File

@@ -31,6 +31,9 @@ import termios
import struct
import base64
import traceback
import six
try:
#pylint: disable=F0401
import default_encoding_utf8
@@ -280,7 +283,7 @@ class textui(backend.Backend):
objectClass: top
objectClass: someClass
"""
assert isinstance(attr, basestring)
assert isinstance(attr, six.string_types)
if not isinstance(value, (list, tuple)):
# single-value attribute
self.print_indented(format % (attr, self.encode_binary(value)), indent)
@@ -420,7 +423,7 @@ class textui(backend.Backend):
------------------
Only dashed above.
"""
assert isinstance(dash, basestring)
assert isinstance(dash, six.string_types)
assert len(dash) == 1
dashes = dash * len(string)
if above:

View File

@@ -35,8 +35,10 @@ from types import NoneType
import os
from os import path
import sys
from ipapython.dn import DN
import six
from ipapython.dn import DN
from ipalib.base import check_name
from ipalib.constants import CONFIG_SECTION
from ipalib.constants import OVERRIDE_ERROR, SET_ERROR, DEL_ERROR
@@ -239,7 +241,7 @@ class Env(object):
(self.__class__.__name__, key, self.__d[key], value)
)
assert not hasattr(self, key)
if isinstance(value, basestring):
if isinstance(value, six.string_types):
value = value.strip()
if isinstance(value, str):
value = value.decode('utf-8')

View File

@@ -32,6 +32,8 @@ Messages also have the 'type' argument, set to one of 'debug', 'info',
from inspect import isclass
import six
from ipalib.constants import TYPE_ERROR
from ipalib.text import _ as ugettext
from ipalib.text import Gettext, NGettext
@@ -60,7 +62,7 @@ def process_message_arguments(obj, format=None, message=None, **kw):
obj.format = format
obj.forwarded = False
obj.msg = obj.format % kw
if isinstance(obj.format, basestring):
if isinstance(obj.format, six.string_types):
obj.strerror = ugettext(obj.format) % kw
else:
obj.strerror = obj.format % kw

View File

@@ -108,6 +108,7 @@ from types import NoneType
import encodings.idna
import dns.name
import six
from ipalib.text import _ as ugettext
from ipalib.plugable import ReadOnly, lock, check_name
@@ -394,8 +395,8 @@ class Param(ReadOnly):
('cli_name', str, None),
('cli_short_name', str, None),
('deprecated_cli_aliases', frozenset, frozenset()),
('label', (basestring, Gettext), None),
('doc', (basestring, Gettext), None),
('label', (six.string_types, Gettext), None),
('doc', (six.string_types, Gettext), None),
('required', bool, True),
('multivalue', bool, False),
('primary_key', bool, False),
@@ -964,7 +965,7 @@ class Bool(Param):
"""
if type(value) in self.allowed_types:
return value
if isinstance(value, basestring):
if isinstance(value, six.string_types):
value = value.lower()
if value in self.truths:
return True
@@ -1143,7 +1144,7 @@ class Decimal(Number):
value = kw.get(kwparam)
if value is None:
continue
if isinstance(value, (basestring, float)):
if isinstance(value, (six.string_types, float)):
try:
value = decimal.Decimal(value)
except Exception as e:
@@ -1233,7 +1234,7 @@ class Decimal(Number):
return value
def _convert_scalar(self, value, index=None):
if isinstance(value, (basestring, float)):
if isinstance(value, (six.string_types, float)):
try:
value = decimal.Decimal(value)
except decimal.DecimalException as e:
@@ -1264,8 +1265,8 @@ class Data(Param):
('minlength', int, None),
('maxlength', int, None),
('length', int, None),
('pattern', (basestring,), None),
('pattern_errmsg', (basestring,), None),
('pattern', (six.string_types,), None),
('pattern_errmsg', (six.string_types,), None),
)
re = None
@@ -1474,7 +1475,7 @@ class IA5Str(Str):
super(IA5Str, self).__init__(name, *rules, **kw)
def _convert_scalar(self, value, index=None):
if isinstance(value, basestring):
if isinstance(value, six.string_types):
for i in xrange(len(value)):
if ord(value[i]) > 127:
raise ConversionError(name=self.get_param_name(),
@@ -1646,7 +1647,7 @@ class DateTime(Param):
type_error = _('must be datetime value')
def _convert_scalar(self, value, index=None):
if isinstance(value, basestring):
if isinstance(value, six.string_types):
for date_format in self.accepted_formats:
try:
time = datetime.datetime.strptime(value, date_format)

View File

@@ -25,6 +25,8 @@ import time
from copy import deepcopy
import base64
import six
from ipalib import api, crud, errors
from ipalib import Method, Object, Command
from ipalib import Flag, Int, Str
@@ -816,7 +818,7 @@ def _check_single_value_attrs(params, entry_attrs):
# required, make sure we enforce that.
def _check_empty_attrs(params, entry_attrs):
for (a, v) in entry_attrs.iteritems():
if v is None or (isinstance(v, basestring) and len(v) == 0):
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)
@@ -2038,7 +2040,7 @@ class LDAPSearch(BaseLDAPCommand, crud.Search):
config_attrs = config.get(
self.obj.search_attributes_config, [])
if len(config_attrs) == 1 and (
isinstance(config_attrs[0], basestring)):
isinstance(config_attrs[0], six.string_types)):
search_attrs = config_attrs[0].split(',')
search_kw['objectclass'] = self.obj.object_class

View File

@@ -22,6 +22,8 @@ import string
import posixpath
import os
import six
from ipalib import api, errors
from ipalib import Flag, Int, Password, Str, Bool, StrEnum, DateTime, Bytes
from ipalib.plugable import Registry
@@ -89,7 +91,7 @@ def validate_nsaccountlock(entry_attrs):
if 'nsaccountlock' in entry_attrs:
nsaccountlock = entry_attrs['nsaccountlock']
if not isinstance(nsaccountlock, (bool, Bool)):
if not isinstance(nsaccountlock, basestring):
if not isinstance(nsaccountlock, six.string_types):
raise errors.OnlyOneValueAllowed(attr='nsaccountlock')
if nsaccountlock.lower() not in ('true', 'false'):
raise errors.ValidationError(name='nsaccountlock',
@@ -400,7 +402,7 @@ class baseuser(LDAPObject):
if not isinstance(email, (list, tuple)):
email = [email]
for m in email:
if isinstance(m, basestring):
if isinstance(m, six.string_types):
if '@' not in m and defaultdomain:
m = m + u'@' + defaultdomain
if not Email(m):

View File

@@ -24,11 +24,13 @@ import netaddr
import time
import re
import binascii
import encodings.idna
import dns.name
import dns.exception
import dns.rdatatype
import dns.resolver
import encodings.idna
import six
from ipalib.request import context
from ipalib import api, errors, output
@@ -1671,7 +1673,7 @@ def _create_idn_filter(cmd, ldap, *args, **options):
config = ldap.get_ipa_config()
config_attrs = config.get(cmd.obj.search_attributes_config, [])
if len(config_attrs) == 1 and (isinstance(config_attrs[0],
basestring)):
six.string_types)):
search_attrs = config_attrs[0].split(',')
search_kw['objectclass'] = cmd.obj.object_class

View File

@@ -18,6 +18,8 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import six
from ipalib import api
from ipalib import Int, Str
from ipalib.plugable import Registry
@@ -25,6 +27,7 @@ from ipalib.plugins.baseldap import *
from ipalib.plugins.idviews import remove_ipaobject_overrides
from ipalib.plugins import baseldap
from ipalib import _, ngettext
if api.env.in_server and api.env.context in ['lite', 'server']:
try:
import ipaserver.dcerpc
@@ -460,7 +463,7 @@ class group_find(LDAPSearch):
search_kw = {}
config = ldap.get_ipa_config()
attrs = config.get(self.obj.search_attributes_config, [])
if len(attrs) == 1 and isinstance(attrs[0], basestring):
if len(attrs) == 1 and isinstance(attrs[0], six.string_types):
search_attrs = attrs[0].split(',')
for a in search_attrs:
search_kw[a] = args[-1]

View File

@@ -20,6 +20,8 @@
import re
import traceback
import six
from ipalib.plugins import baseldap
from ipalib.plugins.privilege import validate_permission_to_privilege
from ipalib import errors
@@ -134,7 +136,7 @@ class DNOrURL(DNParam):
"""
def _convert_scalar(self, value, index=None):
if isinstance(value, basestring) and value.startswith('ldap:///'):
if isinstance(value, six.string_types) and value.startswith('ldap:///'):
value = strip_ldap_prefix(value)
return super(DNOrURL, self)._convert_scalar(value, index=index)

View File

@@ -41,13 +41,14 @@ import urllib
import json
import socket
from urllib2 import urlparse
from xmlrpclib import (Binary, Fault, DateTime, dumps, loads, ServerProxy,
Transport, ProtocolError, MININT, MAXINT)
import gssapi
from dns import resolver, rdatatype
from dns.exception import DNSException
from nss.error import NSPRError
import six
from ipalib.backend import Connectible
from ipalib.constants import LDAP_GENERALIZED_TIME_FORMAT
@@ -339,7 +340,7 @@ def json_decode_binary(val):
elif isinstance(val, list):
return tuple(json_decode_binary(v) for v in val)
else:
if isinstance(val, basestring):
if isinstance(val, six.string_types):
try:
return val.decode('utf-8')
except UnicodeDecodeError:

View File

@@ -29,13 +29,15 @@ import re
import decimal
import dns
import encodings
import netaddr
from types import NoneType
from weakref import WeakKeyDictionary
import netaddr
from dns import resolver, rdatatype
from dns.exception import DNSException
from dns.resolver import NXDOMAIN
from netaddr.core import AddrFormatError
import six
from ipalib import errors, messages
from ipalib.text import _
@@ -178,7 +180,7 @@ def check_writable_file(filename):
raise errors.FileError(reason=str(e))
def normalize_zonemgr(zonemgr):
if not zonemgr or not isinstance(zonemgr, basestring):
if not zonemgr or not isinstance(zonemgr, six.string_types):
return zonemgr
if '@' in zonemgr:
# local-part needs to be normalized
@@ -572,8 +574,8 @@ def _resolve_record(owner, rtype, nameserver_ip=None, edns0=False,
:param flag_cd: requires dnssec=True, adds flag CD
:raise DNSException: if error occurs
"""
assert isinstance(nameserver_ip, basestring)
assert isinstance(rtype, basestring)
assert isinstance(nameserver_ip, six.string_types)
assert isinstance(rtype, six.string_types)
res = dns.resolver.Resolver()
if nameserver_ip:

View File

@@ -23,6 +23,9 @@ import datetime
import email.utils
from urllib2 import urlparse
from calendar import timegm
import six
from ipapython.ipa_log_manager import log_mgr
'''
@@ -390,7 +393,7 @@ class Cookie(object):
self._timestamp = value
elif isinstance(value, (int, long, float)):
self._timestamp = datetime.datetime.utcfromtimestamp(value)
elif isinstance(value, basestring):
elif isinstance(value, six.string_types):
self._timestamp = Cookie.parse_datetime(value)
else:
raise TypeError('value must be datetime, int, long, float, basestring or None, not %s' % \
@@ -416,7 +419,7 @@ class Cookie(object):
self._expires = value
elif isinstance(value, (int, long, float)):
self._expires = datetime.datetime.utcfromtimestamp(value)
elif isinstance(value, basestring):
elif isinstance(value, six.string_types):
self._expires = Cookie.parse_datetime(value)
else:
raise TypeError('value must be datetime, int, long, float, basestring or None, not %s' % \

View File

@@ -418,9 +418,11 @@ to the constructor. The result may share underlying structure.
'''
import sys
from ldap.dn import str2dn, dn2str
from ldap import DECODING_ERROR
import sys
import six
__all__ = 'AVA', 'RDN', 'DN'
@@ -443,7 +445,7 @@ def _adjust_indices(start, end, length):
def _normalize_ava_input(val):
if not isinstance(val, basestring):
if not isinstance(val, six.string_types):
val = unicode(val).encode('utf-8')
elif isinstance(val, unicode):
val = val.encode('utf-8')
@@ -490,7 +492,7 @@ def get_ava(*args):
if len(arg) != 2:
raise ValueError("tuple or list must be 2-valued, not \"%s\"" % (arg))
ava = [_normalize_ava_input(arg[0]), _normalize_ava_input(arg[1]), 0]
elif isinstance(arg, basestring):
elif isinstance(arg, six.string_types):
rdn = str2rdn(arg)
if len(rdn) > 1:
raise TypeError("multiple AVA's specified by \"%s\"" % (arg))
@@ -651,7 +653,7 @@ class AVA(object):
caseIgnoreMatch.
'''
# Try coercing string to AVA, if successful compare to coerced object
if isinstance(other, basestring):
if isinstance(other, six.string_types):
try:
other_ava = AVA(other)
return self.__eq__(other_ava)
@@ -795,7 +797,7 @@ class RDN(object):
if raw: # fast raw mode
avas = args
elif ava_count == 1 and isinstance(args[0], basestring):
elif ava_count == 1 and isinstance(args[0], six.string_types):
avas = str2rdn(args[0])
sort = 1
elif ava_count == 1 and isinstance(args[0], RDN):
@@ -835,7 +837,7 @@ class RDN(object):
return self._get_ava(self._avas[key])
if isinstance(key, slice):
return [self._get_ava(ava) for ava in self._avas[key]]
elif isinstance(key, basestring):
elif isinstance(key, six.string_types):
for ava in self._avas:
if key == ava[0].decode('utf-8'):
return ava[1].decode('utf-8')
@@ -880,7 +882,7 @@ class RDN(object):
def __eq__(self, other):
# Try coercing string to RDN, if successful compare to coerced object
if isinstance(other, basestring):
if isinstance(other, six.string_types):
try:
other_rdn = RDN(other)
return self.__eq__(other_rdn)
@@ -910,7 +912,7 @@ class RDN(object):
result._avas.append((ava[0], ava[1], ava[2]))
elif isinstance(other, AVA):
result._avas.append(other.to_openldap())
elif isinstance(other, basestring):
elif isinstance(other, six.string_types):
rdn = self.__class__(other)
for ava in rdn._avas:
result._avas.append((ava[0], ava[1], ava[2]))
@@ -1080,7 +1082,7 @@ class DN(object):
return [[list(a) for a in rdn] for rdn in rdns]
def _rdns_from_value(self, value):
if isinstance(value, basestring):
if isinstance(value, six.string_types):
try:
if isinstance(value, unicode):
value = value.encode('utf-8')
@@ -1144,7 +1146,7 @@ class DN(object):
new_dn = cls.__new__(cls)
new_dn.rdns = self.rdns[key]
return new_dn
elif isinstance(key, basestring):
elif isinstance(key, six.string_types):
for rdn in self.rdns:
for ava in rdn:
if key == ava[0].decode('utf-8'):
@@ -1170,7 +1172,7 @@ class DN(object):
def __eq__(self, other):
# Try coercing to DN, if successful compare to coerced object
if isinstance(other, (basestring, RDN, AVA)):
if isinstance(other, (six.string_types, RDN, AVA)):
try:
other_dn = DN(other)
return self.__eq__(other_dn)

View File

@@ -36,6 +36,7 @@ import ldap.filter
from ldap.ldapobject import SimpleLDAPObject
from ldap.controls import SimplePagedResultsControl
import ldapurl
import six
from ipalib import errors, _
from ipalib.constants import LDAP_GENERALIZED_TIME_FORMAT
@@ -330,7 +331,7 @@ class LDAPEntry(collections.MutableMapping):
self._not_list.discard(name)
def _attr_name(self, name):
if not isinstance(name, basestring):
if not isinstance(name, six.string_types):
raise TypeError(
"attribute name must be unicode or str, got %s object %r" % (
name.__class__.__name__, name))

View File

@@ -37,9 +37,11 @@ import time
import gssapi
import pwd
import grp
from contextlib import contextmanager
from dns import resolver, rdatatype
from dns.exception import DNSException
from contextlib import contextmanager
import six
from ipapython.ipa_log_manager import *
from ipapython import ipavalidate
@@ -117,7 +119,7 @@ class CheckedIPAddress(netaddr.IPAddress):
# netaddr.IPAddress doesn't handle zone indices in textual
# IPv6 addresses. Try removing zone index and parse the
# address again.
if not isinstance(addr, basestring):
if not isinstance(addr, six.string_types):
raise
addr, sep, foo = addr.partition('%')
if sep != '%':
@@ -295,7 +297,7 @@ def run(args, stdin=None, raiseonerr=True,
p_out = None
p_err = None
if isinstance(nolog, basestring):
if isinstance(nolog, six.string_types):
# We expect a tuple (or list, or other iterable) of nolog strings.
# Passing just a single string is bad: strings are also, so this
# would result in every individual character of that string being
@@ -383,7 +385,7 @@ def run(args, stdin=None, raiseonerr=True,
def nolog_replace(string, nolog):
"""Replace occurences of strings given in `nolog` with XXXXXXXX"""
for value in nolog:
if not isinstance(value, basestring):
if not isinstance(value, six.string_types):
continue
quoted = urllib2.quote(value)
@@ -761,7 +763,7 @@ def user_input(prompt, default = None, allow_empty = True):
return ''
raise RuntimeError("Failed to get user input")
if isinstance(default, basestring):
if isinstance(default, six.string_types):
while True:
try:
ret = raw_input("%s [%s]: " % (prompt, default))

View File

@@ -509,6 +509,8 @@ import logging
import re
import time
import six
#-------------------------------------------------------------------------------
# Default format
LOGGING_DEFAULT_FORMAT = '%(levelname)s %(message)s'
@@ -600,7 +602,7 @@ def parse_log_level(level):
'''
# Is it a string representation of an integer?
# If so convert to an int.
if isinstance(level, basestring):
if isinstance(level, six.string_types):
try:
level = int(level)
except:
@@ -608,7 +610,7 @@ def parse_log_level(level):
# If it's a string lookup it's name and map to logging level
# otherwise validate the integer value is in range.
if isinstance(level, basestring):
if isinstance(level, six.string_types):
result = log_level_name_map.get(level.lower()) #pylint: disable=E1103
if result is None:
raise ValueError('unknown log level (%s)' % level)
@@ -959,7 +961,7 @@ class LogManager(object):
if not isinstance(config, dict):
raise TypeError('expected dict for handler config, got "%s"', type(config))
if isinstance(logger, basestring):
if isinstance(logger, six.string_types):
logger = self.get_logger(logger)
else:
if not isinstance(logger, logging.Logger):
@@ -1167,7 +1169,7 @@ class LogManager(object):
user = cfg.get('user')
group = cfg.get('group')
if user is not None:
if isinstance(user, basestring):
if isinstance(user, six.string_types):
pw = pwd.getpwnam(user)
uid = pw.pw_uid
elif isinstance(user, int):
@@ -1175,7 +1177,7 @@ class LogManager(object):
else:
raise TypeError("user (%s) is not int or basestring" % user)
if group is not None:
if isinstance(group, basestring):
if isinstance(group, six.string_types):
pw = pwd.getpwnam(group)
gid = pw.pw_gid
elif isinstance(group, int):
@@ -1216,7 +1218,7 @@ class LogManager(object):
datefmt = cfg.get("datefmt", None)
formatter = logging.Formatter(format, datefmt)
time_zone_converter = cfg.get('time_zone_converter', time.localtime)
if isinstance(time_zone_converter, basestring):
if isinstance(time_zone_converter, six.string_types):
converter = {'local' : time.localtime,
'localtime' : time.localtime,
'gmt' : time.gmtime,
@@ -1310,7 +1312,7 @@ class LogManager(object):
List of loggers with the handler is bound to.
'''
if isinstance(handler, basestring):
if isinstance(handler, six.string_types):
handler = self.get_handler(handler)
elif isinstance(handler, logging.Handler):
if not handler in self.handlers.values():
@@ -1344,7 +1346,7 @@ class LogManager(object):
use configure_state to track the state of the log manager.
'''
if isinstance(handler, basestring):
if isinstance(handler, six.string_types):
handler = self.get_handler(handler)
elif not isinstance(handler, logging.Handler):
raise TypeError('handler must be basestring or Handler object, got %s' % type(handler))
@@ -1522,7 +1524,7 @@ class LogManager(object):
'''
is_object = False
if isinstance(who, basestring):
if isinstance(who, six.string_types):
obj_name = who
else:
is_object = True

View File

@@ -26,6 +26,7 @@ import sys
import time
import ldap
import six
from ipaserver.install import installutils
from ipaserver.install import service
@@ -178,7 +179,7 @@ def named_conf_set_directive(name, value, section=NAMED_SECTION_IPA,
if name == match.group('name'):
matched = True
if value is not None:
if not isinstance(value, basestring):
if not isinstance(value, six.string_types):
value = str(value)
new_conf = named_conf_arg_template \
% dict(indent=last_indent,

View File

@@ -28,6 +28,8 @@ import os
import json
import collections
import six
from ipapython import ipautil
from ipatests.test_integration.config import Config, Domain
@@ -128,7 +130,7 @@ def config_from_env(env):
kwargs['domains'] = []
# $IPv6SETUP needs to be 'TRUE' to enable ipv6
if isinstance(kwargs['ipv6'], basestring):
if isinstance(kwargs['ipv6'], six.string_types):
kwargs['ipv6'] = (kwargs['ipv6'].upper() == 'TRUE')
config = Config(**kwargs)

View File

@@ -25,6 +25,7 @@ import datetime
import nose
import contextlib
import six
from ipatests.util import assert_deepequal, Fuzzy
from ipalib import api, request, errors
@@ -35,7 +36,7 @@ from ipapython.version import API_VERSION
# Matches a gidnumber like '1391016742'
# FIXME: Does it make more sense to return gidnumber, uidnumber, etc. as `int`
# or `long`? If not, we still need to return them as `unicode` instead of `str`.
fuzzy_digits = Fuzzy('^\d+$', type=basestring)
fuzzy_digits = Fuzzy('^\d+$', type=six.string_types)
uuid_re = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
@@ -76,14 +77,14 @@ fuzzy_sudocmddn = Fuzzy(
)
# Matches a hash signature, not enforcing length
fuzzy_hash = Fuzzy('^([a-f0-9][a-f0-9]:)+[a-f0-9][a-f0-9]$', type=basestring)
fuzzy_hash = Fuzzy('^([a-f0-9][a-f0-9]:)+[a-f0-9][a-f0-9]$', type=six.string_types)
# Matches a date, like Tue Apr 26 17:45:35 2016 UTC
fuzzy_date = Fuzzy('^[a-zA-Z]{3} [a-zA-Z]{3} \d{2} \d{2}:\d{2}:\d{2} \d{4} UTC$')
fuzzy_issuer = Fuzzy(type=basestring, test=lambda issuer: valid_issuer(issuer))
fuzzy_issuer = Fuzzy(type=six.string_types, test=lambda issuer: valid_issuer(issuer))
fuzzy_hex = Fuzzy('^0x[0-9a-fA-F]+$', type=basestring)
fuzzy_hex = Fuzzy('^0x[0-9a-fA-F]+$', type=six.string_types)
# Matches password - password consists of all printable characters without whitespaces
# The only exception is space, but space cannot be at the beggingin or end of the pwd
@@ -93,7 +94,7 @@ fuzzy_password = Fuzzy('^\S([\S ]*\S)*$')
fuzzy_dergeneralizedtime = Fuzzy(type=datetime.datetime)
# match any string
fuzzy_string = Fuzzy(type=basestring)
fuzzy_string = Fuzzy(type=six.string_types)
# case insensitive match of sets
def fuzzy_set_ci(s):

View File

@@ -24,12 +24,15 @@ Common utility functions and classes for unit tests.
import inspect
import os
from os import path
import ldap
import ldap.sasl
import ldap.modlist
import tempfile
import shutil
import re
import six
import ldap
import ldap.sasl
import ldap.modlist
import ipalib
from ipalib.plugable import Plugin
from ipalib.request import context
@@ -213,7 +216,7 @@ class Fuzzy(object):
:param test: A callable used to perform equality test, e.g.
``lambda other: other >= 18``
"""
assert regex is None or isinstance(regex, basestring)
assert regex is None or isinstance(regex, six.string_types)
assert test is None or callable(test)
if regex is None:
self.re = None
@@ -221,7 +224,7 @@ class Fuzzy(object):
self.re = re.compile(regex)
if type is None:
type = unicode
assert type in (unicode, str, basestring)
assert type in (unicode, str, six.string_types)
self.regex = regex
self.type = type
self.test = test
@@ -309,7 +312,7 @@ def assert_deepequal(expected, got, doc='', stack=tuple()):
if isinstance(got, tuple):
got = list(got)
if isinstance(expected, DN):
if isinstance(got, basestring):
if isinstance(got, six.string_types):
got = DN(got)
if not (isinstance(expected, Fuzzy) or callable(expected) or type(expected) is type(got)):
raise AssertionError(