Removes several pylint warnings.

This patche removes 93 pylint deprecation warnings due to invalid escape
sequences (mostly 'invalid escape sequence \d') on unicode strings.

Signed-off-by: Rafael Guterres Jeffman <rjeffman@redhat.com>
Reviewed-By: Christian Heimes <cheimes@redhat.com>
This commit is contained in:
Rafael Guterres Jeffman 2019-09-23 18:30:22 -03:00 committed by Christian Heimes
parent bc53544c6f
commit c898be1df9
32 changed files with 84 additions and 77 deletions

View File

@ -16,7 +16,7 @@ from ipapython.dnsutil import DNSName
if six.PY3: if six.PY3:
unicode = str unicode = str
__doc__ = _(""" __doc__ = _(r"""
Auto Membership Rule. Auto Membership Rule.
Bring clarity to the membership of hosts and users by configuring inclusive Bring clarity to the membership of hosts and users by configuring inclusive

View File

@ -16,7 +16,7 @@ from ipapython.dnsutil import DNSName
if six.PY3: if six.PY3:
unicode = str unicode = str
__doc__ = _(""" __doc__ = _(r"""
Groups of users Groups of users
Manage groups of users. By default, new groups are POSIX groups. You Manage groups of users. By default, new groups are POSIX groups. You

View File

@ -16,7 +16,7 @@ from ipapython.dnsutil import DNSName
if six.PY3: if six.PY3:
unicode = str unicode = str
__doc__ = _(""" __doc__ = _(r"""
Simulate use of Host-based access controls Simulate use of Host-based access controls
HBAC rules control who can access what services on what hosts. HBAC rules control who can access what services on what hosts.

View File

@ -16,7 +16,7 @@ from ipapython.dnsutil import DNSName
if six.PY3: if six.PY3:
unicode = str unicode = str
__doc__ = _(""" __doc__ = _(r"""
Cross-realm trusts Cross-realm trusts
Manage trust relationship between IPA and Active Directory domains. Manage trust relationship between IPA and Active Directory domains.

View File

@ -16,7 +16,7 @@ from ipapython.dnsutil import DNSName
if six.PY3: if six.PY3:
unicode = str unicode = str
__doc__ = _(""" __doc__ = _(r"""
Auto Membership Rule. Auto Membership Rule.
Bring clarity to the membership of hosts and users by configuring inclusive Bring clarity to the membership of hosts and users by configuring inclusive

View File

@ -16,7 +16,7 @@ from ipapython.dnsutil import DNSName
if six.PY3: if six.PY3:
unicode = str unicode = str
__doc__ = _(""" __doc__ = _(r"""
Groups of users Groups of users
Manage groups of users. By default, new groups are POSIX groups. You Manage groups of users. By default, new groups are POSIX groups. You

View File

@ -16,7 +16,7 @@ from ipapython.dnsutil import DNSName
if six.PY3: if six.PY3:
unicode = str unicode = str
__doc__ = _(""" __doc__ = _(r"""
Simulate use of Host-based access controls Simulate use of Host-based access controls
HBAC rules control who can access what services on what hosts. HBAC rules control who can access what services on what hosts.

View File

@ -16,7 +16,7 @@ from ipapython.dnsutil import DNSName
if six.PY3: if six.PY3:
unicode = str unicode = str
__doc__ = _(""" __doc__ = _(r"""
Cross-realm trusts Cross-realm trusts
Manage trust relationship between IPA and Active Directory domains. Manage trust relationship between IPA and Active Directory domains.

View File

@ -2,6 +2,8 @@
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license # Copyright (C) 2016 FreeIPA Contributors see COPYING for license
# #
from __future__ import unicode_literals
import importlib import importlib
import os import os
import re import re
@ -42,19 +44,19 @@ def get_package(server_info, client):
if not is_valid: if not is_valid:
if not client.isconnected(): if not client.isconnected():
client.connect(verbose=False) client.connect(verbose=False)
env = client.forward(u'env', u'api_version', version=u'2.0') env = client.forward('env', 'api_version', version='2.0')
try: try:
server_version = env['result']['api_version'] server_version = env['result']['api_version']
except KeyError: except KeyError:
ping = client.forward(u'ping', version=u'2.0') ping = client.forward('ping', version='2.0')
try: try:
match = re.search(u'API version (2\.[0-9]+)', ping['summary']) match = re.search(r'API version (2\.[0-9]+)', ping['summary'])
except KeyError: except KeyError:
match = None match = None
if match is not None: if match is not None:
server_version = match.group(1) server_version = match.group(1)
else: else:
server_version = u'2.0' server_version = '2.0'
server_info['version'] = server_version server_info['version'] = server_version
server_info.update_validity() server_info.update_validity()

View File

@ -24,6 +24,8 @@ The classes in this module make heavy use of Python container emulation. If
you are unfamiliar with this Python feature, see you are unfamiliar with this Python feature, see
http://docs.python.org/ref/sequence-types.html http://docs.python.org/ref/sequence-types.html
""" """
from __future__ import unicode_literals
import logging import logging
import operator import operator
import re import re
@ -173,7 +175,7 @@ class Plugin(ReadOnly):
def __summary_getter(cls): def __summary_getter(cls):
doc = cls.doc doc = cls.doc
if not _(doc).msg: if not _(doc).msg:
return u'<%s.%s>' % (cls.__module__, cls.__name__) return '<%s.%s>' % (cls.__module__, cls.__name__)
else: else:
return unicode(doc).split('\n\n', 1)[0].strip() return unicode(doc).split('\n\n', 1)[0].strip()
@ -467,7 +469,7 @@ class API(ReadOnly):
level = ipa_log_manager.convert_log_level(match.group(1)) level = ipa_log_manager.convert_log_level(match.group(1))
value = getattr(self.env, attr) value = getattr(self.env, attr)
regexps = re.split('\s*,\s*', value) regexps = re.split(r'\s*,\s*', value)
# Add the regexp, it maps to the configured level # Add the regexp, it maps to the configured level
for regexp in regexps: for regexp in regexps:

View File

@ -554,7 +554,7 @@ class NSSDatabase:
chain = result.output.splitlines() chain = result.output.splitlines()
for c in chain: for c in chain:
m = re.match('\s*"(.*)" \[.*', c) m = re.match(r'\s*"(.*)" \[.*', c)
if m: if m:
root_nicknames.append(m.groups()[0]) root_nicknames.append(m.groups()[0])

View File

@ -17,7 +17,7 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
''' r'''
Goal Goal
---- ----

View File

@ -310,7 +310,7 @@ def template_str(txt, vars):
# eval() is a special string one can insert into a template to have the # eval() is a special string one can insert into a template to have the
# Python interpreter evaluate the string. This is intended to allow # Python interpreter evaluate the string. This is intended to allow
# math to be performed in templates. # math to be performed in templates.
pattern = re.compile('(eval\s*\(([^()]*)\))') pattern = re.compile(r'(eval\s*\(([^()]*)\))')
val = pattern.sub(lambda x: str(eval(x.group(2))), val) val = pattern.sub(lambda x: str(eval(x.group(2))), val)
return val return val
@ -1145,7 +1145,7 @@ def config_replace_variables(filepath, replacevars=dict(), appendvars=dict(),
One have to run restore_context(filepath) afterwards or One have to run restore_context(filepath) afterwards or
security context of the file will not be correct after modification security context of the file will not be correct after modification
""" """
pattern = re.compile(''' pattern = re.compile(r'''
(^ (^
\s* \s*
(?P<option> [^\#;]+?) (?P<option> [^\#;]+?)
@ -1220,7 +1220,7 @@ def inifile_replace_variables(filepath, section, replacevars=dict(), appendvars=
One have to run restore_context(filepath) afterwards or One have to run restore_context(filepath) afterwards or
security context of the file will not be correct after modification security context of the file will not be correct after modification
""" """
pattern = re.compile(''' pattern = re.compile(r'''
(^ (^
\[ \[
(?P<section> .+) \] (?P<section> .+) \]

View File

@ -22,7 +22,7 @@
# Make sure we only run this module at the server where samba4-python # Make sure we only run this module at the server where samba4-python
# package is installed to avoid issues with unavailable modules # package is installed to avoid issues with unavailable modules
from __future__ import absolute_import from __future__ import absolute_import, unicode_literals
import logging import logging
import re import re
@ -634,7 +634,7 @@ class DomainValidator:
struct.unpack('<I', sid[8+4*i:12+4*i])[0] struct.unpack('<I', sid[8+4*i:12+4*i])[0]
for i in range(number_sub_id) for i in range(number_sub_id)
] ]
return u'S-%d-%d-%s' % (sid_rev_num, ia, return 'S-%d-%d-%s' % (sid_rev_num, ia,
'-'.join([str(s) for s in subs]),) '-'.join([str(s) for s in subs]),)
def kinit_as_administrator(self, domain): def kinit_as_administrator(self, domain):
@ -900,9 +900,9 @@ class TrustDomainInstance:
We try NCACN_NP before NCACN_IP_TCP and use SMB2 before SMB1. We try NCACN_NP before NCACN_IP_TCP and use SMB2 before SMB1.
""" """
transports = (u'ncacn_np', u'ncacn_ip_tcp') transports = ('ncacn_np', 'ncacn_ip_tcp')
options = (u'smb2,print', u'print') options = ('smb2,print', 'print')
return [u'%s:%s[%s]' % (t, remote_host, o) return ['%s:%s[%s]' % (t, remote_host, o)
for t in transports for o in options] for t in transports for o in options]
def retrieve_anonymously(self, remote_host, def retrieve_anonymously(self, remote_host,
@ -976,7 +976,7 @@ class TrustDomainInstance:
objectAttribute.sec_qos = lsa.QosInfo() objectAttribute.sec_qos = lsa.QosInfo()
try: try:
self._policy_handle = \ self._policy_handle = \
self._pipe.OpenPolicy2(u"", objectAttribute, self._pipe.OpenPolicy2("", objectAttribute,
security.SEC_FLAG_MAXIMUM_ALLOWED) security.SEC_FLAG_MAXIMUM_ALLOWED)
result = self._pipe.QueryInfoPolicy2(self._policy_handle, result = self._pipe.QueryInfoPolicy2(self._policy_handle,
lsa.LSA_POLICY_INFO_DNS) lsa.LSA_POLICY_INFO_DNS)
@ -1301,7 +1301,7 @@ class TrustDomainInstance:
""" """
if self.info['name'] == another_domain.info['name']: if self.info['name'] == another_domain.info['name']:
# Check that NetBIOS names do not clash # Check that NetBIOS names do not clash
raise errors.ValidationError(name=u'AD Trust Setup', raise errors.ValidationError(name='AD Trust Setup',
error=_('the IPA server and the ' error=_('the IPA server and the '
'remote domain cannot share ' 'remote domain cannot share '
'the same NetBIOS name: %s') 'the same NetBIOS name: %s')
@ -1597,7 +1597,7 @@ def retrieve_remote_domain(hostname, local_flatname,
# realm admin is in DOMAIN\user format # realm admin is in DOMAIN\user format
# strip DOMAIN part as we'll enforce the one discovered # strip DOMAIN part as we'll enforce the one discovered
realm_admin = names[-1] realm_admin = names[-1]
auth_string = u"%s\%s%%%s" \ auth_string = r"%s\%s%%%s" \
% (rd.info['name'], realm_admin, realm_passwd) % (rd.info['name'], realm_admin, realm_passwd)
td = get_instance(local_flatname) td = get_instance(local_flatname)
td.creds.parse_string(auth_string) td.creds.parse_string(auth_string)

View File

@ -2,7 +2,7 @@
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license # Copyright (C) 2016 FreeIPA Contributors see COPYING for license
# #
from __future__ import absolute_import from __future__ import absolute_import, unicode_literals
import logging import logging
@ -31,23 +31,23 @@ logger = logging.getLogger(__name__)
IPA_DEFAULT_MASTER_SRV_REC = ( IPA_DEFAULT_MASTER_SRV_REC = (
# srv record name, port # srv record name, port
(DNSName(u'_ldap._tcp'), 389), (DNSName('_ldap._tcp'), 389),
(DNSName(u'_kerberos._tcp'), 88), (DNSName('_kerberos._tcp'), 88),
(DNSName(u'_kerberos._udp'), 88), (DNSName('_kerberos._udp'), 88),
(DNSName(u'_kerberos-master._tcp'), 88), (DNSName('_kerberos-master._tcp'), 88),
(DNSName(u'_kerberos-master._udp'), 88), (DNSName('_kerberos-master._udp'), 88),
(DNSName(u'_kpasswd._tcp'), 464), (DNSName('_kpasswd._tcp'), 464),
(DNSName(u'_kpasswd._udp'), 464), (DNSName('_kpasswd._udp'), 464),
) )
IPA_DEFAULT_ADTRUST_SRV_REC = ( IPA_DEFAULT_ADTRUST_SRV_REC = (
# srv record name, port # srv record name, port
(DNSName(u'_ldap._tcp.Default-First-Site-Name._sites.dc._msdcs'), 389), (DNSName('_ldap._tcp.Default-First-Site-Name._sites.dc._msdcs'), 389),
(DNSName(u'_ldap._tcp.dc._msdcs'), 389), (DNSName('_ldap._tcp.dc._msdcs'), 389),
(DNSName(u'_kerberos._tcp.Default-First-Site-Name._sites.dc._msdcs'), 88), (DNSName('_kerberos._tcp.Default-First-Site-Name._sites.dc._msdcs'), 88),
(DNSName(u'_kerberos._udp.Default-First-Site-Name._sites.dc._msdcs'), 88), (DNSName('_kerberos._udp.Default-First-Site-Name._sites.dc._msdcs'), 88),
(DNSName(u'_kerberos._tcp.dc._msdcs'), 88), (DNSName('_kerberos._tcp.dc._msdcs'), 88),
(DNSName(u'_kerberos._udp.dc._msdcs'), 88), (DNSName('_kerberos._udp.dc._msdcs'), 88),
) )
IPA_DEFAULT_NTP_SRV_REC = ( IPA_DEFAULT_NTP_SRV_REC = (
@ -83,7 +83,7 @@ class IPASystemRecords:
self.__init_data() self.__init_data()
def __get_server_attrs(self, server_result): def __get_server_attrs(self, server_result):
weight = int(server_result.get('ipaserviceweight', [u'100'])[0]) weight = int(server_result.get('ipaserviceweight', ['100'])[0])
location = server_result.get('ipalocation_location', [None])[0] location = server_result.get('ipalocation_location', [None])[0]
roles = set(server_result.get('enabled_role_servrole', ())) roles = set(server_result.get('enabled_role_servrole', ()))
@ -98,7 +98,7 @@ class IPASystemRecords:
kwargs = dict(no_members=False) kwargs = dict(no_members=False)
if not all_servers: if not all_servers:
# only active, fully installed masters] # only active, fully installed masters]
kwargs["servrole"] = u"IPA master" kwargs["servrole"] = "IPA master"
servers = self.api_instance.Command.server_find(**kwargs) servers = self.api_instance.Command.server_find(**kwargs)
for s in servers['result']: for s in servers['result']:
@ -277,10 +277,10 @@ class IPASystemRecords:
): ):
update_dict = self.__prepare_records_update_dict(nodes) update_dict = self.__prepare_records_update_dict(nodes)
cname_template = { cname_template = {
'addattr': [u'objectclass=idnsTemplateObject'], 'addattr': ['objectclass=idnsTemplateObject'],
'setattr': [ 'setattr': [
u'idnsTemplateAttribute;cnamerecord=%s' r'idnsTemplateAttribute;cnamerecord=%s'
u'.\{substitutionvariable_ipalocation\}._locations' % r'.\{substitutionvariable_ipalocation\}._locations' %
record_name.relativize(self.domain_abs) record_name.relativize(self.domain_abs)
] ]
} }
@ -474,7 +474,7 @@ class IPASystemRecords:
for rdataset in node: for rdataset in node:
for rd in rdataset: for rd in rdataset:
records.append( records.append(
u'{name} {ttl} {rdclass} {rdtype} {rdata}'.format( '{name} {ttl} {rdclass} {rdtype} {rdata}'.format(
name=name.ToASCII(), name=name.ToASCII(),
ttl=rdataset.ttl, ttl=rdataset.ttl,
rdclass=rdataclass.to_text(rd.rdclass), rdclass=rdataclass.to_text(rd.rdclass),

View File

@ -675,7 +675,8 @@ class ADTRUSTInstance(service.Service):
has_dns_lookup_kdc_true = False has_dns_lookup_kdc_true = False
for line in krb5conf: for line in krb5conf:
if re.match("^\s*dns_lookup_kdc\s*=\s*[Tt][Rr][Uu][Ee]\s*$", line): regex = r"^\s*dns_lookup_kdc\s*=\s*[Tt][Rr][Uu][Ee]\s*$"
if re.match(regex, line):
has_dns_lookup_kdc_true = True has_dns_lookup_kdc_true = True
break break
krb5conf.close() krb5conf.close()

View File

@ -67,8 +67,8 @@ if six.PY3:
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
named_conf_section_ipa_start_re = re.compile('\s*dyndb\s+"ipa"\s+"[^"]+"\s+{') named_conf_section_ipa_start_re = re.compile(r'\s*dyndb\s+"ipa"\s+"[^"]+"\s+{')
named_conf_section_options_start_re = re.compile('\s*options\s+{') named_conf_section_options_start_re = re.compile(r'\s*options\s+{')
named_conf_section_end_re = re.compile('};') named_conf_section_end_re = re.compile('};')
named_conf_arg_ipa_re = re.compile( named_conf_arg_ipa_re = re.compile(
r'(?P<indent>\s*)(?P<name>\S+)\s"(?P<value>[^"]+)";') r'(?P<indent>\s*)(?P<name>\S+)\s"(?P<value>[^"]+)";')

View File

@ -463,7 +463,7 @@ class DsInstance(service.Service):
('cn', 'config')), ('cn', 'config')),
objectclass=["top", "nsSaslMapping"], objectclass=["top", "nsSaslMapping"],
cn=["Full Principal"], cn=["Full Principal"],
nsSaslMapRegexString=['\(.*\)@\(.*\)'], nsSaslMapRegexString=[r'\(.*\)@\(.*\)'],
nsSaslMapBaseDNTemplate=[self.suffix], nsSaslMapBaseDNTemplate=[self.suffix],
nsSaslMapFilterTemplate=['(krbPrincipalName=\\1@\\2)'], nsSaslMapFilterTemplate=['(krbPrincipalName=\\1@\\2)'],
nsSaslMapPriority=['10'], nsSaslMapPriority=['10'],

View File

@ -140,7 +140,7 @@ def find_autoredirect(fqdn):
""" """
filename = paths.HTTPD_IPA_REWRITE_CONF filename = paths.HTTPD_IPA_REWRITE_CONF
if os.path.exists(filename): if os.path.exists(filename):
pattern = "^RewriteRule \^/\$ https://%s/ipa/ui \[L,NC,R=301\]" % fqdn pattern = r"^RewriteRule \^/\$ https://%s/ipa/ui \[L,NC,R=301\]" % fqdn
p = re.compile(pattern) p = re.compile(pattern)
for line in fileinput.input(filename): for line in fileinput.input(filename):
if p.search(line): if p.search(line):
@ -157,7 +157,7 @@ def find_version(filename):
If the file does not exist, returns -1. If the file does not exist, returns -1.
""" """
if os.path.exists(filename): if os.path.exists(filename):
pattern = "^[\s#]*VERSION\s+([0-9]+)\s+.*" pattern = r"^[\s#]*VERSION\s+([0-9]+)\s+.*"
p = re.compile(pattern) p = re.compile(pattern)
for line in fileinput.input(filename): for line in fileinput.input(filename):
if p.search(line): if p.search(line):

View File

@ -70,11 +70,11 @@ EXAMPLES:
Add the initial rule: Add the initial rule:
ipa automember-add --type=hostgroup webservers ipa automember-add --type=hostgroup webservers
ipa automember-add --type=group devel ipa automember-add --type=group devel
""") + _(""" """) + _(r"""
Add a condition to the rule: Add a condition to the rule:
ipa automember-add-condition --key=fqdn --type=hostgroup --inclusive-regex=^web[1-9]+\.example\.com webservers ipa automember-add-condition --key=fqdn --type=hostgroup --inclusive-regex=^web[1-9]+\.example\.com webservers
ipa automember-add-condition --key=manager --type=group --inclusive-regex=^uid=mscott devel ipa automember-add-condition --key=manager --type=group --inclusive-regex=^uid=mscott devel
""") + _(""" """) + _(r"""
Add an exclusive condition to the rule to prevent auto assignment: Add an exclusive condition to the rule to prevent auto assignment:
ipa automember-add-condition --key=fqdn --type=hostgroup --exclusive-regex=^web5\.example\.com webservers ipa automember-add-condition --key=fqdn --type=hostgroup --exclusive-regex=^web5\.example\.com webservers
""") + _(""" """) + _("""
@ -95,7 +95,7 @@ EXAMPLES:
Description: Developers Description: Developers
GID: 1004200000 GID: 1004200000
Member users: tuser Member users: tuser
""") + _(""" """) + _(r"""
Remove a condition from the rule: Remove a condition from the rule:
ipa automember-remove-condition --key=fqdn --type=hostgroup --inclusive-regex=^web[1-9]+\.example\.com webservers ipa automember-remove-condition --key=fqdn --type=hostgroup --inclusive-regex=^web[1-9]+\.example\.com webservers
""") + _(""" """) + _("""

View File

@ -200,7 +200,7 @@ def validate_del_attribute(ugettext, attr):
validate_attribute(ugettext, 'delattr', attr) validate_attribute(ugettext, 'delattr', attr)
def validate_attribute(ugettext, name, attr): def validate_attribute(ugettext, name, attr):
m = re.match("\s*(.*?)\s*=\s*(.*?)\s*$", attr) m = re.match(r"\s*(.*?)\s*=\s*(.*?)\s*$", attr)
if not m or len(m.groups()) != 2: if not m or len(m.groups()) != 2:
raise errors.ValidationError( raise errors.ValidationError(
name=name, error=_('Invalid format. Should be name=value')) name=name, error=_('Invalid format. Should be name=value'))
@ -919,7 +919,7 @@ last, after all sets and adds."""),
elif type(attrs) not in (list, tuple): elif type(attrs) not in (list, tuple):
attrs = [attrs] attrs = [attrs]
for a in attrs: for a in attrs:
m = re.match("\s*(.*?)\s*=\s*(.*?)\s*$", a) m = re.match(r"\s*(.*?)\s*=\s*(.*?)\s*$", a)
attr = str(m.group(1)).lower() attr = str(m.group(1)).lower()
value = m.group(2) value = m.group(2)
if attr in self.obj.params and attr not in self.params: if attr in self.obj.params and attr not in self.params:

View File

@ -1458,7 +1458,7 @@ class TXTRecord(DNSRecord):
def _normalize_uri_target(uri_target): def _normalize_uri_target(uri_target):
"""DNS-escape "\ characters and double-quote target.""" r"""DNS-escape "\ characters and double-quote target."""
# is user-provided string is already quoted? # is user-provided string is already quoted?
if uri_target[0:1] == uri_target[-1:] == '"': if uri_target[0:1] == uri_target[-1:] == '"':
uri_target = uri_target[1:-1] uri_target = uri_target[1:-1]

View File

@ -42,7 +42,7 @@ except ImportError:
if six.PY3: if six.PY3:
unicode = str unicode = str
__doc__ = _(""" __doc__ = _(r"""
Simulate use of Host-based access controls Simulate use of Host-based access controls
HBAC rules control who can access what services on what hosts. HBAC rules control who can access what services on what hosts.

View File

@ -554,7 +554,7 @@ class host(LDAPObject):
), ),
Str('macaddress*', Str('macaddress*',
normalizer=lambda value: value.upper(), normalizer=lambda value: value.upper(),
pattern='^([a-fA-F0-9]{2}[:|\-]?){5}[a-fA-F0-9]{2}$', pattern=r'^([a-fA-F0-9]{2}[:|\-]?){5}[a-fA-F0-9]{2}$',
pattern_errmsg=('Must be of the form HH:HH:HH:HH:HH:HH, where ' pattern_errmsg=('Must be of the form HH:HH:HH:HH:HH:HH, where '
'each H is a hexadecimal character.'), 'each H is a hexadecimal character.'),
label=_('MAC address'), label=_('MAC address'),

View File

@ -390,7 +390,7 @@ class permission(baseldap.LDAPObject):
# memberof # memberof
memberof = [] memberof = []
for targetfilter in ipapermtargetfilter: for targetfilter in ipapermtargetfilter:
match = re.match('^\(memberof=(.*)\)$', targetfilter, re.I) match = re.match(r'^\(memberof=(.*)\)$', targetfilter, re.I)
if match: if match:
try: try:
dn = DN(match.group(1)) dn = DN(match.group(1))

View File

@ -50,9 +50,9 @@ def pytest_addoption(parser):
def _get_logname_from_node(node): def _get_logname_from_node(node):
name = node.nodeid name = node.nodeid
name = re.sub('\(\)/', '', name) # remove ()/ name = re.sub(r'\(\)/', '', name) # remove ()/
name = re.sub('[()]', '', name) # and standalone brackets name = re.sub(r'[()]', '', name) # and standalone brackets
name = re.sub('(/|::)', '-', name) name = re.sub(r'(/|::)', '-', name)
return name return name

View File

@ -76,7 +76,7 @@ def check_admin_in_cli(host):
# LDAP do not guarantee any order, so the test cannot assume it. Based on # LDAP do not guarantee any order, so the test cannot assume it. Based on
# that, the code bellow order the 'Member of groups' field to able to # that, the code bellow order the 'Member of groups' field to able to
# assert it latter. # assert it latter.
data = dict(re.findall("\W*(.+):\W*(.+)\W*", result.stdout_text)) data = dict(re.findall(r"\W*(.+):\W*(.+)\W*", result.stdout_text))
data["Member of groups"] = ', '.join(sorted(data["Member of groups"] data["Member of groups"] = ', '.join(sorted(data["Member of groups"]
.split(", "))) .split(", ")))
result.stdout_text = ''.join([' {}: {}\n'.format(k, v) result.stdout_text = ''.join([' {}: {}\n'.format(k, v)

View File

@ -51,7 +51,7 @@ def check_CA_flag(host, nssdb=paths.PKI_TOMCAT_ALIAS_DIR,
text = result.stdout_text text = result.stdout_text
# match CN in cert nickname and C flag in SSL section of NSS flags table # match CN in cert nickname and C flag in SSL section of NSS flags table
match_CA_flag = re.compile('.*{}.*\s+C'.format(cn)) match_CA_flag = re.compile(r'.*{}.*\s+C'.format(cn))
match = re.search(match_CA_flag, text) match = re.search(match_CA_flag, text)
return match return match

View File

@ -154,9 +154,9 @@ class BaseTestLegacyClient:
# Only for POSIX trust testing does the testuser belong to the # Only for POSIX trust testing does the testuser belong to the
# testgroup # testgroup
group_name = '\(%s\)' % testgroup if self.posix_trust else '' group_name = r'\(%s\)' % testgroup if self.posix_trust else ''
uid_regex = "uid=%s\(%s\)" % (self.testuser_uid_regex, testuser) uid_regex = r"uid=%s\(%s\)" % (self.testuser_uid_regex, testuser)
gid_regex = "gid=%s%s" % (self.testuser_gid_regex, group_name) gid_regex = "gid=%s%s" % (self.testuser_gid_regex, group_name)
groups_regex = "groups=%s%s" % (self.testuser_gid_regex, group_name) groups_regex = "groups=%s%s" % (self.testuser_gid_regex, group_name)
@ -282,9 +282,9 @@ class BaseTestLegacyClient:
# Only for POSIX trust testing does the testuser belong to the # Only for POSIX trust testing does the testuser belong to the
# testgroup # testgroup
group_name = '\(%s\)' % testgroup if self.posix_trust else '' group_name = r'\(%s\)' % testgroup if self.posix_trust else ''
uid_regex = "uid=%s\(%s\)" % (self.subdomain_testuser_uid_regex, uid_regex = r"uid=%s\(%s\)" % (self.subdomain_testuser_uid_regex,
testuser) testuser)
gid_regex = "gid=%s%s" % (self.subdomain_testuser_gid_regex, gid_regex = "gid=%s%s" % (self.subdomain_testuser_gid_regex,
group_name) group_name)
@ -381,9 +381,9 @@ class BaseTestLegacyClient:
# Only for POSIX trust testing does the testuser belong to the # Only for POSIX trust testing does the testuser belong to the
# testgroup # testgroup
group_name = '\({}\)'.format(testgroup) if self.posix_trust else '' group_name = r'\({}\)'.format(testgroup) if self.posix_trust else ''
uid_regex = "uid={0}\({1}\)".format( uid_regex = r"uid={0}\({1}\)".format(
self.treedomain_testuser_uid_regex, testuser) self.treedomain_testuser_uid_regex, testuser)
gid_regex = "gid={0}{1}".format( gid_regex = "gid={0}{1}".format(

View File

@ -20,8 +20,8 @@ reasoning = "Topology plugin disabled due to domain level 0"
def find_segment(master, replica): def find_segment(master, replica):
result = master.run_command(['ipa', 'topologysegment-find', result = master.run_command(['ipa', 'topologysegment-find',
DOMAIN_SUFFIX_NAME]).stdout_text DOMAIN_SUFFIX_NAME]).stdout_text
segment_re = re.compile('Left node: (?P<left>\S+)\n.*Right node: ' segment_re = re.compile(r'Left node: (?P<left>\S+)\n.*Right node: '
'(?P<right>\S+)\n') r'(?P<right>\S+)\n')
allsegments = segment_re.findall(result) allsegments = segment_re.findall(result)
for segment in allsegments: for segment in allsegments:
if master.hostname in segment and replica.hostname in segment: if master.hostname in segment and replica.hostname in segment:

View File

@ -21,6 +21,8 @@ Test adding/removing external members (trusted domain objects) to IPA groups.
These tests are skipped if trust is not established. These tests are skipped if trust is not established.
""" """
from __future__ import unicode_literals
import unittest import unittest
from ipalib import api from ipalib import api
@ -41,7 +43,7 @@ def get_trusted_group_name():
return None return None
ad_netbios = trusts['result'][0]['ipantflatname'] ad_netbios = trusts['result'][0]['ipantflatname']
return u'%s\Domain Admins' % ad_netbios return r'%s\Domain Admins' % ad_netbios
@pytest.mark.tier1 @pytest.mark.tier1

View File

@ -194,7 +194,7 @@ def assert_not_equal(val1, val2):
class Fuzzy: class Fuzzy:
""" r"""
Perform a fuzzy (non-strict) equality tests. Perform a fuzzy (non-strict) equality tests.
`Fuzzy` instances will likely be used when comparing nesting `Fuzzy` instances will likely be used when comparing nesting