Refs #27025 -- Fixed "invalid escape sequence" warnings in Python 3.6.

http://bugs.python.org/issue27364
This commit is contained in:
Tim Graham 2016-09-16 12:15:00 -04:00
parent 17677d510f
commit 8119b679eb
42 changed files with 82 additions and 82 deletions

View File

@ -2,31 +2,31 @@ from django.conf.urls import url
from django.contrib.admindocs import views from django.contrib.admindocs import views
urlpatterns = [ urlpatterns = [
url('^$', url(r'^$',
views.BaseAdminDocsView.as_view(template_name='admin_doc/index.html'), views.BaseAdminDocsView.as_view(template_name='admin_doc/index.html'),
name='django-admindocs-docroot'), name='django-admindocs-docroot'),
url('^bookmarklets/$', url(r'^bookmarklets/$',
views.BookmarkletsView.as_view(), views.BookmarkletsView.as_view(),
name='django-admindocs-bookmarklets'), name='django-admindocs-bookmarklets'),
url('^tags/$', url(r'^tags/$',
views.TemplateTagIndexView.as_view(), views.TemplateTagIndexView.as_view(),
name='django-admindocs-tags'), name='django-admindocs-tags'),
url('^filters/$', url(r'^filters/$',
views.TemplateFilterIndexView.as_view(), views.TemplateFilterIndexView.as_view(),
name='django-admindocs-filters'), name='django-admindocs-filters'),
url('^views/$', url(r'^views/$',
views.ViewIndexView.as_view(), views.ViewIndexView.as_view(),
name='django-admindocs-views-index'), name='django-admindocs-views-index'),
url('^views/(?P<view>[^/]+)/$', url(r'^views/(?P<view>[^/]+)/$',
views.ViewDetailView.as_view(), views.ViewDetailView.as_view(),
name='django-admindocs-views-detail'), name='django-admindocs-views-detail'),
url('^models/$', url(r'^models/$',
views.ModelIndexView.as_view(), views.ModelIndexView.as_view(),
name='django-admindocs-models-index'), name='django-admindocs-models-index'),
url('^models/(?P<app_label>[^\.]+)\.(?P<model_name>[^/]+)/$', url(r'^models/(?P<app_label>[^\.]+)\.(?P<model_name>[^/]+)/$',
views.ModelDetailView.as_view(), views.ModelDetailView.as_view(),
name='django-admindocs-models-detail'), name='django-admindocs-models-detail'),
url('^templates/(?P<template>.*)/$', url(r'^templates/(?P<template>.*)/$',
views.TemplateDetailView.as_view(), views.TemplateDetailView.as_view(),
name='django-admindocs-templates'), name='django-admindocs-templates'),
] ]

View File

@ -430,7 +430,7 @@ non_named_group_matcher = re.compile(r'\(.*?\)')
def simplify_regex(pattern): def simplify_regex(pattern):
""" r"""
Clean up urlpattern regexes into something more readable by humans. For Clean up urlpattern regexes into something more readable by humans. For
example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$" example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
into "/<sport_slug>/athletes/<athlete_slug>/". into "/<sport_slug>/athletes/<athlete_slug>/".

View File

@ -143,7 +143,7 @@ class UserAttributeSimilarityValidator(object):
value = getattr(user, attribute_name, None) value = getattr(user, attribute_name, None)
if not value or not isinstance(value, string_types): if not value or not isinstance(value, string_types):
continue continue
value_parts = re.split('\W+', value) + [value] value_parts = re.split(r'\W+', value) + [value]
for value_part in value_parts: for value_part in value_parts:
if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity: if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity:
try: try:

View File

@ -49,7 +49,7 @@ def intcomma(value, use_l10n=True):
else: else:
return number_format(value, force_grouping=True) return number_format(value, force_grouping=True)
orig = force_text(value) orig = force_text(value)
new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig) new = re.sub(r"^(-?\d+)(\d{3})", r'\g<1>,\g<2>', orig)
if orig == new: if orig == new:
return new return new
else: else:

View File

@ -78,7 +78,7 @@ def check_include_trailing_dollar(pattern):
Check that include is not used with a regex ending with a dollar. Check that include is not used with a regex ending with a dollar.
""" """
regex_pattern = pattern.regex.pattern regex_pattern = pattern.regex.pattern
if regex_pattern.endswith('$') and not regex_pattern.endswith('\$'): if regex_pattern.endswith('$') and not regex_pattern.endswith(r'\$'):
warning = Warning( warning = Warning(
"Your URL pattern {} uses include with a regex ending with a '$'. " "Your URL pattern {} uses include with a regex ending with a '$'. "
"Remove the dollar from the regex to avoid problems including " "Remove the dollar from the regex to avoid problems including "

View File

@ -88,12 +88,12 @@ class URLValidator(RegexValidator):
# Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1 # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
domain_re = r'(?:\.(?!-)[a-z' + ul + r'0-9-]{1,63}(?<!-))*' domain_re = r'(?:\.(?!-)[a-z' + ul + r'0-9-]{1,63}(?<!-))*'
tld_re = ( tld_re = (
'\.' # dot r'\.' # dot
'(?!-)' # can't start with a dash r'(?!-)' # can't start with a dash
'(?:[a-z' + ul + '-]{2,63}' # domain label r'(?:[a-z' + ul + '-]{2,63}' # domain label
'|xn--[a-z0-9]{1,59})' # or punycode label r'|xn--[a-z0-9]{1,59})' # or punycode label
'(?<!-)' # can't end with a dash r'(?<!-)' # can't end with a dash
'\.?' # may have a trailing dot r'\.?' # may have a trailing dot
) )
host_re = '(' + hostname_re + domain_re + tld_re + '|localhost)' host_re = '(' + hostname_re + domain_re + tld_re + '|localhost)'
@ -156,7 +156,7 @@ class URLValidator(RegexValidator):
raise ValidationError(self.message, code=self.code) raise ValidationError(self.message, code=self.code)
integer_validator = RegexValidator( integer_validator = RegexValidator(
_lazy_re_compile('^-?\d+\Z'), _lazy_re_compile(r'^-?\d+\Z'),
message=_('Enter a valid integer.'), message=_('Enter a valid integer.'),
code='invalid', code='invalid',
) )
@ -295,7 +295,7 @@ def ip_address_validators(protocol, unpack_ipv4):
def int_list_validator(sep=',', message=None, code='invalid', allow_negative=False): def int_list_validator(sep=',', message=None, code='invalid', allow_negative=False):
regexp = _lazy_re_compile('^%(neg)s\d+(?:%(sep)s%(neg)s\d+)*\Z' % { regexp = _lazy_re_compile(r'^%(neg)s\d+(?:%(sep)s%(neg)s\d+)*\Z' % {
'neg': '(-)?' if allow_negative else '', 'neg': '(-)?' if allow_negative else '',
'sep': re.escape(sep), 'sep': re.escape(sep),
}) })

View File

@ -428,7 +428,7 @@ class BaseDatabaseOperations(object):
def prep_for_like_query(self, x): def prep_for_like_query(self, x):
"""Prepares a value for use in a LIKE query.""" """Prepares a value for use in a LIKE query."""
return force_text(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_") return force_text(x).replace("\\", "\\\\").replace("%", r"\%").replace("_", r"\_")
# Same as prep_for_like_query(), but called for "iexact" matches, which # Same as prep_for_like_query(), but called for "iexact" matches, which
# need not necessarily be implemented using "LIKE" in the backend. # need not necessarily be implemented using "LIKE" in the backend.

View File

@ -125,14 +125,14 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
if field_desc.startswith("UNIQUE"): if field_desc.startswith("UNIQUE"):
continue continue
m = re.search('references (\S*) ?\(["|]?(.*)["|]?\)', field_desc, re.I) m = re.search(r'references (\S*) ?\(["|]?(.*)["|]?\)', field_desc, re.I)
if not m: if not m:
continue continue
table, column = [s.strip('"') for s in m.groups()] table, column = [s.strip('"') for s in m.groups()]
if field_desc.startswith("FOREIGN KEY"): if field_desc.startswith("FOREIGN KEY"):
# Find name of the target FK field # Find name of the target FK field
m = re.match('FOREIGN KEY\(([^\)]*)\).*', field_desc, re.I) m = re.match(r'FOREIGN KEY\(([^\)]*)\).*', field_desc, re.I)
field_name = m.groups()[0].strip('"') field_name = m.groups()[0].strip('"')
else: else:
field_name = field_desc.split()[0].strip('"') field_name = field_desc.split()[0].strip('"')
@ -175,7 +175,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
if field_desc.startswith("UNIQUE"): if field_desc.startswith("UNIQUE"):
continue continue
m = re.search('"(.*)".*references (.*) \(["|](.*)["|]\)', field_desc, re.I) m = re.search(r'"(.*)".*references (.*) \(["|](.*)["|]\)', field_desc, re.I)
if not m: if not m:
continue continue

View File

@ -181,7 +181,7 @@ class MigrationWriter(object):
# for comments # for comments
migration_imports = set() migration_imports = set()
for line in list(imports): for line in list(imports):
if re.match("^import (.*)\.\d+[^\s]*$", line): if re.match(r"^import (.*)\.\d+[^\s]*$", line):
migration_imports.add(line.split("import")[1].strip()) migration_imports.add(line.split("import")[1].strip())
imports.remove(line) imports.remove(line)
self.needs_manual_porting = True self.needs_manual_porting = True

View File

@ -639,7 +639,7 @@ filter_raw_string = r"""
)""" % { )""" % {
'constant': constant_string, 'constant': constant_string,
'num': r'[-+\.]?\d[\d\.e]*', 'num': r'[-+\.]?\d[\d\.e]*',
'var_chars': "\w\.", 'var_chars': r'\w\.',
'filter_sep': re.escape(FILTER_SEPARATOR), 'filter_sep': re.escape(FILTER_SEPARATOR),
'arg_sep': re.escape(FILTER_ARGUMENT_SEPARATOR), 'arg_sep': re.escape(FILTER_ARGUMENT_SEPARATOR),
} }

View File

@ -259,7 +259,7 @@ def stringformat(value, arg):
def title(value): def title(value):
"""Converts a string into titlecase.""" """Converts a string into titlecase."""
t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title()) t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title())
return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t) return re.sub(r"\d([A-Z])", lambda m: m.group(0).lower(), t)
@register.filter(is_safe=True) @register.filter(is_safe=True)

View File

@ -1329,7 +1329,7 @@ def templatetag(parser, token):
@register.tag @register.tag
def url(parser, token): def url(parser, token):
""" r"""
Return an absolute URL matching the given view with its parameters. Return an absolute URL matching the given view with its parameters.
This is a way to define links that aren't tied to a particular URL This is a way to define links that aren't tied to a particular URL

View File

@ -33,7 +33,7 @@ __all__ = ('Client', 'RedirectCycleError', 'RequestFactory', 'encode_file', 'enc
BOUNDARY = 'BoUnDaRyStRiNg' BOUNDARY = 'BoUnDaRyStRiNg'
MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY
CONTENT_TYPE_RE = re.compile('.*; charset=([\w\d-]+);?') CONTENT_TYPE_RE = re.compile(r'.*; charset=([\w\d-]+);?')
class RedirectCycleError(Exception): class RedirectCycleError(Exception):

View File

@ -10,7 +10,7 @@ from django.utils import six
from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.html_parser import HTMLParseError, HTMLParser from django.utils.html_parser import HTMLParseError, HTMLParser
WHITESPACE = re.compile('\s+') WHITESPACE = re.compile(r'\s+')
def normalize_whitespace(string): def normalize_whitespace(string):

View File

@ -36,7 +36,7 @@ simple_email_re = re.compile(r'^\S+@\S+\.\S+$')
link_target_attribute_re = re.compile(r'(<a [^>]*?)target=[^\s>]+') link_target_attribute_re = re.compile(r'(<a [^>]*?)target=[^\s>]+')
html_gunk_re = re.compile( html_gunk_re = re.compile(
r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|' r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|'
'<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE) r'<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE)
hard_coded_bullets_re = re.compile( hard_coded_bullets_re = re.compile(
r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join(re.escape(x) for x in DOTS), re.DOTALL r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join(re.escape(x) for x in DOTS), re.DOTALL
) )

View File

@ -48,7 +48,7 @@ class NonCapture(list):
def normalize(pattern): def normalize(pattern):
""" r"""
Given a reg-exp pattern, normalizes it to an iterable of forms that Given a reg-exp pattern, normalizes it to an iterable of forms that
suffice for reverse matching. This does the following: suffice for reverse matching. This does the following:
@ -203,7 +203,7 @@ def normalize(pattern):
def next_char(input_iter): def next_char(input_iter):
""" r"""
An iterator that yields the next character from "pattern_iter", respecting An iterator that yields the next character from "pattern_iter", respecting
escape sequences. An escaped character is replaced by a representative of escape sequences. An escaped character is replaced by a representative of
its class (e.g. \w -> "x"). If the escaped character is one that is its class (e.g. \w -> "x"). If the escaped character is one that is

View File

@ -423,11 +423,11 @@ def slugify(value, allow_unicode=False):
value = force_text(value) value = force_text(value)
if allow_unicode: if allow_unicode:
value = unicodedata.normalize('NFKC', value) value = unicodedata.normalize('NFKC', value)
value = re.sub('[^\w\s-]', '', value, flags=re.U).strip().lower() value = re.sub(r'[^\w\s-]', '', value, flags=re.U).strip().lower()
return mark_safe(re.sub('[-\s]+', '-', value, flags=re.U)) return mark_safe(re.sub(r'[-\s]+', '-', value, flags=re.U))
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub('[^\w\s-]', '', value).strip().lower() value = re.sub(r'[^\w\s-]', '', value).strip().lower()
return mark_safe(re.sub('[-\s]+', '-', value)) return mark_safe(re.sub(r'[-\s]+', '-', value))
def camel_case_to_spaces(value): def camel_case_to_spaces(value):

View File

@ -255,7 +255,7 @@ def get_language_info(lang_code):
info['name_translated'] = ugettext_lazy(info['name']) info['name_translated'] = ugettext_lazy(info['name'])
return info return info
trim_whitespace_re = re.compile('\s*\n\s*') trim_whitespace_re = re.compile(r'\s*\n\s*')
def trim_whitespace(s): def trim_whitespace(s):

View File

@ -537,7 +537,7 @@ TECHNICAL_500_TEMPLATE = ("""
<meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="robots" content="NONE,NOARCHIVE"> <meta name="robots" content="NONE,NOARCHIVE">
<title>{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %}""" <title>{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %}"""
"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title> r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title>
<style type="text/css"> <style type="text/css">
html * { padding:0; margin:0; } html * { padding:0; margin:0; }
body * { padding:10px 20px; } body * { padding:10px 20px; }

View File

@ -153,8 +153,8 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
def test_simplify_regex(self): def test_simplify_regex(self):
tests = ( tests = (
('^a', '/a'), ('^a', '/a'),
('^(?P<a>\w+)/b/(?P<c>\w+)/$', '/<a>/b/<c>/'), (r'^(?P<a>\w+)/b/(?P<c>\w+)/$', '/<a>/b/<c>/'),
('^(?P<a>\w+)/b/(?P<c>\w+)$', '/<a>/b/<c>'), (r'^(?P<a>\w+)/b/(?P<c>\w+)$', '/<a>/b/<c>'),
) )
for pattern, output in tests: for pattern, output in tests:
self.assertEqual(simplify_regex(pattern), output) self.assertEqual(simplify_regex(pattern), output)

View File

@ -717,7 +717,7 @@ class ManageNoSettings(AdminScriptTestCase):
args = ['check', 'admin_scripts'] args = ['check', 'admin_scripts']
out, err = self.run_manage(args) out, err = self.run_manage(args)
self.assertNoOutput(out) self.assertNoOutput(out)
self.assertOutput(err, "No module named '?(test_project\.)?settings'?", regex=True) self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True)
def test_builtin_with_bad_settings(self): def test_builtin_with_bad_settings(self):
"no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist" "no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist"
@ -950,7 +950,7 @@ class ManageAlternateSettings(AdminScriptTestCase):
args = ['check', 'admin_scripts'] args = ['check', 'admin_scripts']
out, err = self.run_manage(args) out, err = self.run_manage(args)
self.assertNoOutput(out) self.assertNoOutput(out)
self.assertOutput(err, "No module named '?(test_project\.)?settings'?", regex=True) self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True)
def test_builtin_with_settings(self): def test_builtin_with_settings(self):
"alternate: manage.py builtin commands work with settings provided as argument" "alternate: manage.py builtin commands work with settings provided as argument"
@ -985,7 +985,7 @@ class ManageAlternateSettings(AdminScriptTestCase):
args = ['noargs_command'] args = ['noargs_command']
out, err = self.run_manage(args) out, err = self.run_manage(args)
self.assertNoOutput(out) self.assertNoOutput(out)
self.assertOutput(err, "No module named '?(test_project\.)?settings'?", regex=True) self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True)
def test_custom_command_with_settings(self): def test_custom_command_with_settings(self):
"alternate: manage.py can execute user commands if settings are provided as argument" "alternate: manage.py can execute user commands if settings are provided as argument"

View File

@ -2289,7 +2289,7 @@ class AdminViewStringPrimaryKeyTest(TestCase):
cls.p1 = PrePopulatedPost.objects.create(title='A Long Title', published=True, slug='a-long-title') cls.p1 = PrePopulatedPost.objects.create(title='A Long Title', published=True, slug='a-long-title')
cls.pk = ( cls.pk = (
"abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 " "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 "
"""-_.!~*'() ;/?:@&=+$, <>#%" {}|\^[]`""" r"""-_.!~*'() ;/?:@&=+$, <>#%" {}|\^[]`"""
) )
cls.m1 = ModelWithStringPrimaryKey.objects.create(string_pk=cls.pk) cls.m1 = ModelWithStringPrimaryKey.objects.create(string_pk=cls.pk)
content_type_pk = ContentType.objects.get_for_model(ModelWithStringPrimaryKey).pk content_type_pk = ContentType.objects.get_for_model(ModelWithStringPrimaryKey).pk
@ -4323,7 +4323,7 @@ class SeleniumTests(AdminSeleniumTestCase):
self.selenium.find_element_by_id('id_relatedprepopulated_set-2-1-pubdate').send_keys('1981-08-22') self.selenium.find_element_by_id('id_relatedprepopulated_set-2-1-pubdate').send_keys('1981-08-22')
self.get_select_option('#id_relatedprepopulated_set-2-1-status', 'option one').click() self.get_select_option('#id_relatedprepopulated_set-2-1-status', 'option one').click()
self.selenium.find_element_by_id('id_relatedprepopulated_set-2-1-name').send_keys( self.selenium.find_element_by_id('id_relatedprepopulated_set-2-1-name').send_keys(
'a tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters' r'a tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters'
) )
slug1 = self.selenium.find_element_by_id('id_relatedprepopulated_set-2-1-slug1').get_attribute('value') slug1 = self.selenium.find_element_by_id('id_relatedprepopulated_set-2-1-slug1').get_attribute('value')
slug2 = self.selenium.find_element_by_id('id_relatedprepopulated_set-2-1-slug2').get_attribute('value') slug2 = self.selenium.find_element_by_id('id_relatedprepopulated_set-2-1-slug2').get_attribute('value')
@ -4365,7 +4365,7 @@ class SeleniumTests(AdminSeleniumTestCase):
slug2='option-two-and-now-tabular-inline', slug2='option-two-and-now-tabular-inline',
) )
RelatedPrepopulated.objects.get( RelatedPrepopulated.objects.get(
name='a tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters', name=r'a tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters',
pubdate='1981-08-22', pubdate='1981-08-22',
status='option one', status='option one',
slug1='tabular-inline-ignored-characters-1981-08-22', slug1='tabular-inline-ignored-characters-1981-08-22',

View File

@ -419,7 +419,7 @@ class AdminFileWidgetTests(TestDataMixin, TestCase):
self.assertHTMLEqual( self.assertHTMLEqual(
w.render('test', self.album.cover_art), w.render('test', self.album.cover_art),
'<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/'
'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> ' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> '
'<span class="clearable-file-input">' '<span class="clearable-file-input">'
'<input type="checkbox" name="test-clear" id="test-clear_id" /> ' '<input type="checkbox" name="test-clear" id="test-clear_id" /> '
'<label for="test-clear_id">Clear</label></span><br />' '<label for="test-clear_id">Clear</label></span><br />'
@ -441,7 +441,7 @@ class AdminFileWidgetTests(TestDataMixin, TestCase):
self.assertContains( self.assertContains(
response, response,
'<p><a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">' '<p><a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">'
'albums\hybrid_theory.jpg</a></p>' % {'STORAGE_URL': default_storage.url('')}, r'albums\hybrid_theory.jpg</a></p>' % {'STORAGE_URL': default_storage.url('')},
html=True, html=True,
) )
self.assertNotContains( self.assertNotContains(

View File

@ -117,8 +117,8 @@ class UserManagerTestCase(TestCase):
self.assertEqual(returned, 'normal@domain.com') self.assertEqual(returned, 'normal@domain.com')
def test_create_user_email_domain_normalize_with_whitespace(self): def test_create_user_email_domain_normalize_with_whitespace(self):
returned = UserManager.normalize_email('email\ with_whitespace@D.COM') returned = UserManager.normalize_email(r'email\ with_whitespace@D.COM')
self.assertEqual(returned, 'email\ with_whitespace@d.com') self.assertEqual(returned, r'email\ with_whitespace@d.com')
def test_empty_username(self): def test_empty_username(self):
with self.assertRaisesMessage(ValueError, 'The given username must be set'): with self.assertRaisesMessage(ValueError, 'The given username must be set'):

View File

@ -552,7 +552,7 @@ class ExpressionsTests(TestCase):
self.assertEqual(c_qs.get(), c) self.assertEqual(c_qs.get(), c)
def test_patterns_escape(self): def test_patterns_escape(self):
""" r"""
Test that special characters (e.g. %, _ and \) stored in database are Test that special characters (e.g. %, _ and \) stored in database are
properly escaped when using a pattern lookup with an expression properly escaped when using a pattern lookup with an expression
refs #16731 refs #16731
@ -584,7 +584,7 @@ class ExpressionsTests(TestCase):
ordered=False) ordered=False)
def test_insensitive_patterns_escape(self): def test_insensitive_patterns_escape(self):
""" r"""
Test that special characters (e.g. %, _ and \) stored in database are Test that special characters (e.g. %, _ and \) stored in database are
properly escaped when using a case insensitive pattern lookup with an properly escaped when using a case insensitive pattern lookup with an
expression -- refs #16731 expression -- refs #16731

View File

@ -158,11 +158,11 @@ class FieldDeconstructionTests(SimpleTestCase):
self.assertEqual(kwargs, {"upload_to": "foo/bar", "max_length": 200}) self.assertEqual(kwargs, {"upload_to": "foo/bar", "max_length": 200})
def test_file_path_field(self): def test_file_path_field(self):
field = models.FilePathField(match=".*\.txt$") field = models.FilePathField(match=r".*\.txt$")
name, path, args, kwargs = field.deconstruct() name, path, args, kwargs = field.deconstruct()
self.assertEqual(path, "django.db.models.FilePathField") self.assertEqual(path, "django.db.models.FilePathField")
self.assertEqual(args, []) self.assertEqual(args, [])
self.assertEqual(kwargs, {"match": ".*\.txt$"}) self.assertEqual(kwargs, {"match": r".*\.txt$"})
field = models.FilePathField(recursive=True, allow_folders=True, max_length=123) field = models.FilePathField(recursive=True, allow_folders=True, max_length=123)
name, path, args, kwargs = field.deconstruct() name, path, args, kwargs = field.deconstruct()
self.assertEqual(path, "django.db.models.FilePathField") self.assertEqual(path, "django.db.models.FilePathField")

View File

@ -53,7 +53,7 @@ class FilePathFieldTest(SimpleTestCase):
def test_filepathfield_3(self): def test_filepathfield_3(self):
path = upath(forms.__file__) path = upath(forms.__file__)
path = os.path.dirname(os.path.abspath(path)) + '/' path = os.path.dirname(os.path.abspath(path)) + '/'
f = FilePathField(path=path, match='^.*?\.py$') f = FilePathField(path=path, match=r'^.*?\.py$')
f.choices.sort() f.choices.sort()
expected = [ expected = [
('/django/forms/__init__.py', '__init__.py'), ('/django/forms/__init__.py', '__init__.py'),
@ -72,7 +72,7 @@ class FilePathFieldTest(SimpleTestCase):
def test_filepathfield_4(self): def test_filepathfield_4(self):
path = os.path.abspath(upath(forms.__file__)) path = os.path.abspath(upath(forms.__file__))
path = os.path.dirname(path) + '/' path = os.path.dirname(path) + '/'
f = FilePathField(path=path, recursive=True, match='^.*?\.py$') f = FilePathField(path=path, recursive=True, match=r'^.*?\.py$')
f.choices.sort() f.choices.sort()
expected = [ expected = [
('/django/forms/__init__.py', '__init__.py'), ('/django/forms/__init__.py', '__init__.py'),

View File

@ -48,8 +48,8 @@ class RegexFieldTest(SimpleTestCase):
f.clean('123') f.clean('123')
six.assertRaisesRegex( six.assertRaisesRegex(
self, ValidationError, self, ValidationError,
"'Ensure this value has at least 5 characters \(it has 3\)\.'," r"'Ensure this value has at least 5 characters \(it has 3\)\.',"
" u?'Enter a valid value\.'", r" u?'Enter a valid value\.'",
f.clean, 'abc' f.clean, 'abc'
) )
self.assertEqual('12345', f.clean('12345')) self.assertEqual('12345', f.clean('12345'))
@ -60,7 +60,7 @@ class RegexFieldTest(SimpleTestCase):
f.clean('12345a') f.clean('12345a')
def test_regexfield_unicode_characters(self): def test_regexfield_unicode_characters(self):
f = RegexField('^\w+$') f = RegexField(r'^\w+$')
self.assertEqual('éèøçÎÎ你好', f.clean('éèøçÎÎ你好')) self.assertEqual('éèøçÎÎ你好', f.clean('éèøçÎÎ你好'))
def test_change_regex_after_init(self): def test_change_regex_after_init(self):

View File

@ -23,7 +23,7 @@ class SplitDateTimeFieldTest(SimpleTestCase):
f.clean('') f.clean('')
with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"):
f.clean('hello') f.clean('hello')
with six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'"): with six.assertRaisesRegex(self, ValidationError, r"'Enter a valid date\.', u?'Enter a valid time\.'"):
f.clean(['hello', 'there']) f.clean(['hello', 'there'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean(['2006-01-10', 'there']) f.clean(['2006-01-10', 'there'])
@ -43,7 +43,7 @@ class SplitDateTimeFieldTest(SimpleTestCase):
self.assertIsNone(f.clean(['', ''])) self.assertIsNone(f.clean(['', '']))
with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"):
f.clean('hello') f.clean('hello')
with six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'"): with six.assertRaisesRegex(self, ValidationError, r"'Enter a valid date\.', u?'Enter a valid time\.'"):
f.clean(['hello', 'there']) f.clean(['hello', 'there'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean(['2006-01-10', 'there']) f.clean(['2006-01-10', 'there'])

View File

@ -2914,7 +2914,7 @@ Good luck picking a username that doesn&#39;t already exist.</p>
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
six.assertRaisesRegex( six.assertRaisesRegex(
self, ValidationError, self, ValidationError,
"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home'] r"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']
) )
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(['61', '287654321', '123', 'Home']) f.clean(['61', '287654321', '123', 'Home'])
@ -2930,7 +2930,7 @@ Good luck picking a username that doesn&#39;t already exist.</p>
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
six.assertRaisesRegex( six.assertRaisesRegex(
self, ValidationError, self, ValidationError,
"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home'] r"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']
) )
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(['61', '287654321', '123', 'Home']) f.clean(['61', '287654321', '123', 'Home'])

View File

@ -71,7 +71,7 @@ class GDALRasterTests(unittest.TestCase):
def test_rs_name_repr(self): def test_rs_name_repr(self):
self.assertEqual(self.rs_path, self.rs.name) self.assertEqual(self.rs_path, self.rs.name)
six.assertRegex(self, repr(self.rs), "<Raster object at 0x\w+>") six.assertRegex(self, repr(self.rs), r"<Raster object at 0x\w+>")
def test_rs_driver(self): def test_rs_driver(self):
self.assertEqual(self.rs.driver.name, 'GTiff') self.assertEqual(self.rs.driver.name, 'GTiff')

View File

@ -19,7 +19,7 @@ test_srs = ({
# From proj's "cs2cs -le" and Wikipedia (semi-minor only) # From proj's "cs2cs -le" and Wikipedia (semi-minor only)
'ellipsoid': (6378137.0, 6356752.3, 298.257223563), 'ellipsoid': (6378137.0, 6356752.3, 298.257223563),
'eprec': (1, 1, 9), 'eprec': (1, 1, 9),
'wkt': re.sub('[\s+]', '', """ 'wkt': re.sub(r'[\s+]', '', """
GEOGCS["WGS 84", GEOGCS["WGS 84",
DATUM["WGS_1984", DATUM["WGS_1984",
SPHEROID["WGS 84",6378137,298.257223563, SPHEROID["WGS 84",6378137,298.257223563,

View File

@ -97,7 +97,7 @@ class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
self.fail("The token '%s' could not be found in %s, please check the test config" % (token, path)) self.fail("The token '%s' could not be found in %s, please check the test config" % (token, path))
def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts): def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts):
""" r"""
self.assertLocationCommentPresent('django.po', 42, 'dirA', 'dirB', 'foo.py') self.assertLocationCommentPresent('django.po', 42, 'dirA', 'dirB', 'foo.py')
verifies that the django.po file has a gettext-style location comment of the form verifies that the django.po file has a gettext-style location comment of the form
@ -307,7 +307,7 @@ class BasicExtractorTests(ExtractorTests):
self, str(ws[2].message), self, str(ws[2].message),
r"The translator-targeted comment 'Translators: ignored i18n " r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #4' \(file templates[/\\]comments.thtml, line 8\) " r"comment #4' \(file templates[/\\]comments.thtml, line 8\) "
"was ignored, because it wasn't the last item on the line\." r"was ignored, because it wasn't the last item on the line\."
) )
# Now test .po file contents # Now test .po file contents
self.assertTrue(os.path.exists(self.PO_FILE)) self.assertTrue(os.path.exists(self.PO_FILE))

View File

@ -747,7 +747,7 @@ class FormattingTests(SimpleTestCase):
self.maxDiff = 3000 self.maxDiff = 3000
# Catalan locale # Catalan locale
with translation.override('ca', deactivate=True): with translation.override('ca', deactivate=True):
self.assertEqual('j \d\e F \d\e Y', get_format('DATE_FORMAT')) self.assertEqual(r'j \d\e F \d\e Y', get_format('DATE_FORMAT'))
self.assertEqual(1, get_format('FIRST_DAY_OF_WEEK')) self.assertEqual(1, get_format('FIRST_DAY_OF_WEEK'))
self.assertEqual(',', get_format('DECIMAL_SEPARATOR')) self.assertEqual(',', get_format('DECIMAL_SEPARATOR'))
self.assertEqual('10:15', time_format(self.t)) self.assertEqual('10:15', time_format(self.t))

View File

@ -411,7 +411,7 @@ class LookupTests(TestCase):
Article.objects.create(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22)) Article.objects.create(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22))
self.assertQuerysetEqual( self.assertQuerysetEqual(
Article.objects.filter(headline__contains='\\'), Article.objects.filter(headline__contains='\\'),
['<Article: Article with \ backslash>'] [r'<Article: Article with \ backslash>']
) )
def test_exclude(self): def test_exclude(self):

View File

@ -686,7 +686,7 @@ class ExecutorUnitTests(TestCase):
self.assertEqual(plan, [(a2_impl, True)]) self.assertEqual(plan, [(a2_impl, True)])
def test_minimize_rollbacks_branchy(self): def test_minimize_rollbacks_branchy(self):
""" r"""
Minimize rollbacks when target has multiple in-app children. Minimize rollbacks when target has multiple in-app children.
a: 1 <---- 3 <--\ a: 1 <---- 3 <--\
@ -731,7 +731,7 @@ class ExecutorUnitTests(TestCase):
self.assertEqual(plan, exp) self.assertEqual(plan, exp)
def test_backwards_nothing_to_do(self): def test_backwards_nothing_to_do(self):
""" r"""
If the current state satisfies the given target, do nothing. If the current state satisfies the given target, do nothing.
a: 1 <--- 2 a: 1 <--- 2

View File

@ -68,7 +68,7 @@ class GraphTests(SimpleTestCase):
) )
def test_complex_graph(self): def test_complex_graph(self):
""" r"""
Tests a complex dependency graph: Tests a complex dependency graph:
app_a: 0001 <-- 0002 <--- 0003 <-- 0004 app_a: 0001 <-- 0002 <--- 0003 <-- 0004

View File

@ -427,7 +427,7 @@ class LoaderTests(TestCase):
]}) ]})
def test_loading_squashed_ref_squashed(self): def test_loading_squashed_ref_squashed(self):
"Tests loading a squashed migration with a new migration referencing it" "Tests loading a squashed migration with a new migration referencing it"
""" r"""
The sample migrations are structured like this: The sample migrations are structured like this:
app_1 1 --> 2 ---------------------*--> 3 *--> 4 app_1 1 --> 2 ---------------------*--> 3 *--> 4

View File

@ -169,7 +169,7 @@ class CustomFF(models.Model):
class FilePathModel(models.Model): class FilePathModel(models.Model):
path = models.FilePathField(path=os.path.dirname(upath(__file__)), match=".*\.py$", blank=True) path = models.FilePathField(path=os.path.dirname(upath(__file__)), match=r".*\.py$", blank=True)
try: try:

View File

@ -98,7 +98,7 @@ class IfEqualTagTests(SimpleTestCase):
@setup({'ifequal-split09': r"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}"}) @setup({'ifequal-split09': r"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}"})
def test_ifequal_split09(self): def test_ifequal_split09(self):
output = self.engine.render_to_string('ifequal-split09', {'a': 'slash\man'}) output = self.engine.render_to_string('ifequal-split09', {'a': r'slash\man'})
self.assertEqual(output, 'yes') self.assertEqual(output, 'yes')
@setup({'ifequal-split10': r"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}"}) @setup({'ifequal-split10': r"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}"})

View File

@ -95,9 +95,9 @@ class TestUtilsHttp(unittest.TestCase):
r'\/example.com', r'\/example.com',
r'/\example.com', r'/\example.com',
'http:///example.com', 'http:///example.com',
'http:/\//example.com', r'http:/\//example.com',
'http:\/example.com', r'http:\/example.com',
'http:/\example.com', r'http:/\example.com',
'javascript:alert("XSS")', 'javascript:alert("XSS")',
'\njavascript:alert(x)', '\njavascript:alert(x)',
'\x08//example.com', '\x08//example.com',

View File

@ -67,7 +67,7 @@ class JsTokensTest(SimpleTestCase):
(r"""/a[\]]b/""", [r"""regex /a[\]]b/"""]), (r"""/a[\]]b/""", [r"""regex /a[\]]b/"""]),
(r"""/[\]/]/gi""", [r"""regex /[\]/]/gi"""]), (r"""/[\]/]/gi""", [r"""regex /[\]/]/gi"""]),
(r"""/\[[^\]]+\]/gi""", [r"""regex /\[[^\]]+\]/gi"""]), (r"""/\[[^\]]+\]/gi""", [r"""regex /\[[^\]]+\]/gi"""]),
(""" (r"""
rexl.re = { rexl.re = {
NAME: /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/, NAME: /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/,
UNQUOTED_LITERAL: /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/, UNQUOTED_LITERAL: /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/,
@ -86,7 +86,7 @@ class JsTokensTest(SimpleTestCase):
"punct }", "punct ;" "punct }", "punct ;"
]), ]),
(""" (r"""
rexl.re = { rexl.re = {
NAME: /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/, NAME: /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/,
UNQUOTED_LITERAL: /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/, UNQUOTED_LITERAL: /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/,