mirror of
https://github.com/django/django.git
synced 2025-01-22 00:02:15 +00:00
Refs #23919 -- Removed unneeded str() calls
This commit is contained in:
parent
4e729feaa6
commit
042b7350a0
@ -83,7 +83,7 @@ class OpenLayersWidget(Textarea):
|
|||||||
|
|
||||||
# JavaScript construction utilities for the Bounds and Projection.
|
# JavaScript construction utilities for the Bounds and Projection.
|
||||||
def ol_bounds(extent):
|
def ol_bounds(extent):
|
||||||
return 'new OpenLayers.Bounds(%s)' % str(extent)
|
return 'new OpenLayers.Bounds(%s)' % extent
|
||||||
|
|
||||||
def ol_projection(srid):
|
def ol_projection(srid):
|
||||||
return 'new OpenLayers.Projection("EPSG:%s")' % srid
|
return 'new OpenLayers.Projection("EPSG:%s")' % srid
|
||||||
|
@ -58,9 +58,9 @@ class PostGISAdapter:
|
|||||||
"""
|
"""
|
||||||
if self.is_geometry:
|
if self.is_geometry:
|
||||||
# Psycopg will figure out whether to use E'\\000' or '\000'.
|
# Psycopg will figure out whether to use E'\\000' or '\000'.
|
||||||
return str('%s(%s)' % (
|
return '%s(%s)' % (
|
||||||
'ST_GeogFromWKB' if self.geography else 'ST_GeomFromEWKB',
|
'ST_GeogFromWKB' if self.geography else 'ST_GeomFromEWKB',
|
||||||
self._adapter.getquoted().decode())
|
self._adapter.getquoted().decode()
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# For rasters, add explicit type cast to WKB string.
|
# For rasters, add explicit type cast to WKB string.
|
||||||
|
@ -65,7 +65,7 @@ class GeoFunc(Func):
|
|||||||
if check_types and not isinstance(value, check_types):
|
if check_types and not isinstance(value, check_types):
|
||||||
raise TypeError(
|
raise TypeError(
|
||||||
"The %s parameter has the wrong type: should be %s." % (
|
"The %s parameter has the wrong type: should be %s." % (
|
||||||
param_name, str(check_types))
|
param_name, check_types)
|
||||||
)
|
)
|
||||||
return value
|
return value
|
||||||
|
|
||||||
|
@ -109,7 +109,7 @@ class DataSource(GDALBase):
|
|||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
"Returns OGR GetName and Driver for the Data Source."
|
"Returns OGR GetName and Driver for the Data Source."
|
||||||
return '%s (%s)' % (self.name, str(self.driver))
|
return '%s (%s)' % (self.name, self.driver)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def layer_count(self):
|
def layer_count(self):
|
||||||
|
@ -60,11 +60,11 @@ class Driver(GDALBase):
|
|||||||
elif isinstance(dr_input, c_void_p):
|
elif isinstance(dr_input, c_void_p):
|
||||||
driver = dr_input
|
driver = dr_input
|
||||||
else:
|
else:
|
||||||
raise GDALException('Unrecognized input type for GDAL/OGR Driver: %s' % str(type(dr_input)))
|
raise GDALException('Unrecognized input type for GDAL/OGR Driver: %s' % type(dr_input))
|
||||||
|
|
||||||
# Making sure we get a valid pointer to the OGR Driver
|
# Making sure we get a valid pointer to the OGR Driver
|
||||||
if not driver:
|
if not driver:
|
||||||
raise GDALException('Could not initialize GDAL/OGR Driver on input: %s' % str(dr_input))
|
raise GDALException('Could not initialize GDAL/OGR Driver on input: %s' % dr_input)
|
||||||
self.ptr = driver
|
self.ptr = driver
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
|
@ -51,7 +51,7 @@ class Envelope:
|
|||||||
else:
|
else:
|
||||||
self._from_sequence(args[0])
|
self._from_sequence(args[0])
|
||||||
else:
|
else:
|
||||||
raise TypeError('Incorrect type of argument: %s' % str(type(args[0])))
|
raise TypeError('Incorrect type of argument: %s' % type(args[0]))
|
||||||
elif len(args) == 4:
|
elif len(args) == 4:
|
||||||
# Individual parameters passed in.
|
# Individual parameters passed in.
|
||||||
# Thanks to ww for the help
|
# Thanks to ww for the help
|
||||||
@ -123,7 +123,7 @@ class Envelope:
|
|||||||
else:
|
else:
|
||||||
raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
|
raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
|
||||||
else:
|
else:
|
||||||
raise TypeError('Incorrect type of argument: %s' % str(type(args[0])))
|
raise TypeError('Incorrect type of argument: %s' % type(args[0]))
|
||||||
elif len(args) == 2:
|
elif len(args) == 2:
|
||||||
# An x and an y parameter were passed in
|
# An x and an y parameter were passed in
|
||||||
return self.expand_to_include((args[0], args[1], args[0], args[1]))
|
return self.expand_to_include((args[0], args[1], args[0], args[1]))
|
||||||
|
@ -109,7 +109,7 @@ class OGRGeometry(GDALBase):
|
|||||||
# Now checking the Geometry pointer before finishing initialization
|
# Now checking the Geometry pointer before finishing initialization
|
||||||
# by setting the pointer for the object.
|
# by setting the pointer for the object.
|
||||||
if not g:
|
if not g:
|
||||||
raise GDALException('Cannot create OGR Geometry from input: %s' % str(geom_input))
|
raise GDALException('Cannot create OGR Geometry from input: %s' % geom_input)
|
||||||
self.ptr = g
|
self.ptr = g
|
||||||
|
|
||||||
# Assigning the SpatialReference object to the geometry, if valid.
|
# Assigning the SpatialReference object to the geometry, if valid.
|
||||||
@ -549,7 +549,7 @@ class LineString(OGRGeometry):
|
|||||||
elif dim == 3:
|
elif dim == 3:
|
||||||
return (x.value, y.value, z.value)
|
return (x.value, y.value, z.value)
|
||||||
else:
|
else:
|
||||||
raise OGRIndexError('index out of range: %s' % str(index))
|
raise OGRIndexError('index out of range: %s' % index)
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
"Iterates over each point in the LineString."
|
"Iterates over each point in the LineString."
|
||||||
|
@ -73,7 +73,7 @@ class GEOSCoordSeq(GEOSBase):
|
|||||||
"Checks the given index."
|
"Checks the given index."
|
||||||
sz = self.size
|
sz = self.size
|
||||||
if (sz < 1) or (index < 0) or (index >= sz):
|
if (sz < 1) or (index < 0) or (index >= sz):
|
||||||
raise IndexError('invalid GEOS Geometry index: %s' % str(index))
|
raise IndexError('invalid GEOS Geometry index: %s' % index)
|
||||||
|
|
||||||
def _checkdim(self, dim):
|
def _checkdim(self, dim):
|
||||||
"Checks the given dimension."
|
"Checks the given dimension."
|
||||||
|
@ -73,7 +73,7 @@ class GEOSGeometry(GEOSBase, ListMixin):
|
|||||||
g = capi.geom_clone(geo_input.ptr)
|
g = capi.geom_clone(geo_input.ptr)
|
||||||
else:
|
else:
|
||||||
# Invalid geometry type.
|
# Invalid geometry type.
|
||||||
raise TypeError('Improper geometry input type: %s' % str(type(geo_input)))
|
raise TypeError('Improper geometry input type: %s' % type(geo_input))
|
||||||
|
|
||||||
if g:
|
if g:
|
||||||
# Setting the pointer object with a valid pointer.
|
# Setting the pointer object with a valid pointer.
|
||||||
|
@ -179,7 +179,7 @@ class ListMixin:
|
|||||||
for i in range(0, len(self)):
|
for i in range(0, len(self)):
|
||||||
if self[i] == val:
|
if self[i] == val:
|
||||||
return i
|
return i
|
||||||
raise ValueError('%s not found in object' % str(val))
|
raise ValueError('%s not found in object' % val)
|
||||||
|
|
||||||
# ## Mutating ##
|
# ## Mutating ##
|
||||||
def append(self, val):
|
def append(self, val):
|
||||||
@ -242,7 +242,7 @@ class ListMixin:
|
|||||||
return index
|
return index
|
||||||
if correct and -length <= index < 0:
|
if correct and -length <= index < 0:
|
||||||
return index + length
|
return index + length
|
||||||
raise IndexError('invalid index: %s' % str(index))
|
raise IndexError('invalid index: %s' % index)
|
||||||
|
|
||||||
def _check_allowed(self, items):
|
def _check_allowed(self, items):
|
||||||
if hasattr(self, '_allowed'):
|
if hasattr(self, '_allowed'):
|
||||||
|
@ -56,7 +56,7 @@ class Point(GEOSGeometry):
|
|||||||
return capi.create_point(None)
|
return capi.create_point(None)
|
||||||
|
|
||||||
if ndim < 2 or ndim > 3:
|
if ndim < 2 or ndim > 3:
|
||||||
raise TypeError('Invalid point dimension: %s' % str(ndim))
|
raise TypeError('Invalid point dimension: %s' % ndim)
|
||||||
|
|
||||||
cs = capi.create_cs(c_uint(1), c_uint(ndim))
|
cs = capi.create_cs(c_uint(1), c_uint(ndim))
|
||||||
i = iter(coords)
|
i = iter(coords)
|
||||||
|
@ -153,9 +153,9 @@ class WSGIHandler(base.BaseHandler):
|
|||||||
response._handler_class = self.__class__
|
response._handler_class = self.__class__
|
||||||
|
|
||||||
status = '%d %s' % (response.status_code, response.reason_phrase)
|
status = '%d %s' % (response.status_code, response.reason_phrase)
|
||||||
response_headers = [(str(k), str(v)) for k, v in response.items()]
|
response_headers = list(response.items())
|
||||||
for c in response.cookies.values():
|
for c in response.cookies.values():
|
||||||
response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
|
response_headers.append(('Set-Cookie', c.output(header='')))
|
||||||
start_response(status, response_headers)
|
start_response(status, response_headers)
|
||||||
if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
|
if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
|
||||||
response = environ['wsgi.file_wrapper'](response.file_to_stream)
|
response = environ['wsgi.file_wrapper'](response.file_to_stream)
|
||||||
@ -208,9 +208,9 @@ def get_bytes_from_wsgi(environ, key, default):
|
|||||||
"""
|
"""
|
||||||
Get a value from the WSGI environ dictionary as bytes.
|
Get a value from the WSGI environ dictionary as bytes.
|
||||||
|
|
||||||
key and default should be str objects.
|
key and default should be strings.
|
||||||
"""
|
"""
|
||||||
value = environ.get(str(key), str(default))
|
value = environ.get(key, default)
|
||||||
# Non-ASCII values in the WSGI environ are arbitrarily decoded with
|
# Non-ASCII values in the WSGI environ are arbitrarily decoded with
|
||||||
# ISO-8859-1. This is wrong for Django websites where UTF-8 is the default.
|
# ISO-8859-1. This is wrong for Django websites where UTF-8 is the default.
|
||||||
# Re-encode to recover the original bytestring.
|
# Re-encode to recover the original bytestring.
|
||||||
|
@ -68,7 +68,7 @@ def forbid_multi_line_headers(name, val, encoding):
|
|||||||
else:
|
else:
|
||||||
if name.lower() == 'subject':
|
if name.lower() == 'subject':
|
||||||
val = Header(val).encode()
|
val = Header(val).encode()
|
||||||
return str(name), val
|
return name, val
|
||||||
|
|
||||||
|
|
||||||
def split_addr(addr, encoding):
|
def split_addr(addr, encoding):
|
||||||
|
@ -398,7 +398,7 @@ class Command(BaseCommand):
|
|||||||
self.process_files(file_list)
|
self.process_files(file_list)
|
||||||
potfiles = []
|
potfiles = []
|
||||||
for path in self.locale_paths:
|
for path in self.locale_paths:
|
||||||
potfile = os.path.join(path, '%s.pot' % str(self.domain))
|
potfile = os.path.join(path, '%s.pot' % self.domain)
|
||||||
if not os.path.exists(potfile):
|
if not os.path.exists(potfile):
|
||||||
continue
|
continue
|
||||||
args = ['msguniq'] + self.msguniq_options + [potfile]
|
args = ['msguniq'] + self.msguniq_options + [potfile]
|
||||||
@ -417,7 +417,7 @@ class Command(BaseCommand):
|
|||||||
|
|
||||||
def remove_potfiles(self):
|
def remove_potfiles(self):
|
||||||
for path in self.locale_paths:
|
for path in self.locale_paths:
|
||||||
pot_path = os.path.join(path, '%s.pot' % str(self.domain))
|
pot_path = os.path.join(path, '%s.pot' % self.domain)
|
||||||
if os.path.exists(pot_path):
|
if os.path.exists(pot_path):
|
||||||
os.unlink(pot_path)
|
os.unlink(pot_path)
|
||||||
|
|
||||||
@ -583,7 +583,7 @@ class Command(BaseCommand):
|
|||||||
)
|
)
|
||||||
for build_file in build_files:
|
for build_file in build_files:
|
||||||
msgs = build_file.postprocess_messages(msgs)
|
msgs = build_file.postprocess_messages(msgs)
|
||||||
potfile = os.path.join(locale_dir, '%s.pot' % str(self.domain))
|
potfile = os.path.join(locale_dir, '%s.pot' % self.domain)
|
||||||
write_pot_file(potfile, msgs)
|
write_pot_file(potfile, msgs)
|
||||||
|
|
||||||
for build_file in build_files:
|
for build_file in build_files:
|
||||||
@ -599,7 +599,7 @@ class Command(BaseCommand):
|
|||||||
basedir = os.path.join(os.path.dirname(potfile), locale, 'LC_MESSAGES')
|
basedir = os.path.join(os.path.dirname(potfile), locale, 'LC_MESSAGES')
|
||||||
if not os.path.isdir(basedir):
|
if not os.path.isdir(basedir):
|
||||||
os.makedirs(basedir)
|
os.makedirs(basedir)
|
||||||
pofile = os.path.join(basedir, '%s.po' % str(self.domain))
|
pofile = os.path.join(basedir, '%s.po' % self.domain)
|
||||||
|
|
||||||
if os.path.exists(pofile):
|
if os.path.exists(pofile):
|
||||||
args = ['msgmerge'] + self.msgmerge_options + [pofile, potfile]
|
args = ['msgmerge'] + self.msgmerge_options + [pofile, potfile]
|
||||||
|
@ -56,7 +56,7 @@ class Command(BaseCommand):
|
|||||||
# We rely on the environment because it's currently the only
|
# We rely on the environment because it's currently the only
|
||||||
# way to reach WSGIRequestHandler. This seems an acceptable
|
# way to reach WSGIRequestHandler. This seems an acceptable
|
||||||
# compromise considering `runserver` runs indefinitely.
|
# compromise considering `runserver` runs indefinitely.
|
||||||
os.environ[str("DJANGO_COLORS")] = str("nocolor")
|
os.environ["DJANGO_COLORS"] = "nocolor"
|
||||||
super(Command, self).execute(*args, **options)
|
super(Command, self).execute(*args, **options)
|
||||||
|
|
||||||
def get_handler(self, *args, **options):
|
def get_handler(self, *args, **options):
|
||||||
|
@ -103,7 +103,7 @@ class WSGIRequestHandler(simple_server.WSGIRequestHandler):
|
|||||||
}
|
}
|
||||||
if args[1][0] == '4':
|
if args[1][0] == '4':
|
||||||
# 0x16 = Handshake, 0x03 = SSL 3.0 or TLS 1.x
|
# 0x16 = Handshake, 0x03 = SSL 3.0 or TLS 1.x
|
||||||
if args[0].startswith(str('\x16\x03')):
|
if args[0].startswith('\x16\x03'):
|
||||||
extra['status_code'] = 500
|
extra['status_code'] = 500
|
||||||
logger.error(
|
logger.error(
|
||||||
"You're accessing the development server over HTTPS, but "
|
"You're accessing the development server over HTTPS, but "
|
||||||
|
@ -45,13 +45,13 @@ def decoder(conv_func):
|
|||||||
return lambda s: conv_func(s.decode('utf-8'))
|
return lambda s: conv_func(s.decode('utf-8'))
|
||||||
|
|
||||||
|
|
||||||
Database.register_converter(str("bool"), decoder(lambda s: s == '1'))
|
Database.register_converter("bool", decoder(lambda s: s == '1'))
|
||||||
Database.register_converter(str("time"), decoder(parse_time))
|
Database.register_converter("time", decoder(parse_time))
|
||||||
Database.register_converter(str("date"), decoder(parse_date))
|
Database.register_converter("date", decoder(parse_date))
|
||||||
Database.register_converter(str("datetime"), decoder(parse_datetime))
|
Database.register_converter("datetime", decoder(parse_datetime))
|
||||||
Database.register_converter(str("timestamp"), decoder(parse_datetime))
|
Database.register_converter("timestamp", decoder(parse_datetime))
|
||||||
Database.register_converter(str("TIMESTAMP"), decoder(parse_datetime))
|
Database.register_converter("TIMESTAMP", decoder(parse_datetime))
|
||||||
Database.register_converter(str("decimal"), decoder(backend_utils.typecast_decimal))
|
Database.register_converter("decimal", decoder(backend_utils.typecast_decimal))
|
||||||
|
|
||||||
Database.register_adapter(decimal.Decimal, backend_utils.rev_typecast_decimal)
|
Database.register_adapter(decimal.Decimal, backend_utils.rev_typecast_decimal)
|
||||||
|
|
||||||
|
@ -35,10 +35,10 @@ from django.utils.version import get_version
|
|||||||
|
|
||||||
class Deferred:
|
class Deferred:
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return str('<Deferred field>')
|
return '<Deferred field>'
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return str('<Deferred field>')
|
return '<Deferred field>'
|
||||||
|
|
||||||
|
|
||||||
DEFERRED = Deferred()
|
DEFERRED = Deferred()
|
||||||
@ -118,7 +118,7 @@ class ModelBase(type):
|
|||||||
new_class.add_to_class(
|
new_class.add_to_class(
|
||||||
'DoesNotExist',
|
'DoesNotExist',
|
||||||
subclass_exception(
|
subclass_exception(
|
||||||
str('DoesNotExist'),
|
'DoesNotExist',
|
||||||
tuple(
|
tuple(
|
||||||
x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.abstract
|
x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.abstract
|
||||||
) or (ObjectDoesNotExist,),
|
) or (ObjectDoesNotExist,),
|
||||||
@ -127,7 +127,7 @@ class ModelBase(type):
|
|||||||
new_class.add_to_class(
|
new_class.add_to_class(
|
||||||
'MultipleObjectsReturned',
|
'MultipleObjectsReturned',
|
||||||
subclass_exception(
|
subclass_exception(
|
||||||
str('MultipleObjectsReturned'),
|
'MultipleObjectsReturned',
|
||||||
tuple(
|
tuple(
|
||||||
x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.abstract
|
x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.abstract
|
||||||
) or (MultipleObjectsReturned,),
|
) or (MultipleObjectsReturned,),
|
||||||
|
@ -32,9 +32,7 @@ from django.utils.itercompat import is_iterable
|
|||||||
from django.utils.text import capfirst
|
from django.utils.text import capfirst
|
||||||
from django.utils.translation import ugettext_lazy as _
|
from django.utils.translation import ugettext_lazy as _
|
||||||
|
|
||||||
# Avoid "TypeError: Item in ``from list'' not a string" -- unicode_literals
|
__all__ = [
|
||||||
# makes these strings unicode
|
|
||||||
__all__ = [str(x) for x in (
|
|
||||||
'AutoField', 'BLANK_CHOICE_DASH', 'BigAutoField', 'BigIntegerField',
|
'AutoField', 'BLANK_CHOICE_DASH', 'BigAutoField', 'BigIntegerField',
|
||||||
'BinaryField', 'BooleanField', 'CharField', 'CommaSeparatedIntegerField',
|
'BinaryField', 'BooleanField', 'CharField', 'CommaSeparatedIntegerField',
|
||||||
'DateField', 'DateTimeField', 'DecimalField', 'DurationField',
|
'DateField', 'DateTimeField', 'DecimalField', 'DurationField',
|
||||||
@ -43,7 +41,7 @@ __all__ = [str(x) for x in (
|
|||||||
'NOT_PROVIDED', 'NullBooleanField', 'PositiveIntegerField',
|
'NOT_PROVIDED', 'NullBooleanField', 'PositiveIntegerField',
|
||||||
'PositiveSmallIntegerField', 'SlugField', 'SmallIntegerField', 'TextField',
|
'PositiveSmallIntegerField', 'SlugField', 'SmallIntegerField', 'TextField',
|
||||||
'TimeField', 'URLField', 'UUIDField',
|
'TimeField', 'URLField', 'UUIDField',
|
||||||
)]
|
]
|
||||||
|
|
||||||
|
|
||||||
class Empty:
|
class Empty:
|
||||||
|
@ -277,7 +277,7 @@ class FileField(Field):
|
|||||||
def get_prep_value(self, value):
|
def get_prep_value(self, value):
|
||||||
"Returns field's value prepared for saving into a database."
|
"Returns field's value prepared for saving into a database."
|
||||||
value = super(FileField, self).get_prep_value(value)
|
value = super(FileField, self).get_prep_value(value)
|
||||||
# Need to convert File objects provided via a form to unicode for database insertion
|
# Need to convert File objects provided via a form to string for database insertion
|
||||||
if value is None:
|
if value is None:
|
||||||
return None
|
return None
|
||||||
return str(value)
|
return str(value)
|
||||||
|
@ -2,7 +2,7 @@ import hashlib
|
|||||||
|
|
||||||
from django.utils.encoding import force_bytes
|
from django.utils.encoding import force_bytes
|
||||||
|
|
||||||
__all__ = [str('Index')]
|
__all__ = ['Index']
|
||||||
|
|
||||||
# The max length of the names of the indexes (restricted to 30 due to Oracle)
|
# The max length of the names of the indexes (restricted to 30 due to Oracle)
|
||||||
MAX_NAME_LENGTH = 30
|
MAX_NAME_LENGTH = 30
|
||||||
|
@ -22,13 +22,13 @@ def parse_cookie(cookie):
|
|||||||
Return a dictionary parsed from a `Cookie:` header string.
|
Return a dictionary parsed from a `Cookie:` header string.
|
||||||
"""
|
"""
|
||||||
cookiedict = {}
|
cookiedict = {}
|
||||||
for chunk in cookie.split(str(';')):
|
for chunk in cookie.split(';'):
|
||||||
if str('=') in chunk:
|
if '=' in chunk:
|
||||||
key, val = chunk.split(str('='), 1)
|
key, val = chunk.split('=', 1)
|
||||||
else:
|
else:
|
||||||
# Assume an empty name per
|
# Assume an empty name per
|
||||||
# https://bugzilla.mozilla.org/show_bug.cgi?id=169091
|
# https://bugzilla.mozilla.org/show_bug.cgi?id=169091
|
||||||
key, val = str(''), chunk
|
key, val = '', chunk
|
||||||
key, val = key.strip(), val.strip()
|
key, val = key.strip(), val.strip()
|
||||||
if key or val:
|
if key or val:
|
||||||
# unquote using Python's algorithm.
|
# unquote using Python's algorithm.
|
||||||
|
@ -509,11 +509,11 @@ class QueryDict(MultiValueDict):
|
|||||||
# this slightly more restricted function, used by QueryDict.
|
# this slightly more restricted function, used by QueryDict.
|
||||||
def bytes_to_text(s, encoding):
|
def bytes_to_text(s, encoding):
|
||||||
"""
|
"""
|
||||||
Converts basestring objects to unicode, using the given encoding. Illegally
|
Convert bytes objects to strings, using the given encoding. Illegally
|
||||||
encoded input characters are replaced with Unicode "unknown" codepoint
|
encoded input characters are replaced with Unicode "unknown" codepoint
|
||||||
(\ufffd).
|
(\ufffd).
|
||||||
|
|
||||||
Returns any non-basestring objects without change.
|
Return any non-bytes objects without change.
|
||||||
"""
|
"""
|
||||||
if isinstance(s, bytes):
|
if isinstance(s, bytes):
|
||||||
return str(s, encoding, 'replace')
|
return str(s, encoding, 'replace')
|
||||||
|
@ -124,8 +124,7 @@ class HttpResponseBase:
|
|||||||
value = value.decode(charset)
|
value = value.decode(charset)
|
||||||
except UnicodeError as e:
|
except UnicodeError as e:
|
||||||
if mime_encode:
|
if mime_encode:
|
||||||
# Wrapping in str() is a workaround for #12422 under Python 2.
|
value = Header(value, 'utf-8', maxlinelen=sys.maxsize).encode()
|
||||||
value = str(Header(value, 'utf-8', maxlinelen=sys.maxsize).encode())
|
|
||||||
else:
|
else:
|
||||||
e.reason += ', HTTP response headers must be in %s format' % charset
|
e.reason += ', HTTP response headers must be in %s format' % charset
|
||||||
raise
|
raise
|
||||||
|
@ -281,15 +281,15 @@ class RequestFactory:
|
|||||||
# See http://www.python.org/dev/peps/pep-3333/#environ-variables
|
# See http://www.python.org/dev/peps/pep-3333/#environ-variables
|
||||||
environ = {
|
environ = {
|
||||||
'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
|
'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
|
||||||
'PATH_INFO': str('/'),
|
'PATH_INFO': '/',
|
||||||
'REMOTE_ADDR': str('127.0.0.1'),
|
'REMOTE_ADDR': '127.0.0.1',
|
||||||
'REQUEST_METHOD': str('GET'),
|
'REQUEST_METHOD': 'GET',
|
||||||
'SCRIPT_NAME': str(''),
|
'SCRIPT_NAME': '',
|
||||||
'SERVER_NAME': str('testserver'),
|
'SERVER_NAME': 'testserver',
|
||||||
'SERVER_PORT': str('80'),
|
'SERVER_PORT': '80',
|
||||||
'SERVER_PROTOCOL': str('HTTP/1.1'),
|
'SERVER_PROTOCOL': 'HTTP/1.1',
|
||||||
'wsgi.version': (1, 0),
|
'wsgi.version': (1, 0),
|
||||||
'wsgi.url_scheme': str('http'),
|
'wsgi.url_scheme': 'http',
|
||||||
'wsgi.input': FakePayload(b''),
|
'wsgi.input': FakePayload(b''),
|
||||||
'wsgi.errors': self.errors,
|
'wsgi.errors': self.errors,
|
||||||
'wsgi.multiprocess': True,
|
'wsgi.multiprocess': True,
|
||||||
@ -393,14 +393,14 @@ class RequestFactory:
|
|||||||
data = force_bytes(data, settings.DEFAULT_CHARSET)
|
data = force_bytes(data, settings.DEFAULT_CHARSET)
|
||||||
r = {
|
r = {
|
||||||
'PATH_INFO': self._get_path(parsed),
|
'PATH_INFO': self._get_path(parsed),
|
||||||
'REQUEST_METHOD': str(method),
|
'REQUEST_METHOD': method,
|
||||||
'SERVER_PORT': str('443') if secure else str('80'),
|
'SERVER_PORT': '443' if secure else '80',
|
||||||
'wsgi.url_scheme': str('https') if secure else str('http'),
|
'wsgi.url_scheme': 'https' if secure else 'http',
|
||||||
}
|
}
|
||||||
if data:
|
if data:
|
||||||
r.update({
|
r.update({
|
||||||
'CONTENT_LENGTH': len(data),
|
'CONTENT_LENGTH': len(data),
|
||||||
'CONTENT_TYPE': str(content_type),
|
'CONTENT_TYPE': content_type,
|
||||||
'wsgi.input': FakePayload(data),
|
'wsgi.input': FakePayload(data),
|
||||||
})
|
})
|
||||||
r.update(extra)
|
r.update(extra)
|
||||||
|
@ -35,7 +35,7 @@ class SeleniumTestCaseBase(type(LiveServerTestCase)):
|
|||||||
for browser in test_class.browsers[1:]:
|
for browser in test_class.browsers[1:]:
|
||||||
browser_test_class = cls.__new__(
|
browser_test_class = cls.__new__(
|
||||||
cls,
|
cls,
|
||||||
str("%s%s" % (capfirst(browser), name)),
|
"%s%s" % (capfirst(browser), name),
|
||||||
(test_class,),
|
(test_class,),
|
||||||
{'browser': browser, '__module__': test_class.__module__}
|
{'browser': browser, '__module__': test_class.__module__}
|
||||||
)
|
)
|
||||||
|
@ -236,7 +236,7 @@ class RegexURLResolver(LocaleRegexProvider):
|
|||||||
urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__
|
urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__
|
||||||
else:
|
else:
|
||||||
urlconf_repr = repr(self.urlconf_name)
|
urlconf_repr = repr(self.urlconf_name)
|
||||||
return str('<%s %s (%s:%s) %s>') % (
|
return '<%s %s (%s:%s) %s>' % (
|
||||||
self.__class__.__name__, urlconf_repr, self.app_name,
|
self.__class__.__name__, urlconf_repr, self.app_name,
|
||||||
self.namespace, self.regex.pattern,
|
self.namespace, self.regex.pattern,
|
||||||
)
|
)
|
||||||
|
@ -193,7 +193,7 @@ def smart_urlquote(url):
|
|||||||
# Tilde is part of RFC3986 Unreserved Characters
|
# Tilde is part of RFC3986 Unreserved Characters
|
||||||
# http://tools.ietf.org/html/rfc3986#section-2.3
|
# http://tools.ietf.org/html/rfc3986#section-2.3
|
||||||
# See also http://bugs.python.org/issue16285
|
# See also http://bugs.python.org/issue16285
|
||||||
segment = quote(segment, safe=RFC3986_SUBDELIMS + RFC3986_GENDELIMS + str('~'))
|
segment = quote(segment, safe=RFC3986_SUBDELIMS + RFC3986_GENDELIMS + '~')
|
||||||
return force_text(segment)
|
return force_text(segment)
|
||||||
|
|
||||||
# Handle IDN before quoting.
|
# Handle IDN before quoting.
|
||||||
|
@ -40,8 +40,8 @@ RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T))
|
|||||||
RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T))
|
RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T))
|
||||||
ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y))
|
ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y))
|
||||||
|
|
||||||
RFC3986_GENDELIMS = str(":/?#[]@")
|
RFC3986_GENDELIMS = ":/?#[]@"
|
||||||
RFC3986_SUBDELIMS = str("!$&'()*+,;=")
|
RFC3986_SUBDELIMS = "!$&'()*+,;="
|
||||||
|
|
||||||
FIELDS_MATCH = re.compile('[&;]')
|
FIELDS_MATCH = re.compile('[&;]')
|
||||||
|
|
||||||
@ -365,7 +365,7 @@ def limited_parse_qsl(qs, keep_blank_values=False, encoding='utf-8',
|
|||||||
for name_value in pairs:
|
for name_value in pairs:
|
||||||
if not name_value:
|
if not name_value:
|
||||||
continue
|
continue
|
||||||
nv = name_value.split(str('='), 1)
|
nv = name_value.split('=', 1)
|
||||||
if len(nv) != 2:
|
if len(nv) != 2:
|
||||||
# Handle case of a control-name with no equal sign
|
# Handle case of a control-name with no equal sign
|
||||||
if keep_blank_values:
|
if keep_blank_values:
|
||||||
|
@ -95,7 +95,7 @@ def _safety_decorator(safety_marker, func):
|
|||||||
def mark_safe(s):
|
def mark_safe(s):
|
||||||
"""
|
"""
|
||||||
Explicitly mark a string as safe for (HTML) output purposes. The returned
|
Explicitly mark a string as safe for (HTML) output purposes. The returned
|
||||||
object can be used everywhere a string or unicode object is appropriate.
|
object can be used everywhere a string is appropriate.
|
||||||
|
|
||||||
If used on a method as a decorator, mark the returned data as safe.
|
If used on a method as a decorator, mark the returned data as safe.
|
||||||
|
|
||||||
|
@ -307,8 +307,7 @@ def do_translate(message, translation_function):
|
|||||||
"""
|
"""
|
||||||
global _default
|
global _default
|
||||||
|
|
||||||
# str() is allowing a bytestring message to remain bytestring on Python 2
|
eol_message = message.replace('\r\n', '\n').replace('\r', '\n')
|
||||||
eol_message = message.replace(str('\r\n'), str('\n')).replace(str('\r'), str('\n'))
|
|
||||||
|
|
||||||
if len(eol_message) == 0:
|
if len(eol_message) == 0:
|
||||||
# Returns an empty value of the corresponding type if an empty message
|
# Returns an empty value of the corresponding type if an empty message
|
||||||
|
@ -25,7 +25,7 @@ def get_version(version=None):
|
|||||||
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'rc'}
|
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'rc'}
|
||||||
sub = mapping[version[3]] + str(version[4])
|
sub = mapping[version[3]] + str(version[4])
|
||||||
|
|
||||||
return str(main + sub)
|
return main + sub
|
||||||
|
|
||||||
|
|
||||||
def get_main_version(version=None):
|
def get_main_version(version=None):
|
||||||
|
@ -145,14 +145,13 @@ class AdminScriptTestCase(unittest.TestCase):
|
|||||||
|
|
||||||
# Set the test environment
|
# Set the test environment
|
||||||
if settings_file:
|
if settings_file:
|
||||||
test_environ['DJANGO_SETTINGS_MODULE'] = str(settings_file)
|
test_environ['DJANGO_SETTINGS_MODULE'] = settings_file
|
||||||
elif 'DJANGO_SETTINGS_MODULE' in test_environ:
|
elif 'DJANGO_SETTINGS_MODULE' in test_environ:
|
||||||
del test_environ['DJANGO_SETTINGS_MODULE']
|
del test_environ['DJANGO_SETTINGS_MODULE']
|
||||||
python_path = [base_dir, django_dir, tests_dir]
|
python_path = [base_dir, django_dir, tests_dir]
|
||||||
python_path.extend(ext_backend_base_dirs)
|
python_path.extend(ext_backend_base_dirs)
|
||||||
# Use native strings for better compatibility
|
test_environ[python_path_var_name] = os.pathsep.join(python_path)
|
||||||
test_environ[str(python_path_var_name)] = os.pathsep.join(python_path)
|
test_environ['PYTHONWARNINGS'] = ''
|
||||||
test_environ[str('PYTHONWARNINGS')] = str('')
|
|
||||||
|
|
||||||
# Move to the test directory and run
|
# Move to the test directory and run
|
||||||
os.chdir(self.test_dir)
|
os.chdir(self.test_dir)
|
||||||
|
@ -37,10 +37,7 @@ def mock_inputs(inputs):
|
|||||||
return inputs['password']
|
return inputs['password']
|
||||||
|
|
||||||
def mock_input(prompt):
|
def mock_input(prompt):
|
||||||
# prompt should be encoded in Python 2. This line will raise an
|
assert '__proxy__' not in prompt
|
||||||
# Exception if prompt contains unencoded non-ASCII on Python 2.
|
|
||||||
prompt = str(prompt)
|
|
||||||
assert str('__proxy__') not in prompt
|
|
||||||
response = ''
|
response = ''
|
||||||
for key, val in inputs.items():
|
for key, val in inputs.items():
|
||||||
if key in prompt.lower():
|
if key in prompt.lower():
|
||||||
|
@ -10,7 +10,7 @@ MAX_SOCKET_CHUNK_SIZE = 32 * 1024 * 1024 # 32 MB
|
|||||||
|
|
||||||
|
|
||||||
class ServerHandler(simple_server.ServerHandler):
|
class ServerHandler(simple_server.ServerHandler):
|
||||||
error_status = str("500 INTERNAL SERVER ERROR")
|
error_status = "500 INTERNAL SERVER ERROR"
|
||||||
|
|
||||||
def write(self, data):
|
def write(self, data):
|
||||||
"""'write()' callable as specified by PEP 3333"""
|
"""'write()' callable as specified by PEP 3333"""
|
||||||
@ -55,12 +55,12 @@ class FileWrapperHandler(ServerHandler):
|
|||||||
|
|
||||||
|
|
||||||
def wsgi_app(environ, start_response):
|
def wsgi_app(environ, start_response):
|
||||||
start_response(str('200 OK'), [(str('Content-Type'), str('text/plain'))])
|
start_response('200 OK', [('Content-Type', 'text/plain')])
|
||||||
return [b'Hello World!']
|
return [b'Hello World!']
|
||||||
|
|
||||||
|
|
||||||
def wsgi_app_file_wrapper(environ, start_response):
|
def wsgi_app_file_wrapper(environ, start_response):
|
||||||
start_response(str('200 OK'), [(str('Content-Type'), str('text/plain'))])
|
start_response('200 OK', [('Content-Type', 'text/plain')])
|
||||||
return environ['wsgi.file_wrapper'](BytesIO(b'foo'))
|
return environ['wsgi.file_wrapper'](BytesIO(b'foo'))
|
||||||
|
|
||||||
|
|
||||||
@ -113,7 +113,7 @@ class WriteChunkCounterHandler(ServerHandler):
|
|||||||
|
|
||||||
|
|
||||||
def send_big_data_app(environ, start_response):
|
def send_big_data_app(environ, start_response):
|
||||||
start_response(str('200 OK'), [(str('Content-Type'), str('text/plain'))])
|
start_response('200 OK', [('Content-Type', 'text/plain')])
|
||||||
# Return a blob of data that is 1.5 times the maximum chunk size.
|
# Return a blob of data that is 1.5 times the maximum chunk size.
|
||||||
return [b'x' * (MAX_SOCKET_CHUNK_SIZE + MAX_SOCKET_CHUNK_SIZE // 2)]
|
return [b'x' * (MAX_SOCKET_CHUNK_SIZE + MAX_SOCKET_CHUNK_SIZE // 2)]
|
||||||
|
|
||||||
|
@ -248,7 +248,7 @@ class RelatedModelFormTests(SimpleTestCase):
|
|||||||
fields = '__all__'
|
fields = '__all__'
|
||||||
|
|
||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
ModelFormMetaclass(str('Form'), (ModelForm,), {'Meta': Meta})
|
ModelFormMetaclass('Form', (ModelForm,), {'Meta': Meta})
|
||||||
|
|
||||||
class B(models.Model):
|
class B(models.Model):
|
||||||
pass
|
pass
|
||||||
@ -267,7 +267,7 @@ class RelatedModelFormTests(SimpleTestCase):
|
|||||||
model = C
|
model = C
|
||||||
fields = '__all__'
|
fields = '__all__'
|
||||||
|
|
||||||
self.assertTrue(issubclass(ModelFormMetaclass(str('Form'), (ModelForm,), {'Meta': Meta}), ModelForm))
|
self.assertTrue(issubclass(ModelFormMetaclass('Form', (ModelForm,), {'Meta': Meta}), ModelForm))
|
||||||
|
|
||||||
|
|
||||||
class ManyToManyExclusionTestCase(TestCase):
|
class ManyToManyExclusionTestCase(TestCase):
|
||||||
|
@ -81,7 +81,7 @@ class GetObjectOr404Tests(TestCase):
|
|||||||
# raises a helpful ValueError message
|
# raises a helpful ValueError message
|
||||||
msg = "First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'str'."
|
msg = "First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'str'."
|
||||||
with self.assertRaisesMessage(ValueError, msg):
|
with self.assertRaisesMessage(ValueError, msg):
|
||||||
get_object_or_404(str("Article"), title__icontains="Run")
|
get_object_or_404("Article", title__icontains="Run")
|
||||||
|
|
||||||
class CustomClass:
|
class CustomClass:
|
||||||
pass
|
pass
|
||||||
|
@ -201,7 +201,7 @@ class GetOrCreateTestsWithManualPKs(TestCase):
|
|||||||
ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different")
|
ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different")
|
||||||
except IntegrityError:
|
except IntegrityError:
|
||||||
formatted_traceback = traceback.format_exc()
|
formatted_traceback = traceback.format_exc()
|
||||||
self.assertIn(str('obj.save'), formatted_traceback)
|
self.assertIn('obj.save', formatted_traceback)
|
||||||
|
|
||||||
# MySQL emits a warning when broken data is saved
|
# MySQL emits a warning when broken data is saved
|
||||||
@ignore_warnings(module='django.db.backends.mysql.base')
|
@ignore_warnings(module='django.db.backends.mysql.base')
|
||||||
|
@ -21,7 +21,7 @@ from django.utils.functional import lazystr
|
|||||||
|
|
||||||
class QueryDictTests(SimpleTestCase):
|
class QueryDictTests(SimpleTestCase):
|
||||||
def test_create_with_no_args(self):
|
def test_create_with_no_args(self):
|
||||||
self.assertEqual(QueryDict(), QueryDict(str('')))
|
self.assertEqual(QueryDict(), QueryDict(''))
|
||||||
|
|
||||||
def test_missing_key(self):
|
def test_missing_key(self):
|
||||||
q = QueryDict()
|
q = QueryDict()
|
||||||
@ -63,7 +63,7 @@ class QueryDictTests(SimpleTestCase):
|
|||||||
def test_single_key_value(self):
|
def test_single_key_value(self):
|
||||||
"""Test QueryDict with one key/value pair"""
|
"""Test QueryDict with one key/value pair"""
|
||||||
|
|
||||||
q = QueryDict(str('foo=bar'))
|
q = QueryDict('foo=bar')
|
||||||
self.assertEqual(q['foo'], 'bar')
|
self.assertEqual(q['foo'], 'bar')
|
||||||
with self.assertRaises(KeyError):
|
with self.assertRaises(KeyError):
|
||||||
q.__getitem__('bar')
|
q.__getitem__('bar')
|
||||||
@ -166,7 +166,7 @@ class QueryDictTests(SimpleTestCase):
|
|||||||
def test_multiple_keys(self):
|
def test_multiple_keys(self):
|
||||||
"""Test QueryDict with two key/value pairs with same keys."""
|
"""Test QueryDict with two key/value pairs with same keys."""
|
||||||
|
|
||||||
q = QueryDict(str('vote=yes&vote=no'))
|
q = QueryDict('vote=yes&vote=no')
|
||||||
|
|
||||||
self.assertEqual(q['vote'], 'no')
|
self.assertEqual(q['vote'], 'no')
|
||||||
with self.assertRaises(AttributeError):
|
with self.assertRaises(AttributeError):
|
||||||
@ -209,23 +209,23 @@ class QueryDictTests(SimpleTestCase):
|
|||||||
q = QueryDict()
|
q = QueryDict()
|
||||||
q1 = pickle.loads(pickle.dumps(q, 2))
|
q1 = pickle.loads(pickle.dumps(q, 2))
|
||||||
self.assertEqual(q, q1)
|
self.assertEqual(q, q1)
|
||||||
q = QueryDict(str('a=b&c=d'))
|
q = QueryDict('a=b&c=d')
|
||||||
q1 = pickle.loads(pickle.dumps(q, 2))
|
q1 = pickle.loads(pickle.dumps(q, 2))
|
||||||
self.assertEqual(q, q1)
|
self.assertEqual(q, q1)
|
||||||
q = QueryDict(str('a=b&c=d&a=1'))
|
q = QueryDict('a=b&c=d&a=1')
|
||||||
q1 = pickle.loads(pickle.dumps(q, 2))
|
q1 = pickle.loads(pickle.dumps(q, 2))
|
||||||
self.assertEqual(q, q1)
|
self.assertEqual(q, q1)
|
||||||
|
|
||||||
def test_update_from_querydict(self):
|
def test_update_from_querydict(self):
|
||||||
"""Regression test for #8278: QueryDict.update(QueryDict)"""
|
"""Regression test for #8278: QueryDict.update(QueryDict)"""
|
||||||
x = QueryDict(str("a=1&a=2"), mutable=True)
|
x = QueryDict("a=1&a=2", mutable=True)
|
||||||
y = QueryDict(str("a=3&a=4"))
|
y = QueryDict("a=3&a=4")
|
||||||
x.update(y)
|
x.update(y)
|
||||||
self.assertEqual(x.getlist('a'), ['1', '2', '3', '4'])
|
self.assertEqual(x.getlist('a'), ['1', '2', '3', '4'])
|
||||||
|
|
||||||
def test_non_default_encoding(self):
|
def test_non_default_encoding(self):
|
||||||
"""#13572 - QueryDict with a non-default encoding"""
|
"""#13572 - QueryDict with a non-default encoding"""
|
||||||
q = QueryDict(str('cur=%A4'), encoding='iso-8859-15')
|
q = QueryDict('cur=%A4', encoding='iso-8859-15')
|
||||||
self.assertEqual(q.encoding, 'iso-8859-15')
|
self.assertEqual(q.encoding, 'iso-8859-15')
|
||||||
self.assertEqual(list(q.items()), [('cur', '€')])
|
self.assertEqual(list(q.items()), [('cur', '€')])
|
||||||
self.assertEqual(q.urlencode(), 'cur=%A4')
|
self.assertEqual(q.urlencode(), 'cur=%A4')
|
||||||
@ -280,16 +280,11 @@ class HttpResponseTests(unittest.TestCase):
|
|||||||
def test_headers_type(self):
|
def test_headers_type(self):
|
||||||
r = HttpResponse()
|
r = HttpResponse()
|
||||||
|
|
||||||
# The following tests explicitly test types in addition to values
|
# ASCII unicode or bytes values are converted to strings.
|
||||||
# because in Python 2 u'foo' == b'foo'.
|
|
||||||
|
|
||||||
# ASCII unicode or bytes values are converted to native strings.
|
|
||||||
r['key'] = 'test'
|
r['key'] = 'test'
|
||||||
self.assertEqual(r['key'], str('test'))
|
self.assertEqual(r['key'], 'test')
|
||||||
self.assertIsInstance(r['key'], str)
|
|
||||||
r['key'] = 'test'.encode('ascii')
|
r['key'] = 'test'.encode('ascii')
|
||||||
self.assertEqual(r['key'], str('test'))
|
self.assertEqual(r['key'], 'test')
|
||||||
self.assertIsInstance(r['key'], str)
|
|
||||||
self.assertIn(b'test', r.serialize_headers())
|
self.assertIn(b'test', r.serialize_headers())
|
||||||
|
|
||||||
# Non-ASCII values are serialized to Latin-1.
|
# Non-ASCII values are serialized to Latin-1.
|
||||||
@ -298,8 +293,7 @@ class HttpResponseTests(unittest.TestCase):
|
|||||||
|
|
||||||
# Other unicode values are MIME-encoded (there's no way to pass them as bytes).
|
# Other unicode values are MIME-encoded (there's no way to pass them as bytes).
|
||||||
r['key'] = '†'
|
r['key'] = '†'
|
||||||
self.assertEqual(r['key'], str('=?utf-8?b?4oCg?='))
|
self.assertEqual(r['key'], '=?utf-8?b?4oCg?=')
|
||||||
self.assertIsInstance(r['key'], str)
|
|
||||||
self.assertIn(b'=?utf-8?b?4oCg?=', r.serialize_headers())
|
self.assertIn(b'=?utf-8?b?4oCg?=', r.serialize_headers())
|
||||||
|
|
||||||
# The response also converts unicode or bytes keys to strings, but requires
|
# The response also converts unicode or bytes keys to strings, but requires
|
||||||
@ -310,7 +304,6 @@ class HttpResponseTests(unittest.TestCase):
|
|||||||
headers = list(r.items())
|
headers = list(r.items())
|
||||||
self.assertEqual(len(headers), 1)
|
self.assertEqual(len(headers), 1)
|
||||||
self.assertEqual(headers[0], ('foo', 'bar'))
|
self.assertEqual(headers[0], ('foo', 'bar'))
|
||||||
self.assertIsInstance(headers[0][0], str)
|
|
||||||
|
|
||||||
r = HttpResponse()
|
r = HttpResponse()
|
||||||
del r['Content-Type']
|
del r['Content-Type']
|
||||||
|
@ -142,7 +142,7 @@ class CompilationErrorHandling(MessageCompilationTests):
|
|||||||
# po file contains invalid msgstr content (triggers non-ascii error content).
|
# po file contains invalid msgstr content (triggers non-ascii error content).
|
||||||
# Make sure the output of msgfmt is unaffected by the current locale.
|
# Make sure the output of msgfmt is unaffected by the current locale.
|
||||||
env = os.environ.copy()
|
env = os.environ.copy()
|
||||||
env.update({str('LANG'): str('C')})
|
env.update({'LANG': 'C'})
|
||||||
with mock.patch('django.core.management.utils.Popen', lambda *args, **kwargs: Popen(*args, env=env, **kwargs)):
|
with mock.patch('django.core.management.utils.Popen', lambda *args, **kwargs: Popen(*args, env=env, **kwargs)):
|
||||||
cmd = MakeMessagesCommand()
|
cmd = MakeMessagesCommand()
|
||||||
if cmd.gettext_version < (0, 18, 3):
|
if cmd.gettext_version < (0, 18, 3):
|
||||||
|
@ -24,8 +24,8 @@ from django.utils.safestring import SafeBytes, SafeText
|
|||||||
from django.utils.translation import (
|
from django.utils.translation import (
|
||||||
LANGUAGE_SESSION_KEY, activate, check_for_language, deactivate,
|
LANGUAGE_SESSION_KEY, activate, check_for_language, deactivate,
|
||||||
get_language, get_language_from_request, get_language_info, gettext_lazy,
|
get_language, get_language_from_request, get_language_info, gettext_lazy,
|
||||||
ngettext_lazy, npgettext, npgettext_lazy, pgettext, trans_real, ugettext,
|
npgettext, npgettext_lazy, pgettext, trans_real, ugettext, ugettext_lazy,
|
||||||
ugettext_lazy, ungettext, ungettext_lazy,
|
ungettext, ungettext_lazy,
|
||||||
)
|
)
|
||||||
|
|
||||||
from .forms import CompanyForm, I18nForm, SelectDateForm
|
from .forms import CompanyForm, I18nForm, SelectDateForm
|
||||||
@ -146,14 +146,11 @@ class TranslationTests(SimpleTestCase):
|
|||||||
@override_settings(LOCALE_PATHS=extended_locale_paths)
|
@override_settings(LOCALE_PATHS=extended_locale_paths)
|
||||||
def test_ungettext_lazy(self):
|
def test_ungettext_lazy(self):
|
||||||
simple_with_format = ungettext_lazy('%d good result', '%d good results')
|
simple_with_format = ungettext_lazy('%d good result', '%d good results')
|
||||||
simple_str_with_format = ngettext_lazy(str('%d good result'), str('%d good results'))
|
|
||||||
simple_context_with_format = npgettext_lazy('Exclamation', '%d good result', '%d good results')
|
simple_context_with_format = npgettext_lazy('Exclamation', '%d good result', '%d good results')
|
||||||
simple_without_format = ungettext_lazy('good result', 'good results')
|
simple_without_format = ungettext_lazy('good result', 'good results')
|
||||||
with translation.override('de'):
|
with translation.override('de'):
|
||||||
self.assertEqual(simple_with_format % 1, '1 gutes Resultat')
|
self.assertEqual(simple_with_format % 1, '1 gutes Resultat')
|
||||||
self.assertEqual(simple_with_format % 4, '4 guten Resultate')
|
self.assertEqual(simple_with_format % 4, '4 guten Resultate')
|
||||||
self.assertEqual(simple_str_with_format % 1, str('1 gutes Resultat'))
|
|
||||||
self.assertEqual(simple_str_with_format % 4, str('4 guten Resultate'))
|
|
||||||
self.assertEqual(simple_context_with_format % 1, '1 gutes Resultat!')
|
self.assertEqual(simple_context_with_format % 1, '1 gutes Resultat!')
|
||||||
self.assertEqual(simple_context_with_format % 4, '4 guten Resultate!')
|
self.assertEqual(simple_context_with_format % 4, '4 guten Resultate!')
|
||||||
self.assertEqual(simple_without_format % 1, 'gutes Resultat')
|
self.assertEqual(simple_without_format % 1, 'gutes Resultat')
|
||||||
@ -163,12 +160,6 @@ class TranslationTests(SimpleTestCase):
|
|||||||
complex_deferred = ungettext_lazy(
|
complex_deferred = ungettext_lazy(
|
||||||
'Hi %(name)s, %(num)d good result', 'Hi %(name)s, %(num)d good results', 'num'
|
'Hi %(name)s, %(num)d good result', 'Hi %(name)s, %(num)d good results', 'num'
|
||||||
)
|
)
|
||||||
complex_str_nonlazy = ngettext_lazy(
|
|
||||||
str('Hi %(name)s, %(num)d good result'), str('Hi %(name)s, %(num)d good results'), 4
|
|
||||||
)
|
|
||||||
complex_str_deferred = ngettext_lazy(
|
|
||||||
str('Hi %(name)s, %(num)d good result'), str('Hi %(name)s, %(num)d good results'), 'num'
|
|
||||||
)
|
|
||||||
complex_context_nonlazy = npgettext_lazy(
|
complex_context_nonlazy = npgettext_lazy(
|
||||||
'Greeting', 'Hi %(name)s, %(num)d good result', 'Hi %(name)s, %(num)d good results', 4
|
'Greeting', 'Hi %(name)s, %(num)d good result', 'Hi %(name)s, %(num)d good results', 4
|
||||||
)
|
)
|
||||||
@ -181,11 +172,6 @@ class TranslationTests(SimpleTestCase):
|
|||||||
self.assertEqual(complex_deferred % {'name': 'Jim', 'num': 5}, 'Hallo Jim, 5 guten Resultate')
|
self.assertEqual(complex_deferred % {'name': 'Jim', 'num': 5}, 'Hallo Jim, 5 guten Resultate')
|
||||||
with self.assertRaisesMessage(KeyError, 'Your dictionary lacks key'):
|
with self.assertRaisesMessage(KeyError, 'Your dictionary lacks key'):
|
||||||
complex_deferred % {'name': 'Jim'}
|
complex_deferred % {'name': 'Jim'}
|
||||||
self.assertEqual(complex_str_nonlazy % {'num': 4, 'name': 'Jim'}, str('Hallo Jim, 4 guten Resultate'))
|
|
||||||
self.assertEqual(complex_str_deferred % {'name': 'Jim', 'num': 1}, str('Hallo Jim, 1 gutes Resultat'))
|
|
||||||
self.assertEqual(complex_str_deferred % {'name': 'Jim', 'num': 5}, str('Hallo Jim, 5 guten Resultate'))
|
|
||||||
with self.assertRaisesMessage(KeyError, 'Your dictionary lacks key'):
|
|
||||||
complex_str_deferred % {'name': 'Jim'}
|
|
||||||
self.assertEqual(complex_context_nonlazy % {'num': 4, 'name': 'Jim'}, 'Willkommen Jim, 4 guten Resultate')
|
self.assertEqual(complex_context_nonlazy % {'num': 4, 'name': 'Jim'}, 'Willkommen Jim, 4 guten Resultate')
|
||||||
self.assertEqual(complex_context_deferred % {'name': 'Jim', 'num': 1}, 'Willkommen Jim, 1 gutes Resultat')
|
self.assertEqual(complex_context_deferred % {'name': 'Jim', 'num': 1}, 'Willkommen Jim, 1 gutes Resultat')
|
||||||
self.assertEqual(complex_context_deferred % {'name': 'Jim', 'num': 5}, 'Willkommen Jim, 5 guten Resultate')
|
self.assertEqual(complex_context_deferred % {'name': 'Jim', 'num': 5}, 'Willkommen Jim, 5 guten Resultate')
|
||||||
@ -917,8 +903,8 @@ class FormattingTests(SimpleTestCase):
|
|||||||
def test_get_format_modules_stability(self):
|
def test_get_format_modules_stability(self):
|
||||||
with self.settings(FORMAT_MODULE_PATH='i18n.other.locale'):
|
with self.settings(FORMAT_MODULE_PATH='i18n.other.locale'):
|
||||||
with translation.override('de', deactivate=True):
|
with translation.override('de', deactivate=True):
|
||||||
old = str("%r") % get_format_modules(reverse=True)
|
old = "%r" % get_format_modules(reverse=True)
|
||||||
new = str("%r") % get_format_modules(reverse=True) # second try
|
new = "%r" % get_format_modules(reverse=True) # second try
|
||||||
self.assertEqual(new, old, 'Value returned by get_formats_modules() must be preserved between calls.')
|
self.assertEqual(new, old, 'Value returned by get_formats_modules() must be preserved between calls.')
|
||||||
|
|
||||||
def test_localize_templatetag_and_filter(self):
|
def test_localize_templatetag_and_filter(self):
|
||||||
|
@ -576,7 +576,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
|
|||||||
s = msg.message().as_bytes()
|
s = msg.message().as_bytes()
|
||||||
self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
|
self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
|
||||||
s = msg.message().as_string()
|
s = msg.message().as_string()
|
||||||
self.assertIn(str('Content-Transfer-Encoding: 8bit'), s)
|
self.assertIn('Content-Transfer-Encoding: 8bit', s)
|
||||||
|
|
||||||
msg = EmailMessage(
|
msg = EmailMessage(
|
||||||
'Subject', 'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'bounce@example.com',
|
'Subject', 'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'bounce@example.com',
|
||||||
@ -585,7 +585,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
|
|||||||
s = msg.message().as_bytes()
|
s = msg.message().as_bytes()
|
||||||
self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
|
self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
|
||||||
s = msg.message().as_string()
|
s = msg.message().as_string()
|
||||||
self.assertIn(str('Content-Transfer-Encoding: 8bit'), s)
|
self.assertIn('Content-Transfer-Encoding: 8bit', s)
|
||||||
|
|
||||||
def test_dont_base64_encode_message_rfc822(self):
|
def test_dont_base64_encode_message_rfc822(self):
|
||||||
# Ticket #18967
|
# Ticket #18967
|
||||||
@ -608,7 +608,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
|
|||||||
parent_s = parent_msg.message().as_string()
|
parent_s = parent_msg.message().as_string()
|
||||||
|
|
||||||
# The child message header is not base64 encoded
|
# The child message header is not base64 encoded
|
||||||
self.assertIn(str('Child Subject'), parent_s)
|
self.assertIn('Child Subject', parent_s)
|
||||||
|
|
||||||
# Feature test: try attaching email.Message object directly to the mail.
|
# Feature test: try attaching email.Message object directly to the mail.
|
||||||
parent_msg = EmailMessage(
|
parent_msg = EmailMessage(
|
||||||
@ -619,7 +619,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
|
|||||||
parent_s = parent_msg.message().as_string()
|
parent_s = parent_msg.message().as_string()
|
||||||
|
|
||||||
# The child message header is not base64 encoded
|
# The child message header is not base64 encoded
|
||||||
self.assertIn(str('Child Subject'), parent_s)
|
self.assertIn('Child Subject', parent_s)
|
||||||
|
|
||||||
# Feature test: try attaching Django's EmailMessage object directly to the mail.
|
# Feature test: try attaching Django's EmailMessage object directly to the mail.
|
||||||
parent_msg = EmailMessage(
|
parent_msg = EmailMessage(
|
||||||
@ -630,7 +630,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
|
|||||||
parent_s = parent_msg.message().as_string()
|
parent_s = parent_msg.message().as_string()
|
||||||
|
|
||||||
# The child message header is not base64 encoded
|
# The child message header is not base64 encoded
|
||||||
self.assertIn(str('Child Subject'), parent_s)
|
self.assertIn('Child Subject', parent_s)
|
||||||
|
|
||||||
def test_sanitize_address(self):
|
def test_sanitize_address(self):
|
||||||
"""
|
"""
|
||||||
@ -700,11 +700,11 @@ class PythonGlobalState(SimpleTestCase):
|
|||||||
|
|
||||||
def test_8bit_latin(self):
|
def test_8bit_latin(self):
|
||||||
txt = MIMEText('Body with latin characters: àáä.', 'plain', 'utf-8')
|
txt = MIMEText('Body with latin characters: àáä.', 'plain', 'utf-8')
|
||||||
self.assertIn(str('Content-Transfer-Encoding: base64'), txt.as_string())
|
self.assertIn('Content-Transfer-Encoding: base64', txt.as_string())
|
||||||
|
|
||||||
def test_8bit_non_latin(self):
|
def test_8bit_non_latin(self):
|
||||||
txt = MIMEText('Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'plain', 'utf-8')
|
txt = MIMEText('Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'plain', 'utf-8')
|
||||||
self.assertIn(str('Content-Transfer-Encoding: base64'), txt.as_string())
|
self.assertIn('Content-Transfer-Encoding: base64', txt.as_string())
|
||||||
|
|
||||||
|
|
||||||
class BaseEmailBackendTests(HeadersCheckMixin):
|
class BaseEmailBackendTests(HeadersCheckMixin):
|
||||||
@ -1091,7 +1091,7 @@ class ConsoleBackendTests(BaseEmailBackendTests, SimpleTestCase):
|
|||||||
self.stream = sys.stdout = StringIO()
|
self.stream = sys.stdout = StringIO()
|
||||||
|
|
||||||
def get_mailbox_content(self):
|
def get_mailbox_content(self):
|
||||||
messages = self.stream.getvalue().split(str('\n' + ('-' * 79) + '\n'))
|
messages = self.stream.getvalue().split('\n' + ('-' * 79) + '\n')
|
||||||
return [message_from_bytes(force_bytes(m)) for m in messages if m]
|
return [message_from_bytes(force_bytes(m)) for m in messages if m]
|
||||||
|
|
||||||
def test_console_stream_kwarg(self):
|
def test_console_stream_kwarg(self):
|
||||||
@ -1127,9 +1127,9 @@ class FakeSMTPChannel(smtpd.SMTPChannel):
|
|||||||
# This is only the first part of the login process. But it's enough
|
# This is only the first part of the login process. But it's enough
|
||||||
# for our tests.
|
# for our tests.
|
||||||
challenge = base64.b64encode(b'somerandomstring13579')
|
challenge = base64.b64encode(b'somerandomstring13579')
|
||||||
self.push(str('334 %s' % challenge.decode()))
|
self.push('334 %s' % challenge.decode())
|
||||||
else:
|
else:
|
||||||
self.push(str('502 Error: login "%s" not implemented' % arg))
|
self.push('502 Error: login "%s" not implemented' % arg)
|
||||||
|
|
||||||
|
|
||||||
class FakeSMTPServer(smtpd.SMTPServer, threading.Thread):
|
class FakeSMTPServer(smtpd.SMTPServer, threading.Thread):
|
||||||
|
@ -6,9 +6,7 @@ import math
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
import tokenize
|
|
||||||
import uuid
|
import uuid
|
||||||
from io import StringIO
|
|
||||||
|
|
||||||
import custom_migration_operations.more_operations
|
import custom_migration_operations.more_operations
|
||||||
import custom_migration_operations.operations
|
import custom_migration_operations.operations
|
||||||
@ -20,7 +18,7 @@ from django.db import migrations, models
|
|||||||
from django.db.migrations.writer import (
|
from django.db.migrations.writer import (
|
||||||
MigrationWriter, OperationWriter, SettingsReference,
|
MigrationWriter, OperationWriter, SettingsReference,
|
||||||
)
|
)
|
||||||
from django.test import SimpleTestCase, ignore_warnings, mock
|
from django.test import SimpleTestCase, mock
|
||||||
from django.utils import datetime_safe
|
from django.utils import datetime_safe
|
||||||
from django.utils.deconstruct import deconstructible
|
from django.utils.deconstruct import deconstructible
|
||||||
from django.utils.functional import SimpleLazyObject
|
from django.utils.functional import SimpleLazyObject
|
||||||
@ -552,22 +550,7 @@ class WriterTests(SimpleTestCase):
|
|||||||
# Just make sure it runs for now, and that things look alright.
|
# Just make sure it runs for now, and that things look alright.
|
||||||
result = self.safe_exec(output)
|
result = self.safe_exec(output)
|
||||||
self.assertIn("Migration", result)
|
self.assertIn("Migration", result)
|
||||||
# In order to preserve compatibility with Python 3.2 unicode literals
|
|
||||||
# prefix shouldn't be added to strings.
|
|
||||||
tokens = tokenize.generate_tokens(StringIO(str(output)).readline)
|
|
||||||
for token_type, token_source, (srow, scol), __, line in tokens:
|
|
||||||
if token_type == tokenize.STRING:
|
|
||||||
self.assertFalse(
|
|
||||||
token_source.startswith('u'),
|
|
||||||
"Unicode literal prefix found at %d:%d: %r" % (
|
|
||||||
srow, scol, line.strip()
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
# Silence warning on Python 2: Not importing directory
|
|
||||||
# 'tests/migrations/migrations_test_apps/without_init_file/migrations':
|
|
||||||
# missing __init__.py
|
|
||||||
@ignore_warnings(category=ImportWarning)
|
|
||||||
def test_migration_path(self):
|
def test_migration_path(self):
|
||||||
test_apps = [
|
test_apps = [
|
||||||
'migrations.migrations_test_apps.normal',
|
'migrations.migrations_test_apps.normal',
|
||||||
|
@ -60,7 +60,7 @@ class WSGIRequestHandlerTestCase(SimpleTestCase):
|
|||||||
handler = WSGIRequestHandler(request, '192.168.0.2', None)
|
handler = WSGIRequestHandler(request, '192.168.0.2', None)
|
||||||
|
|
||||||
with patch_logger('django.server', 'error') as messages:
|
with patch_logger('django.server', 'error') as messages:
|
||||||
handler.log_message("GET %s %s", str('\x16\x03'), "4")
|
handler.log_message("GET %s %s", '\x16\x03', "4")
|
||||||
self.assertIn(
|
self.assertIn(
|
||||||
"You're accessing the development server over HTTPS, "
|
"You're accessing the development server over HTTPS, "
|
||||||
"but it only supports HTTP.",
|
"but it only supports HTTP.",
|
||||||
|
@ -30,5 +30,5 @@ class SimpleTests(TestCase):
|
|||||||
# coerce the returned value.
|
# coerce the returned value.
|
||||||
self.assertIsInstance(obj.__str__(), str)
|
self.assertIsInstance(obj.__str__(), str)
|
||||||
self.assertIsInstance(obj.__repr__(), str)
|
self.assertIsInstance(obj.__repr__(), str)
|
||||||
self.assertEqual(str(obj), str('Default object'))
|
self.assertEqual(str(obj), 'Default object')
|
||||||
self.assertEqual(repr(obj), str('<Default: Default object>'))
|
self.assertEqual(repr(obj), '<Default: Default object>')
|
||||||
|
@ -356,7 +356,7 @@ class URLPatternReverse(SimpleTestCase):
|
|||||||
def test_illegal_kwargs_message(self):
|
def test_illegal_kwargs_message(self):
|
||||||
msg = "Reverse for 'places' with keyword arguments '{'arg1': 2}' not found. 1 pattern(s) tried:"
|
msg = "Reverse for 'places' with keyword arguments '{'arg1': 2}' not found. 1 pattern(s) tried:"
|
||||||
with self.assertRaisesMessage(NoReverseMatch, msg):
|
with self.assertRaisesMessage(NoReverseMatch, msg):
|
||||||
reverse('places', kwargs={str('arg1'): 2})
|
reverse('places', kwargs={'arg1': 2})
|
||||||
|
|
||||||
|
|
||||||
class ResolverTests(SimpleTestCase):
|
class ResolverTests(SimpleTestCase):
|
||||||
@ -436,7 +436,7 @@ class ResolverTests(SimpleTestCase):
|
|||||||
)
|
)
|
||||||
for tried, expected in zip(e.args[0]['tried'], url_types_names):
|
for tried, expected in zip(e.args[0]['tried'], url_types_names):
|
||||||
for t, e in zip(tried, expected):
|
for t, e in zip(tried, expected):
|
||||||
self.assertIsInstance(t, e['type']), str('%s is not an instance of %s') % (t, e['type'])
|
self.assertIsInstance(t, e['type']), '%s is not an instance of %s' % (t, e['type'])
|
||||||
if 'name' in e:
|
if 'name' in e:
|
||||||
if not e['name']:
|
if not e['name']:
|
||||||
self.assertIsNone(t.name, 'Expected no URL name but found %s.' % t.name)
|
self.assertIsNone(t.name, 'Expected no URL name but found %s.' % t.name)
|
||||||
|
@ -12,14 +12,12 @@ from django.utils.http import urlquote_plus
|
|||||||
class TestEncodingUtils(unittest.TestCase):
|
class TestEncodingUtils(unittest.TestCase):
|
||||||
def test_force_text_exception(self):
|
def test_force_text_exception(self):
|
||||||
"""
|
"""
|
||||||
Broken __unicode__/__str__ actually raises an error.
|
Broken __str__ actually raises an error.
|
||||||
"""
|
"""
|
||||||
class MyString:
|
class MyString:
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return b'\xc3\xb6\xc3\xa4\xc3\xbc'
|
return b'\xc3\xb6\xc3\xa4\xc3\xbc'
|
||||||
|
|
||||||
__unicode__ = __str__
|
|
||||||
|
|
||||||
# str(s) raises a TypeError if the result is not a text type.
|
# str(s) raises a TypeError if the result is not a text type.
|
||||||
with self.assertRaises(TypeError):
|
with self.assertRaises(TypeError):
|
||||||
force_text(MyString())
|
force_text(MyString())
|
||||||
|
Loading…
x
Reference in New Issue
Block a user