Refs #23919 -- Removed unneeded str() calls

This commit is contained in:
Claude Paroz 2017-01-20 10:20:53 +01:00
parent 4e729feaa6
commit 042b7350a0
47 changed files with 116 additions and 164 deletions

View File

@ -83,7 +83,7 @@ class OpenLayersWidget(Textarea):
# JavaScript construction utilities for the Bounds and Projection.
def ol_bounds(extent):
return 'new OpenLayers.Bounds(%s)' % str(extent)
return 'new OpenLayers.Bounds(%s)' % extent
def ol_projection(srid):
return 'new OpenLayers.Projection("EPSG:%s")' % srid

View File

@ -58,9 +58,9 @@ class PostGISAdapter:
"""
if self.is_geometry:
# 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',
self._adapter.getquoted().decode())
self._adapter.getquoted().decode()
)
else:
# For rasters, add explicit type cast to WKB string.

View File

@ -65,7 +65,7 @@ class GeoFunc(Func):
if check_types and not isinstance(value, check_types):
raise TypeError(
"The %s parameter has the wrong type: should be %s." % (
param_name, str(check_types))
param_name, check_types)
)
return value

View File

@ -109,7 +109,7 @@ class DataSource(GDALBase):
def __str__(self):
"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
def layer_count(self):

View File

@ -60,11 +60,11 @@ class Driver(GDALBase):
elif isinstance(dr_input, c_void_p):
driver = dr_input
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
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
def __str__(self):

View File

@ -51,7 +51,7 @@ class Envelope:
else:
self._from_sequence(args[0])
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:
# Individual parameters passed in.
# Thanks to ww for the help
@ -123,7 +123,7 @@ class Envelope:
else:
raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
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:
# An x and an y parameter were passed in
return self.expand_to_include((args[0], args[1], args[0], args[1]))

View File

@ -109,7 +109,7 @@ class OGRGeometry(GDALBase):
# Now checking the Geometry pointer before finishing initialization
# by setting the pointer for the object.
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
# Assigning the SpatialReference object to the geometry, if valid.
@ -549,7 +549,7 @@ class LineString(OGRGeometry):
elif dim == 3:
return (x.value, y.value, z.value)
else:
raise OGRIndexError('index out of range: %s' % str(index))
raise OGRIndexError('index out of range: %s' % index)
def __iter__(self):
"Iterates over each point in the LineString."

View File

@ -73,7 +73,7 @@ class GEOSCoordSeq(GEOSBase):
"Checks the given index."
sz = self.size
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):
"Checks the given dimension."

View File

@ -73,7 +73,7 @@ class GEOSGeometry(GEOSBase, ListMixin):
g = capi.geom_clone(geo_input.ptr)
else:
# 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:
# Setting the pointer object with a valid pointer.

View File

@ -179,7 +179,7 @@ class ListMixin:
for i in range(0, len(self)):
if self[i] == val:
return i
raise ValueError('%s not found in object' % str(val))
raise ValueError('%s not found in object' % val)
# ## Mutating ##
def append(self, val):
@ -242,7 +242,7 @@ class ListMixin:
return index
if correct and -length <= index < 0:
return index + length
raise IndexError('invalid index: %s' % str(index))
raise IndexError('invalid index: %s' % index)
def _check_allowed(self, items):
if hasattr(self, '_allowed'):

View File

@ -56,7 +56,7 @@ class Point(GEOSGeometry):
return capi.create_point(None)
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))
i = iter(coords)

View File

@ -153,9 +153,9 @@ class WSGIHandler(base.BaseHandler):
response._handler_class = self.__class__
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():
response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
response_headers.append(('Set-Cookie', c.output(header='')))
start_response(status, response_headers)
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)
@ -208,9 +208,9 @@ def get_bytes_from_wsgi(environ, key, default):
"""
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
# ISO-8859-1. This is wrong for Django websites where UTF-8 is the default.
# Re-encode to recover the original bytestring.

View File

@ -68,7 +68,7 @@ def forbid_multi_line_headers(name, val, encoding):
else:
if name.lower() == 'subject':
val = Header(val).encode()
return str(name), val
return name, val
def split_addr(addr, encoding):

View File

@ -398,7 +398,7 @@ class Command(BaseCommand):
self.process_files(file_list)
potfiles = []
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):
continue
args = ['msguniq'] + self.msguniq_options + [potfile]
@ -417,7 +417,7 @@ class Command(BaseCommand):
def remove_potfiles(self):
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):
os.unlink(pot_path)
@ -583,7 +583,7 @@ class Command(BaseCommand):
)
for build_file in build_files:
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)
for build_file in build_files:
@ -599,7 +599,7 @@ class Command(BaseCommand):
basedir = os.path.join(os.path.dirname(potfile), locale, 'LC_MESSAGES')
if not os.path.isdir(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):
args = ['msgmerge'] + self.msgmerge_options + [pofile, potfile]

View File

@ -56,7 +56,7 @@ class Command(BaseCommand):
# We rely on the environment because it's currently the only
# way to reach WSGIRequestHandler. This seems an acceptable
# compromise considering `runserver` runs indefinitely.
os.environ[str("DJANGO_COLORS")] = str("nocolor")
os.environ["DJANGO_COLORS"] = "nocolor"
super(Command, self).execute(*args, **options)
def get_handler(self, *args, **options):

View File

@ -103,7 +103,7 @@ class WSGIRequestHandler(simple_server.WSGIRequestHandler):
}
if args[1][0] == '4':
# 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
logger.error(
"You're accessing the development server over HTTPS, but "

View File

@ -45,13 +45,13 @@ def decoder(conv_func):
return lambda s: conv_func(s.decode('utf-8'))
Database.register_converter(str("bool"), decoder(lambda s: s == '1'))
Database.register_converter(str("time"), decoder(parse_time))
Database.register_converter(str("date"), decoder(parse_date))
Database.register_converter(str("datetime"), decoder(parse_datetime))
Database.register_converter(str("timestamp"), decoder(parse_datetime))
Database.register_converter(str("TIMESTAMP"), decoder(parse_datetime))
Database.register_converter(str("decimal"), decoder(backend_utils.typecast_decimal))
Database.register_converter("bool", decoder(lambda s: s == '1'))
Database.register_converter("time", decoder(parse_time))
Database.register_converter("date", decoder(parse_date))
Database.register_converter("datetime", decoder(parse_datetime))
Database.register_converter("timestamp", decoder(parse_datetime))
Database.register_converter("TIMESTAMP", decoder(parse_datetime))
Database.register_converter("decimal", decoder(backend_utils.typecast_decimal))
Database.register_adapter(decimal.Decimal, backend_utils.rev_typecast_decimal)

View File

@ -35,10 +35,10 @@ from django.utils.version import get_version
class Deferred:
def __repr__(self):
return str('<Deferred field>')
return '<Deferred field>'
def __str__(self):
return str('<Deferred field>')
return '<Deferred field>'
DEFERRED = Deferred()
@ -118,7 +118,7 @@ class ModelBase(type):
new_class.add_to_class(
'DoesNotExist',
subclass_exception(
str('DoesNotExist'),
'DoesNotExist',
tuple(
x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.abstract
) or (ObjectDoesNotExist,),
@ -127,7 +127,7 @@ class ModelBase(type):
new_class.add_to_class(
'MultipleObjectsReturned',
subclass_exception(
str('MultipleObjectsReturned'),
'MultipleObjectsReturned',
tuple(
x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.abstract
) or (MultipleObjectsReturned,),

View File

@ -32,9 +32,7 @@ from django.utils.itercompat import is_iterable
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
# Avoid "TypeError: Item in ``from list'' not a string" -- unicode_literals
# makes these strings unicode
__all__ = [str(x) for x in (
__all__ = [
'AutoField', 'BLANK_CHOICE_DASH', 'BigAutoField', 'BigIntegerField',
'BinaryField', 'BooleanField', 'CharField', 'CommaSeparatedIntegerField',
'DateField', 'DateTimeField', 'DecimalField', 'DurationField',
@ -43,7 +41,7 @@ __all__ = [str(x) for x in (
'NOT_PROVIDED', 'NullBooleanField', 'PositiveIntegerField',
'PositiveSmallIntegerField', 'SlugField', 'SmallIntegerField', 'TextField',
'TimeField', 'URLField', 'UUIDField',
)]
]
class Empty:

View File

@ -277,7 +277,7 @@ class FileField(Field):
def get_prep_value(self, value):
"Returns field's value prepared for saving into a database."
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:
return None
return str(value)

View File

@ -2,7 +2,7 @@ import hashlib
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)
MAX_NAME_LENGTH = 30

View File

@ -22,13 +22,13 @@ def parse_cookie(cookie):
Return a dictionary parsed from a `Cookie:` header string.
"""
cookiedict = {}
for chunk in cookie.split(str(';')):
if str('=') in chunk:
key, val = chunk.split(str('='), 1)
for chunk in cookie.split(';'):
if '=' in chunk:
key, val = chunk.split('=', 1)
else:
# Assume an empty name per
# https://bugzilla.mozilla.org/show_bug.cgi?id=169091
key, val = str(''), chunk
key, val = '', chunk
key, val = key.strip(), val.strip()
if key or val:
# unquote using Python's algorithm.

View File

@ -509,11 +509,11 @@ class QueryDict(MultiValueDict):
# this slightly more restricted function, used by QueryDict.
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
(\ufffd).
Returns any non-basestring objects without change.
Return any non-bytes objects without change.
"""
if isinstance(s, bytes):
return str(s, encoding, 'replace')

View File

@ -124,8 +124,7 @@ class HttpResponseBase:
value = value.decode(charset)
except UnicodeError as e:
if mime_encode:
# Wrapping in str() is a workaround for #12422 under Python 2.
value = str(Header(value, 'utf-8', maxlinelen=sys.maxsize).encode())
value = Header(value, 'utf-8', maxlinelen=sys.maxsize).encode()
else:
e.reason += ', HTTP response headers must be in %s format' % charset
raise

View File

@ -281,15 +281,15 @@ class RequestFactory:
# See http://www.python.org/dev/peps/pep-3333/#environ-variables
environ = {
'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
'PATH_INFO': str('/'),
'REMOTE_ADDR': str('127.0.0.1'),
'REQUEST_METHOD': str('GET'),
'SCRIPT_NAME': str(''),
'SERVER_NAME': str('testserver'),
'SERVER_PORT': str('80'),
'SERVER_PROTOCOL': str('HTTP/1.1'),
'PATH_INFO': '/',
'REMOTE_ADDR': '127.0.0.1',
'REQUEST_METHOD': 'GET',
'SCRIPT_NAME': '',
'SERVER_NAME': 'testserver',
'SERVER_PORT': '80',
'SERVER_PROTOCOL': 'HTTP/1.1',
'wsgi.version': (1, 0),
'wsgi.url_scheme': str('http'),
'wsgi.url_scheme': 'http',
'wsgi.input': FakePayload(b''),
'wsgi.errors': self.errors,
'wsgi.multiprocess': True,
@ -393,14 +393,14 @@ class RequestFactory:
data = force_bytes(data, settings.DEFAULT_CHARSET)
r = {
'PATH_INFO': self._get_path(parsed),
'REQUEST_METHOD': str(method),
'SERVER_PORT': str('443') if secure else str('80'),
'wsgi.url_scheme': str('https') if secure else str('http'),
'REQUEST_METHOD': method,
'SERVER_PORT': '443' if secure else '80',
'wsgi.url_scheme': 'https' if secure else 'http',
}
if data:
r.update({
'CONTENT_LENGTH': len(data),
'CONTENT_TYPE': str(content_type),
'CONTENT_TYPE': content_type,
'wsgi.input': FakePayload(data),
})
r.update(extra)

View File

@ -35,7 +35,7 @@ class SeleniumTestCaseBase(type(LiveServerTestCase)):
for browser in test_class.browsers[1:]:
browser_test_class = cls.__new__(
cls,
str("%s%s" % (capfirst(browser), name)),
"%s%s" % (capfirst(browser), name),
(test_class,),
{'browser': browser, '__module__': test_class.__module__}
)

View File

@ -236,7 +236,7 @@ class RegexURLResolver(LocaleRegexProvider):
urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__
else:
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.namespace, self.regex.pattern,
)

View File

@ -193,7 +193,7 @@ def smart_urlquote(url):
# Tilde is part of RFC3986 Unreserved Characters
# http://tools.ietf.org/html/rfc3986#section-2.3
# 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)
# Handle IDN before quoting.

View File

@ -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))
ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y))
RFC3986_GENDELIMS = str(":/?#[]@")
RFC3986_SUBDELIMS = str("!$&'()*+,;=")
RFC3986_GENDELIMS = ":/?#[]@"
RFC3986_SUBDELIMS = "!$&'()*+,;="
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:
if not name_value:
continue
nv = name_value.split(str('='), 1)
nv = name_value.split('=', 1)
if len(nv) != 2:
# Handle case of a control-name with no equal sign
if keep_blank_values:

View File

@ -95,7 +95,7 @@ def _safety_decorator(safety_marker, func):
def mark_safe(s):
"""
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.

View File

@ -307,8 +307,7 @@ def do_translate(message, translation_function):
"""
global _default
# str() is allowing a bytestring message to remain bytestring on Python 2
eol_message = message.replace(str('\r\n'), str('\n')).replace(str('\r'), str('\n'))
eol_message = message.replace('\r\n', '\n').replace('\r', '\n')
if len(eol_message) == 0:
# Returns an empty value of the corresponding type if an empty message

View File

@ -25,7 +25,7 @@ def get_version(version=None):
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'rc'}
sub = mapping[version[3]] + str(version[4])
return str(main + sub)
return main + sub
def get_main_version(version=None):

View File

@ -145,14 +145,13 @@ class AdminScriptTestCase(unittest.TestCase):
# Set the test environment
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:
del test_environ['DJANGO_SETTINGS_MODULE']
python_path = [base_dir, django_dir, tests_dir]
python_path.extend(ext_backend_base_dirs)
# Use native strings for better compatibility
test_environ[str(python_path_var_name)] = os.pathsep.join(python_path)
test_environ[str('PYTHONWARNINGS')] = str('')
test_environ[python_path_var_name] = os.pathsep.join(python_path)
test_environ['PYTHONWARNINGS'] = ''
# Move to the test directory and run
os.chdir(self.test_dir)

View File

@ -37,10 +37,7 @@ def mock_inputs(inputs):
return inputs['password']
def mock_input(prompt):
# prompt should be encoded in Python 2. This line will raise an
# Exception if prompt contains unencoded non-ASCII on Python 2.
prompt = str(prompt)
assert str('__proxy__') not in prompt
assert '__proxy__' not in prompt
response = ''
for key, val in inputs.items():
if key in prompt.lower():

View File

@ -10,7 +10,7 @@ MAX_SOCKET_CHUNK_SIZE = 32 * 1024 * 1024 # 32 MB
class ServerHandler(simple_server.ServerHandler):
error_status = str("500 INTERNAL SERVER ERROR")
error_status = "500 INTERNAL SERVER ERROR"
def write(self, data):
"""'write()' callable as specified by PEP 3333"""
@ -55,12 +55,12 @@ class FileWrapperHandler(ServerHandler):
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!']
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'))
@ -113,7 +113,7 @@ class WriteChunkCounterHandler(ServerHandler):
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 [b'x' * (MAX_SOCKET_CHUNK_SIZE + MAX_SOCKET_CHUNK_SIZE // 2)]

View File

@ -248,7 +248,7 @@ class RelatedModelFormTests(SimpleTestCase):
fields = '__all__'
with self.assertRaises(ValueError):
ModelFormMetaclass(str('Form'), (ModelForm,), {'Meta': Meta})
ModelFormMetaclass('Form', (ModelForm,), {'Meta': Meta})
class B(models.Model):
pass
@ -267,7 +267,7 @@ class RelatedModelFormTests(SimpleTestCase):
model = C
fields = '__all__'
self.assertTrue(issubclass(ModelFormMetaclass(str('Form'), (ModelForm,), {'Meta': Meta}), ModelForm))
self.assertTrue(issubclass(ModelFormMetaclass('Form', (ModelForm,), {'Meta': Meta}), ModelForm))
class ManyToManyExclusionTestCase(TestCase):

View File

@ -81,7 +81,7 @@ class GetObjectOr404Tests(TestCase):
# raises a helpful ValueError message
msg = "First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'str'."
with self.assertRaisesMessage(ValueError, msg):
get_object_or_404(str("Article"), title__icontains="Run")
get_object_or_404("Article", title__icontains="Run")
class CustomClass:
pass

View File

@ -201,7 +201,7 @@ class GetOrCreateTestsWithManualPKs(TestCase):
ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different")
except IntegrityError:
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
@ignore_warnings(module='django.db.backends.mysql.base')

View File

@ -21,7 +21,7 @@ from django.utils.functional import lazystr
class QueryDictTests(SimpleTestCase):
def test_create_with_no_args(self):
self.assertEqual(QueryDict(), QueryDict(str('')))
self.assertEqual(QueryDict(), QueryDict(''))
def test_missing_key(self):
q = QueryDict()
@ -63,7 +63,7 @@ class QueryDictTests(SimpleTestCase):
def test_single_key_value(self):
"""Test QueryDict with one key/value pair"""
q = QueryDict(str('foo=bar'))
q = QueryDict('foo=bar')
self.assertEqual(q['foo'], 'bar')
with self.assertRaises(KeyError):
q.__getitem__('bar')
@ -166,7 +166,7 @@ class QueryDictTests(SimpleTestCase):
def test_multiple_keys(self):
"""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')
with self.assertRaises(AttributeError):
@ -209,23 +209,23 @@ class QueryDictTests(SimpleTestCase):
q = QueryDict()
q1 = pickle.loads(pickle.dumps(q, 2))
self.assertEqual(q, q1)
q = QueryDict(str('a=b&c=d'))
q = QueryDict('a=b&c=d')
q1 = pickle.loads(pickle.dumps(q, 2))
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))
self.assertEqual(q, q1)
def test_update_from_querydict(self):
"""Regression test for #8278: QueryDict.update(QueryDict)"""
x = QueryDict(str("a=1&a=2"), mutable=True)
y = QueryDict(str("a=3&a=4"))
x = QueryDict("a=1&a=2", mutable=True)
y = QueryDict("a=3&a=4")
x.update(y)
self.assertEqual(x.getlist('a'), ['1', '2', '3', '4'])
def test_non_default_encoding(self):
"""#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(list(q.items()), [('cur', '')])
self.assertEqual(q.urlencode(), 'cur=%A4')
@ -280,16 +280,11 @@ class HttpResponseTests(unittest.TestCase):
def test_headers_type(self):
r = HttpResponse()
# The following tests explicitly test types in addition to values
# because in Python 2 u'foo' == b'foo'.
# ASCII unicode or bytes values are converted to native strings.
# ASCII unicode or bytes values are converted to strings.
r['key'] = 'test'
self.assertEqual(r['key'], str('test'))
self.assertIsInstance(r['key'], str)
self.assertEqual(r['key'], 'test')
r['key'] = 'test'.encode('ascii')
self.assertEqual(r['key'], str('test'))
self.assertIsInstance(r['key'], str)
self.assertEqual(r['key'], 'test')
self.assertIn(b'test', r.serialize_headers())
# 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).
r['key'] = ''
self.assertEqual(r['key'], str('=?utf-8?b?4oCg?='))
self.assertIsInstance(r['key'], str)
self.assertEqual(r['key'], '=?utf-8?b?4oCg?=')
self.assertIn(b'=?utf-8?b?4oCg?=', r.serialize_headers())
# The response also converts unicode or bytes keys to strings, but requires
@ -310,7 +304,6 @@ class HttpResponseTests(unittest.TestCase):
headers = list(r.items())
self.assertEqual(len(headers), 1)
self.assertEqual(headers[0], ('foo', 'bar'))
self.assertIsInstance(headers[0][0], str)
r = HttpResponse()
del r['Content-Type']

View File

@ -142,7 +142,7 @@ class CompilationErrorHandling(MessageCompilationTests):
# po file contains invalid msgstr content (triggers non-ascii error content).
# Make sure the output of msgfmt is unaffected by the current locale.
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)):
cmd = MakeMessagesCommand()
if cmd.gettext_version < (0, 18, 3):

View File

@ -24,8 +24,8 @@ from django.utils.safestring import SafeBytes, SafeText
from django.utils.translation import (
LANGUAGE_SESSION_KEY, activate, check_for_language, deactivate,
get_language, get_language_from_request, get_language_info, gettext_lazy,
ngettext_lazy, npgettext, npgettext_lazy, pgettext, trans_real, ugettext,
ugettext_lazy, ungettext, ungettext_lazy,
npgettext, npgettext_lazy, pgettext, trans_real, ugettext, ugettext_lazy,
ungettext, ungettext_lazy,
)
from .forms import CompanyForm, I18nForm, SelectDateForm
@ -146,14 +146,11 @@ class TranslationTests(SimpleTestCase):
@override_settings(LOCALE_PATHS=extended_locale_paths)
def test_ungettext_lazy(self):
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_without_format = ungettext_lazy('good result', 'good results')
with translation.override('de'):
self.assertEqual(simple_with_format % 1, '1 gutes Resultat')
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 % 4, '4 guten Resultate!')
self.assertEqual(simple_without_format % 1, 'gutes Resultat')
@ -163,12 +160,6 @@ class TranslationTests(SimpleTestCase):
complex_deferred = ungettext_lazy(
'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(
'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')
with self.assertRaisesMessage(KeyError, 'Your dictionary lacks key'):
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_deferred % {'name': 'Jim', 'num': 1}, 'Willkommen Jim, 1 gutes Resultat')
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):
with self.settings(FORMAT_MODULE_PATH='i18n.other.locale'):
with translation.override('de', deactivate=True):
old = str("%r") % get_format_modules(reverse=True)
new = str("%r") % get_format_modules(reverse=True) # second try
old = "%r" % get_format_modules(reverse=True)
new = "%r" % get_format_modules(reverse=True) # second try
self.assertEqual(new, old, 'Value returned by get_formats_modules() must be preserved between calls.')
def test_localize_templatetag_and_filter(self):

View File

@ -576,7 +576,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
s = msg.message().as_bytes()
self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
s = msg.message().as_string()
self.assertIn(str('Content-Transfer-Encoding: 8bit'), s)
self.assertIn('Content-Transfer-Encoding: 8bit', s)
msg = EmailMessage(
'Subject', 'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'bounce@example.com',
@ -585,7 +585,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
s = msg.message().as_bytes()
self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
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):
# Ticket #18967
@ -608,7 +608,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
parent_s = parent_msg.message().as_string()
# 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.
parent_msg = EmailMessage(
@ -619,7 +619,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
parent_s = parent_msg.message().as_string()
# 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.
parent_msg = EmailMessage(
@ -630,7 +630,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
parent_s = parent_msg.message().as_string()
# 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):
"""
@ -700,11 +700,11 @@ class PythonGlobalState(SimpleTestCase):
def test_8bit_latin(self):
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):
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):
@ -1091,7 +1091,7 @@ class ConsoleBackendTests(BaseEmailBackendTests, SimpleTestCase):
self.stream = sys.stdout = StringIO()
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]
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
# for our tests.
challenge = base64.b64encode(b'somerandomstring13579')
self.push(str('334 %s' % challenge.decode()))
self.push('334 %s' % challenge.decode())
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):

View File

@ -6,9 +6,7 @@ import math
import os
import re
import sys
import tokenize
import uuid
from io import StringIO
import custom_migration_operations.more_operations
import custom_migration_operations.operations
@ -20,7 +18,7 @@ from django.db import migrations, models
from django.db.migrations.writer import (
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.deconstruct import deconstructible
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.
result = self.safe_exec(output)
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):
test_apps = [
'migrations.migrations_test_apps.normal',

View File

@ -60,7 +60,7 @@ class WSGIRequestHandlerTestCase(SimpleTestCase):
handler = WSGIRequestHandler(request, '192.168.0.2', None)
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(
"You're accessing the development server over HTTPS, "
"but it only supports HTTP.",

View File

@ -30,5 +30,5 @@ class SimpleTests(TestCase):
# coerce the returned value.
self.assertIsInstance(obj.__str__(), str)
self.assertIsInstance(obj.__repr__(), str)
self.assertEqual(str(obj), str('Default object'))
self.assertEqual(repr(obj), str('<Default: Default object>'))
self.assertEqual(str(obj), 'Default object')
self.assertEqual(repr(obj), '<Default: Default object>')

View File

@ -356,7 +356,7 @@ class URLPatternReverse(SimpleTestCase):
def test_illegal_kwargs_message(self):
msg = "Reverse for 'places' with keyword arguments '{'arg1': 2}' not found. 1 pattern(s) tried:"
with self.assertRaisesMessage(NoReverseMatch, msg):
reverse('places', kwargs={str('arg1'): 2})
reverse('places', kwargs={'arg1': 2})
class ResolverTests(SimpleTestCase):
@ -436,7 +436,7 @@ class ResolverTests(SimpleTestCase):
)
for tried, expected in zip(e.args[0]['tried'], url_types_names):
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 not e['name']:
self.assertIsNone(t.name, 'Expected no URL name but found %s.' % t.name)

View File

@ -12,14 +12,12 @@ from django.utils.http import urlquote_plus
class TestEncodingUtils(unittest.TestCase):
def test_force_text_exception(self):
"""
Broken __unicode__/__str__ actually raises an error.
Broken __str__ actually raises an error.
"""
class MyString:
def __str__(self):
return b'\xc3\xb6\xc3\xa4\xc3\xbc'
__unicode__ = __str__
# str(s) raises a TypeError if the result is not a text type.
with self.assertRaises(TypeError):
force_text(MyString())