From 38408f8007eae21b9f1cbbcc7f86d4b2042ff86a Mon Sep 17 00:00:00 2001 From: Claude Paroz Date: Sat, 19 May 2012 17:43:34 +0200 Subject: [PATCH] Marked bytestrings with b prefix. Refs #18269 This is a preparation for unicode literals general usage in Django (Python 3 compatibility). --- django/contrib/humanize/tests.py | 2 +- django/core/context_processors.py | 2 +- django/core/files/base.py | 2 +- django/core/files/uploadedfile.py | 4 +- django/core/handlers/wsgi.py | 10 +-- django/db/backends/sqlite3/base.py | 16 ++-- django/db/models/base.py | 4 +- django/forms/models.py | 4 +- django/http/__init__.py | 6 +- django/http/multipartparser.py | 38 ++++---- django/utils/crypto.py | 8 +- django/utils/encoding.py | 4 +- django/utils/html.py | 2 +- django/views/debug.py | 2 +- docs/ref/files/file.txt | 2 +- docs/ref/unicode.txt | 4 +- tests/modeltests/model_forms/tests.py | 14 +-- tests/modeltests/serializers/tests.py | 18 ++-- tests/modeltests/str/tests.py | 8 +- tests/regressiontests/admin_util/tests.py | 2 +- tests/regressiontests/admin_widgets/tests.py | 2 +- tests/regressiontests/cache/tests.py | 2 +- tests/regressiontests/csrf_tests/tests.py | 2 +- tests/regressiontests/file_storage/tests.py | 54 ++++++------ tests/regressiontests/file_uploads/tests.py | 32 +++---- tests/regressiontests/forms/tests/fields.py | 18 ++-- tests/regressiontests/forms/tests/forms.py | 6 +- tests/regressiontests/forms/tests/models.py | 6 +- .../forms/tests/regressions.py | 5 +- tests/regressiontests/forms/tests/widgets.py | 2 +- tests/regressiontests/handlers/tests.py | 2 +- tests/regressiontests/httpwrappers/tests.py | 10 +-- tests/regressiontests/i18n/tests.py | 2 +- tests/regressiontests/localflavor/mk/tests.py | 2 +- tests/regressiontests/mail/tests.py | 36 ++++---- .../model_forms_regress/tests.py | 6 +- tests/regressiontests/requests/tests.py | 88 +++++++++---------- tests/regressiontests/signing/tests.py | 6 +- .../staticfiles_tests/tests.py | 52 +++++------ tests/regressiontests/string_lookup/tests.py | 2 +- tests/regressiontests/templates/tests.py | 14 +-- tests/regressiontests/templates/unicode.py | 12 +-- .../test_client_regress/models.py | 72 +++++++-------- tests/regressiontests/views/__init__.py | 6 +- 44 files changed, 296 insertions(+), 295 deletions(-) diff --git a/django/contrib/humanize/tests.py b/django/contrib/humanize/tests.py index 2aa36443b1..bf6684766b 100644 --- a/django/contrib/humanize/tests.py +++ b/django/contrib/humanize/tests.py @@ -190,7 +190,7 @@ class HumanizeTests(TestCase): orig_humanize_datetime = humanize.datetime orig_timesince_datetime = timesince.datetime humanize.datetime = MockDateTime - timesince.datetime = new.module("mock_datetime") + timesince.datetime = new.module(b"mock_datetime") timesince.datetime.datetime = MockDateTime try: diff --git a/django/core/context_processors.py b/django/core/context_processors.py index 1a2a188246..3ba519188b 100644 --- a/django/core/context_processors.py +++ b/django/core/context_processors.py @@ -22,7 +22,7 @@ def csrf(request): # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. - return 'NOTPROVIDED' + return b'NOTPROVIDED' else: return token _get_val = lazy(_get_val, str) diff --git a/django/core/files/base.py b/django/core/files/base.py index 4d19acd5ba..ad0922b88b 100644 --- a/django/core/files/base.py +++ b/django/core/files/base.py @@ -125,7 +125,7 @@ class ContentFile(File): A File-like object that takes just raw content, rather than an actual file. """ def __init__(self, content, name=None): - content = content or '' + content = content or b'' super(ContentFile, self).__init__(BytesIO(content), name=name) self.size = len(content) diff --git a/django/core/files/uploadedfile.py b/django/core/files/uploadedfile.py index b58349e27b..97d53482e4 100644 --- a/django/core/files/uploadedfile.py +++ b/django/core/files/uploadedfile.py @@ -30,8 +30,8 @@ class UploadedFile(File): self.charset = charset def __repr__(self): - return "<%s: %s (%s)>" % ( - self.__class__.__name__, smart_str(self.name), self.content_type) + return smart_str("<%s: %s (%s)>" % ( + self.__class__.__name__, self.name, self.content_type)) def _get_name(self): return self._name diff --git a/django/core/handlers/wsgi.py b/django/core/handlers/wsgi.py index 0639ef19da..128ff7ac64 100644 --- a/django/core/handlers/wsgi.py +++ b/django/core/handlers/wsgi.py @@ -78,14 +78,14 @@ class LimitedStream(object): def __init__(self, stream, limit, buf_size=64 * 1024 * 1024): self.stream = stream self.remaining = limit - self.buffer = '' + self.buffer = b'' self.buf_size = buf_size def _read_limited(self, size=None): if size is None or size > self.remaining: size = self.remaining if size == 0: - return '' + return b'' result = self.stream.read(size) self.remaining -= len(result) return result @@ -93,17 +93,17 @@ class LimitedStream(object): def read(self, size=None): if size is None: result = self.buffer + self._read_limited() - self.buffer = '' + self.buffer = b'' elif size < len(self.buffer): result = self.buffer[:size] self.buffer = self.buffer[size:] else: # size >= len(self.buffer) result = self.buffer + self._read_limited(size - len(self.buffer)) - self.buffer = '' + self.buffer = b'' return result def readline(self, size=None): - while '\n' not in self.buffer and \ + while b'\n' not in self.buffer and \ (size is None or len(self.buffer) < size): if size: # since size is not None here, len(self.buffer) < size diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py index 7ce9dd38eb..4fba304e23 100644 --- a/django/db/backends/sqlite3/base.py +++ b/django/db/backends/sqlite3/base.py @@ -51,15 +51,15 @@ def adapt_datetime_with_timezone_support(value): default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) value = value.astimezone(timezone.utc).replace(tzinfo=None) - return value.isoformat(" ") + return value.isoformat(b" ") -Database.register_converter("bool", lambda s: str(s) == '1') -Database.register_converter("time", parse_time) -Database.register_converter("date", parse_date) -Database.register_converter("datetime", parse_datetime_with_timezone_support) -Database.register_converter("timestamp", parse_datetime_with_timezone_support) -Database.register_converter("TIMESTAMP", parse_datetime_with_timezone_support) -Database.register_converter("decimal", util.typecast_decimal) +Database.register_converter(b"bool", lambda s: str(s) == '1') +Database.register_converter(b"time", parse_time) +Database.register_converter(b"date", parse_date) +Database.register_converter(b"datetime", parse_datetime_with_timezone_support) +Database.register_converter(b"timestamp", parse_datetime_with_timezone_support) +Database.register_converter(b"TIMESTAMP", parse_datetime_with_timezone_support) +Database.register_converter(b"decimal", util.typecast_decimal) Database.register_adapter(datetime.datetime, adapt_datetime_with_timezone_support) Database.register_adapter(decimal.Decimal, util.rev_typecast_decimal) if Database.version_info >= (2, 4, 1): diff --git a/django/db/models/base.py b/django/db/models/base.py index a555ad9f13..08bfc73a87 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -57,11 +57,11 @@ class ModelBase(type): new_class.add_to_class('_meta', Options(meta, **kwargs)) if not abstract: - new_class.add_to_class('DoesNotExist', subclass_exception('DoesNotExist', + new_class.add_to_class('DoesNotExist', subclass_exception(b'DoesNotExist', tuple(x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.abstract) or (ObjectDoesNotExist,), module)) - new_class.add_to_class('MultipleObjectsReturned', subclass_exception('MultipleObjectsReturned', + new_class.add_to_class('MultipleObjectsReturned', subclass_exception(b'MultipleObjectsReturned', tuple(x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.abstract) or (MultipleObjectsReturned,), module)) diff --git a/django/forms/models.py b/django/forms/models.py index ea80f8d855..5fcf9590eb 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -388,10 +388,10 @@ def modelform_factory(model, form=ModelForm, fields=None, exclude=None, parent = (object,) if hasattr(form, 'Meta'): parent = (form.Meta, object) - Meta = type('Meta', parent, attrs) + Meta = type(b'Meta', parent, attrs) # Give this new form class a reasonable name. - class_name = model.__name__ + 'Form' + class_name = model.__name__ + b'Form' # Class attributes for the new form class. form_class_attrs = { diff --git a/django/http/__init__.py b/django/http/__init__.py index 2bad146010..bf848deb38 100644 --- a/django/http/__init__.py +++ b/django/http/__init__.py @@ -18,7 +18,7 @@ _cookie_encodes_correctly = Cookie.SimpleCookie().value_encode(';') == (';', '"\ # See ticket #13007, http://bugs.python.org/issue2193 and http://trac.edgewall.org/ticket/2256 _tc = Cookie.SimpleCookie() try: - _tc.load('foo:bar=1') + _tc.load(b'foo:bar=1') _cookie_allows_colon_in_names = True except Cookie.CookieError: _cookie_allows_colon_in_names = False @@ -650,8 +650,8 @@ class HttpResponse(object): def _get_content(self): if self.has_header('Content-Encoding'): - return ''.join([str(e) for e in self._container]) - return ''.join([smart_str(e, self._charset) for e in self._container]) + return b''.join([str(e) for e in self._container]) + return b''.join([smart_str(e, self._charset) for e in self._container]) def _set_content(self, value): if hasattr(value, '__iter__'): diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py index d09c8fba86..162c08e38d 100644 --- a/django/http/multipartparser.py +++ b/django/http/multipartparser.py @@ -268,7 +268,7 @@ class LazyStream(object): """ self._producer = producer self._empty = False - self._leftover = '' + self._leftover = b'' self.length = length self.position = 0 self._remaining = length @@ -282,7 +282,7 @@ class LazyStream(object): remaining = (size is not None and [size] or [self._remaining])[0] # do the whole thing in one shot if no limit was provided. if remaining is None: - yield ''.join(self) + yield b''.join(self) return # otherwise do some bookkeeping to return exactly enough @@ -298,7 +298,7 @@ class LazyStream(object): remaining -= len(emitting) yield emitting - out = ''.join(parts()) + out = b''.join(parts()) return out def next(self): @@ -311,7 +311,7 @@ class LazyStream(object): """ if self._leftover: output = self._leftover - self._leftover = '' + self._leftover = b'' else: output = next(self._producer) self._unget_history = [] @@ -341,7 +341,7 @@ class LazyStream(object): return self._update_unget_history(len(bytes)) self.position -= len(bytes) - self._leftover = ''.join([bytes, self._leftover]) + self._leftover = b''.join([bytes, self._leftover]) def _update_unget_history(self, num_bytes): """ @@ -459,7 +459,7 @@ class BoundaryIter(object): if not chunks: raise StopIteration() - chunk = ''.join(chunks) + chunk = b''.join(chunks) boundary = self._find_boundary(chunk, len(chunk) < self._rollback) if boundary: @@ -495,9 +495,9 @@ class BoundaryIter(object): end = index next = index + len(self._boundary) # backup over CRLF - if data[max(0,end-1)] == '\n': + if data[max(0,end-1)] == b'\n': end -= 1 - if data[max(0,end-1)] == '\r': + if data[max(0,end-1)] == b'\r': end -= 1 return end, next @@ -531,7 +531,7 @@ def parse_boundary_stream(stream, max_header_size): # 'find' returns the top of these four bytes, so we'll # need to munch them later to prevent them from polluting # the payload. - header_end = chunk.find('\r\n\r\n') + header_end = chunk.find(b'\r\n\r\n') def _parse_header(line): main_value_pair, params = parse_header(line) @@ -557,7 +557,7 @@ def parse_boundary_stream(stream, max_header_size): outdict = {} # Eliminate blank lines - for line in header.split('\r\n'): + for line in header.split(b'\r\n'): # This terminology ("main value" and "dictionary of # parameters") is from the Python docs. try: @@ -580,7 +580,7 @@ def parse_boundary_stream(stream, max_header_size): class Parser(object): def __init__(self, stream, boundary): self._stream = stream - self._separator = '--' + boundary + self._separator = b'--' + boundary def __iter__(self): boundarystream = InterBoundaryIter(self._stream, self._separator) @@ -590,27 +590,27 @@ class Parser(object): def parse_header(line): """ Parse the header into a key-value. """ - plist = _parse_header_params(';' + line) + plist = _parse_header_params(b';' + line) key = plist.pop(0).lower() pdict = {} for p in plist: - i = p.find('=') + i = p.find(b'=') if i >= 0: name = p[:i].strip().lower() value = p[i+1:].strip() - if len(value) >= 2 and value[0] == value[-1] == '"': + if len(value) >= 2 and value[0] == value[-1] == b'"': value = value[1:-1] - value = value.replace('\\\\', '\\').replace('\\"', '"') + value = value.replace(b'\\\\', b'\\').replace(b'\\"', b'"') pdict[name] = value return key, pdict def _parse_header_params(s): plist = [] - while s[:1] == ';': + while s[:1] == b';': s = s[1:] - end = s.find(';') - while end > 0 and s.count('"', 0, end) % 2: - end = s.find(';', end + 1) + end = s.find(b';') + while end > 0 and s.count(b'"', 0, end) % 2: + end = s.find(b';', end + 1) if end < 0: end = len(s) f = s[:end] diff --git a/django/utils/crypto.py b/django/utils/crypto.py index 44b7faf492..f826c8a80c 100644 --- a/django/utils/crypto.py +++ b/django/utils/crypto.py @@ -23,8 +23,8 @@ except NotImplementedError: from django.conf import settings -_trans_5c = "".join([chr(x ^ 0x5C) for x in xrange(256)]) -_trans_36 = "".join([chr(x ^ 0x36) for x in xrange(256)]) +_trans_5c = b"".join([chr(x ^ 0x5C) for x in xrange(256)]) +_trans_36 = b"".join([chr(x ^ 0x36) for x in xrange(256)]) def salted_hmac(key_salt, value, secret=None): @@ -148,11 +148,11 @@ def pbkdf2(password, salt, iterations, dklen=0, digest=None): def F(i): def U(): - u = salt + struct.pack('>I', i) + u = salt + struct.pack(b'>I', i) for j in xrange(int(iterations)): u = _fast_hmac(password, u, digest).digest() yield _bin_to_long(u) return _long_to_bin(reduce(operator.xor, U()), hex_format_string) T = [F(x) for x in range(1, l + 1)] - return ''.join(T[:-1]) + T[-1][:r] + return b''.join(T[:-1]) + T[-1][:r] diff --git a/django/utils/encoding.py b/django/utils/encoding.py index d9b59448a9..9d9b8b8a2d 100644 --- a/django/utils/encoding.py +++ b/django/utils/encoding.py @@ -154,7 +154,7 @@ def iri_to_uri(iri): # converted. if iri is None: return iri - return urllib.quote(smart_str(iri), safe="/#%[]=:;$&()+,!?*@'~") + return urllib.quote(smart_str(iri), safe=b"/#%[]=:;$&()+,!?*@'~") def filepath_to_uri(path): """Convert an file system path to a URI portion that is suitable for @@ -173,7 +173,7 @@ def filepath_to_uri(path): return path # I know about `os.sep` and `os.altsep` but I want to leave # some flexibility for hardcoding separators. - return urllib.quote(smart_str(path).replace("\\", "/"), safe="/~!*()'") + return urllib.quote(smart_str(path).replace("\\", "/"), safe=b"/~!*()'") # The encoding of the default system locale but falls back to the # given fallback encoding if the encoding is unsupported by python or could diff --git a/django/utils/html.py b/django/utils/html.py index 6760f7adad..1b1a16a911 100644 --- a/django/utils/html.py +++ b/django/utils/html.py @@ -116,7 +116,7 @@ def smart_urlquote(url): # contains a % not followed by two hexadecimal digits. See #9655. if '%' not in url or unquoted_percents_re.search(url): # See http://bugs.python.org/issue2637 - url = urllib.quote(smart_str(url), safe='!*\'();:@&=+$,/?#[]~') + url = urllib.quote(smart_str(url), safe=b'!*\'();:@&=+$,/?#[]~') return force_unicode(url) diff --git a/django/views/debug.py b/django/views/debug.py index 418b2bab9f..7bdf0d25ee 100644 --- a/django/views/debug.py +++ b/django/views/debug.py @@ -333,7 +333,7 @@ class ExceptionReporter(object): source = source.splitlines() if source is None: try: - with open(filename) as fp: + with open(filename, 'rb') as fp: source = fp.readlines() except (OSError, IOError): pass diff --git a/docs/ref/files/file.txt b/docs/ref/files/file.txt index 013d113c84..10108d1f4f 100644 --- a/docs/ref/files/file.txt +++ b/docs/ref/files/file.txt @@ -96,7 +96,7 @@ The ``ContentFile`` Class from django.core.files.base import ContentFile - f1 = ContentFile("my string content") + f1 = ContentFile(b"my string content") f2 = ContentFile(u"my unicode content encoded as UTF-8".encode('UTF-8')) .. currentmodule:: django.core.files.images diff --git a/docs/ref/unicode.txt b/docs/ref/unicode.txt index 1286dcfdd0..46ce4138a4 100644 --- a/docs/ref/unicode.txt +++ b/docs/ref/unicode.txt @@ -269,7 +269,7 @@ You can pass either Unicode strings or UTF-8 bytestrings as arguments to querysets are identical:: qs = People.objects.filter(name__contains=u'Å') - qs = People.objects.filter(name__contains='\xc3\x85') # UTF-8 encoding of Å + qs = People.objects.filter(name__contains=b'\xc3\x85') # UTF-8 encoding of Å Templates ========= @@ -277,7 +277,7 @@ Templates You can use either Unicode or bytestrings when creating templates manually:: from django.template import Template - t1 = Template('This is a bytestring template.') + t1 = Template(b'This is a bytestring template.') t2 = Template(u'This is a Unicode template.') But the common case is to read templates from the filesystem, and this creates diff --git a/tests/modeltests/model_forms/tests.py b/tests/modeltests/model_forms/tests.py index fdaae5b852..af8bcbca4e 100644 --- a/tests/modeltests/model_forms/tests.py +++ b/tests/modeltests/model_forms/tests.py @@ -1126,7 +1126,7 @@ class OldFormForXTests(TestCase): f = TextFileForm( data={'description': u'Assistance'}, - files={'file': SimpleUploadedFile('test1.txt', 'hello world')}) + files={'file': SimpleUploadedFile('test1.txt', b'hello world')}) self.assertEqual(f.is_valid(), True) self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile) instance = f.save() @@ -1135,7 +1135,7 @@ class OldFormForXTests(TestCase): instance.file.delete() f = TextFileForm( data={'description': u'Assistance'}, - files={'file': SimpleUploadedFile('test1.txt', 'hello world')}) + files={'file': SimpleUploadedFile('test1.txt', b'hello world')}) self.assertEqual(f.is_valid(), True) self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile) instance = f.save() @@ -1144,7 +1144,7 @@ class OldFormForXTests(TestCase): # Check if the max_length attribute has been inherited from the model. f = TextFileForm( data={'description': u'Assistance'}, - files={'file': SimpleUploadedFile('test-maxlength.txt', 'hello world')}) + files={'file': SimpleUploadedFile('test-maxlength.txt', b'hello world')}) self.assertEqual(f.is_valid(), False) # Edit an instance that already has the file defined in the model. This will not @@ -1165,7 +1165,7 @@ class OldFormForXTests(TestCase): f = TextFileForm( data={'description': u'Assistance'}, - files={'file': SimpleUploadedFile('test2.txt', 'hello world')}, instance=instance) + files={'file': SimpleUploadedFile('test2.txt', b'hello world')}, instance=instance) self.assertEqual(f.is_valid(), True) instance = f.save() self.assertEqual(instance.file.name, 'tests/test2.txt') @@ -1174,7 +1174,7 @@ class OldFormForXTests(TestCase): instance.file.delete() f = TextFileForm( data={'description': u'Assistance'}, - files={'file': SimpleUploadedFile('test2.txt', 'hello world')}) + files={'file': SimpleUploadedFile('test2.txt', b'hello world')}) self.assertEqual(f.is_valid(), True) instance = f.save() self.assertEqual(instance.file.name, 'tests/test2.txt') @@ -1193,7 +1193,7 @@ class OldFormForXTests(TestCase): f = TextFileForm( data={'description': u'Assistance'}, - files={'file': SimpleUploadedFile('test3.txt', 'hello world')}, instance=instance) + files={'file': SimpleUploadedFile('test3.txt', b'hello world')}, instance=instance) self.assertEqual(f.is_valid(), True) instance = f.save() self.assertEqual(instance.file.name, 'tests/test3.txt') @@ -1215,7 +1215,7 @@ class OldFormForXTests(TestCase): f = TextFileForm( data={'description': u'Assistance'}, - files={'file': SimpleUploadedFile('test3.txt', 'hello world')}) + files={'file': SimpleUploadedFile('test3.txt', b'hello world')}) self.assertEqual(f.is_valid(), True) instance = f.save() self.assertEqual(instance.file.name, 'tests/test3.txt') diff --git a/tests/modeltests/serializers/tests.py b/tests/modeltests/serializers/tests.py index dac098763c..e792c944a1 100644 --- a/tests/modeltests/serializers/tests.py +++ b/tests/modeltests/serializers/tests.py @@ -113,8 +113,8 @@ class SerializersTestBase(object): Tests the ability to create new objects by modifying serialized content. """ - old_headline = "Poker has no place on ESPN" - new_headline = "Poker has no place on television" + old_headline = b"Poker has no place on ESPN" + new_headline = b"Poker has no place on television" serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) serial_str = serial_str.replace(old_headline, new_headline) @@ -284,7 +284,7 @@ class SerializersTransactionTestBase(object): class XmlSerializerTestCase(SerializersTestBase, TestCase): serializer_name = "xml" - pkless_str = """ + pkless_str = b""" Reference @@ -330,7 +330,7 @@ class XmlSerializerTestCase(SerializersTestBase, TestCase): class XmlSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase): serializer_name = "xml" - fwd_ref_str = """ + fwd_ref_str = b""" 1 @@ -350,7 +350,7 @@ class XmlSerializerTransactionTestCase(SerializersTransactionTestBase, Transacti class JsonSerializerTestCase(SerializersTestBase, TestCase): serializer_name = "json" - pkless_str = """[{"pk": null, "model": "serializers.category", "fields": {"name": "Reference"}}]""" + pkless_str = b"""[{"pk": null, "model": "serializers.category", "fields": {"name": "Reference"}}]""" @staticmethod def _validate_output(serial_str): @@ -380,7 +380,7 @@ class JsonSerializerTestCase(SerializersTestBase, TestCase): class JsonSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase): serializer_name = "json" - fwd_ref_str = """[ + fwd_ref_str = b"""[ { "pk": 1, "model": "serializers.article", @@ -413,7 +413,7 @@ except ImportError: else: class YamlSerializerTestCase(SerializersTestBase, TestCase): serializer_name = "yaml" - fwd_ref_str = """- fields: + fwd_ref_str = b"""- fields: headline: Forward references pose no problem pub_date: 2006-06-16 15:00:00 categories: [1] @@ -429,7 +429,7 @@ else: pk: 1 model: serializers.author""" - pkless_str = """- fields: + pkless_str = b"""- fields: name: Reference pk: null model: serializers.category""" @@ -469,7 +469,7 @@ else: class YamlSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase): serializer_name = "yaml" - fwd_ref_str = """- fields: + fwd_ref_str = b"""- fields: headline: Forward references pose no problem pub_date: 2006-06-16 15:00:00 categories: [1] diff --git a/tests/modeltests/str/tests.py b/tests/modeltests/str/tests.py index 9f6cf7ad96..1b0eb0972f 100644 --- a/tests/modeltests/str/tests.py +++ b/tests/modeltests/str/tests.py @@ -11,11 +11,11 @@ from .models import Article, InternationalArticle class SimpleTests(TestCase): def test_basic(self): a = Article.objects.create( - headline='Area man programs in Python', + headline=b'Area man programs in Python', pub_date=datetime.datetime(2005, 7, 28) ) - self.assertEqual(str(a), 'Area man programs in Python') - self.assertEqual(repr(a), '') + self.assertEqual(str(a), b'Area man programs in Python') + self.assertEqual(repr(a), b'') def test_international(self): a = InternationalArticle.objects.create( @@ -23,4 +23,4 @@ class SimpleTests(TestCase): pub_date=datetime.datetime(2005, 7, 28) ) # The default str() output will be the UTF-8 encoded output of __unicode__(). - self.assertEqual(str(a), 'Girl wins \xe2\x82\xac12.500 in lottery') \ No newline at end of file + self.assertEqual(str(a), b'Girl wins \xe2\x82\xac12.500 in lottery') diff --git a/tests/regressiontests/admin_util/tests.py b/tests/regressiontests/admin_util/tests.py index 8113f2e16d..055f494dcd 100644 --- a/tests/regressiontests/admin_util/tests.py +++ b/tests/regressiontests/admin_util/tests.py @@ -170,7 +170,7 @@ class UtilTests(unittest.TestCase): ) self.assertEqual( label_for_field("__str__", Article), - "article" + b"article" ) self.assertRaises( diff --git a/tests/regressiontests/admin_widgets/tests.py b/tests/regressiontests/admin_widgets/tests.py index 8de68b2404..be1d294051 100644 --- a/tests/regressiontests/admin_widgets/tests.py +++ b/tests/regressiontests/admin_widgets/tests.py @@ -280,7 +280,7 @@ class AdminFileWidgetTest(DjangoTestCase): ) self.assertHTMLEqual( - conditional_escape(w.render('test', SimpleUploadedFile('test', 'content'))), + conditional_escape(w.render('test', SimpleUploadedFile('test', b'content'))), '', ) diff --git a/tests/regressiontests/cache/tests.py b/tests/regressiontests/cache/tests.py index 780718b487..cbba7c19a3 100644 --- a/tests/regressiontests/cache/tests.py +++ b/tests/regressiontests/cache/tests.py @@ -822,7 +822,7 @@ class DBCacheTests(BaseCacheTests, TransactionTestCase): def test_second_call_doesnt_crash(self): err = StringIO.StringIO() management.call_command('createcachetable', self._table_name, verbosity=0, interactive=False, stderr=err) - self.assertTrue("Cache table 'test cache table' could not be created" in err.getvalue()) + self.assertTrue(b"Cache table 'test cache table' could not be created" in err.getvalue()) @override_settings(USE_TZ=True) diff --git a/tests/regressiontests/csrf_tests/tests.py b/tests/regressiontests/csrf_tests/tests.py index d403951ae2..2d9b4f755f 100644 --- a/tests/regressiontests/csrf_tests/tests.py +++ b/tests/regressiontests/csrf_tests/tests.py @@ -47,7 +47,7 @@ class TestingHttpRequest(HttpRequest): class CsrfViewMiddlewareTest(TestCase): # The csrf token is potentially from an untrusted source, so could have # characters that need dealing with. - _csrf_id_cookie = "<1>\xc2\xa1" + _csrf_id_cookie = b"<1>\xc2\xa1" _csrf_id = "1" def _get_GET_no_csrf_cookie_request(self): diff --git a/tests/regressiontests/file_storage/tests.py b/tests/regressiontests/file_storage/tests.py index ce64c5de23..87035d96d7 100644 --- a/tests/regressiontests/file_storage/tests.py +++ b/tests/regressiontests/file_storage/tests.py @@ -127,7 +127,7 @@ class FileStorageTests(unittest.TestCase): """ self.assertFalse(self.storage.exists('test.file')) - f = ContentFile('custom contents') + f = ContentFile(b'custom contents') f_name = self.storage.save('test.file', f) atime = self.storage.accessed_time(f_name) @@ -143,7 +143,7 @@ class FileStorageTests(unittest.TestCase): """ self.assertFalse(self.storage.exists('test.file')) - f = ContentFile('custom contents') + f = ContentFile(b'custom contents') f_name = self.storage.save('test.file', f) ctime = self.storage.created_time(f_name) @@ -160,7 +160,7 @@ class FileStorageTests(unittest.TestCase): """ self.assertFalse(self.storage.exists('test.file')) - f = ContentFile('custom contents') + f = ContentFile(b'custom contents') f_name = self.storage.save('test.file', f) mtime = self.storage.modified_time(f_name) @@ -177,7 +177,7 @@ class FileStorageTests(unittest.TestCase): """ self.assertFalse(self.storage.exists('test.file')) - f = ContentFile('custom contents') + f = ContentFile(b'custom contents') f.name = 'test.file' storage_f_name = self.storage.save(None, f) @@ -194,11 +194,11 @@ class FileStorageTests(unittest.TestCase): """ self.assertFalse(self.storage.exists('path/to')) self.storage.save('path/to/test.file', - ContentFile('file saved with path')) + ContentFile(b'file saved with path')) self.assertTrue(self.storage.exists('path/to')) self.assertEqual(self.storage.open('path/to/test.file').read(), - 'file saved with path') + b'file saved with path') self.assertTrue(os.path.exists( os.path.join(self.temp_dir, 'path', 'to', 'test.file'))) @@ -211,7 +211,7 @@ class FileStorageTests(unittest.TestCase): """ self.assertFalse(self.storage.exists('test.file')) - f = ContentFile('custom contents') + f = ContentFile(b'custom contents') f_name = self.storage.save('test.file', f) self.assertEqual(self.storage.path(f_name), @@ -246,8 +246,8 @@ class FileStorageTests(unittest.TestCase): self.assertFalse(self.storage.exists('storage_test_2')) self.assertFalse(self.storage.exists('storage_dir_1')) - f = self.storage.save('storage_test_1', ContentFile('custom content')) - f = self.storage.save('storage_test_2', ContentFile('custom content')) + f = self.storage.save('storage_test_1', ContentFile(b'custom content')) + f = self.storage.save('storage_test_2', ContentFile(b'custom content')) os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1')) dirs, files = self.storage.listdir('') @@ -304,18 +304,18 @@ class FileStorageTests(unittest.TestCase): os.makedirs = fake_makedirs self.storage.save('normal/test.file', - ContentFile('saved normally')) + ContentFile(b'saved normally')) self.assertEqual(self.storage.open('normal/test.file').read(), - 'saved normally') + b'saved normally') self.storage.save('raced/test.file', - ContentFile('saved with race')) + ContentFile(b'saved with race')) self.assertEqual(self.storage.open('raced/test.file').read(), - 'saved with race') + b'saved with race') # Check that OSErrors aside from EEXIST are still raised. self.assertRaises(OSError, - self.storage.save, 'error/test.file', ContentFile('not saved')) + self.storage.save, 'error/test.file', ContentFile(b'not saved')) finally: os.makedirs = real_makedirs @@ -341,16 +341,16 @@ class FileStorageTests(unittest.TestCase): try: os.remove = fake_remove - self.storage.save('normal.file', ContentFile('delete normally')) + self.storage.save('normal.file', ContentFile(b'delete normally')) self.storage.delete('normal.file') self.assertFalse(self.storage.exists('normal.file')) - self.storage.save('raced.file', ContentFile('delete with race')) + self.storage.save('raced.file', ContentFile(b'delete with race')) self.storage.delete('raced.file') self.assertFalse(self.storage.exists('normal.file')) # Check that OSErrors aside from ENOENT are still raised. - self.storage.save('error.file', ContentFile('delete with error')) + self.storage.save('error.file', ContentFile(b'delete with error')) self.assertRaises(OSError, self.storage.delete, 'error.file') finally: os.remove = real_remove @@ -374,9 +374,9 @@ class CustomStorageTests(FileStorageTests): storage_class = CustomStorage def test_custom_get_available_name(self): - first = self.storage.save('custom_storage', ContentFile('custom contents')) + first = self.storage.save('custom_storage', ContentFile(b'custom contents')) self.assertEqual(first, 'custom_storage') - second = self.storage.save('custom_storage', ContentFile('more contents')) + second = self.storage.save('custom_storage', ContentFile(b'more contents')) self.assertEqual(second, 'custom_storage.2') self.storage.delete(first) self.storage.delete(second) @@ -410,7 +410,7 @@ class FileSaveRaceConditionTest(unittest.TestCase): shutil.rmtree(self.storage_dir) def save_file(self, name): - name = self.storage.save(name, SlowFile("Data")) + name = self.storage.save(name, SlowFile(b"Data")) def test_race_condition(self): self.thread.start() @@ -433,7 +433,7 @@ class FileStoragePermissions(unittest.TestCase): shutil.rmtree(self.storage_dir) def test_file_upload_permissions(self): - name = self.storage.save("the_file", ContentFile("data")) + name = self.storage.save("the_file", ContentFile(b"data")) actual_mode = os.stat(self.storage.path(name))[0] & 0777 self.assertEqual(actual_mode, 0666) @@ -453,8 +453,8 @@ class FileStoragePathParsing(unittest.TestCase): sure we still mangle the file name instead of the directory name. """ - self.storage.save('dotted.path/test', ContentFile("1")) - self.storage.save('dotted.path/test', ContentFile("2")) + self.storage.save('dotted.path/test', ContentFile(b"1")) + self.storage.save('dotted.path/test', ContentFile(b"2")) self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path'))) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test'))) @@ -465,8 +465,8 @@ class FileStoragePathParsing(unittest.TestCase): File names with a dot as their first character don't have an extension, and the underscore should get added to the end. """ - self.storage.save('dotted.path/.test', ContentFile("1")) - self.storage.save('dotted.path/.test', ContentFile("2")) + self.storage.save('dotted.path/.test', ContentFile(b"1")) + self.storage.save('dotted.path/.test', ContentFile(b"2")) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test'))) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1'))) @@ -542,11 +542,11 @@ class ContentFileTestCase(unittest.TestCase): Test that the constructor of ContentFile accepts 'name' (#16590). """ def test_content_file_default_name(self): - self.assertEqual(ContentFile("content").name, None) + self.assertEqual(ContentFile(b"content").name, None) def test_content_file_custom_name(self): name = "I can have a name too!" - self.assertEqual(ContentFile("content", name=name).name, name) + self.assertEqual(ContentFile(b"content", name=name).name, name) class NoNameFileTestCase(unittest.TestCase): """ diff --git a/tests/regressiontests/file_uploads/tests.py b/tests/regressiontests/file_uploads/tests.py index de552d88ec..c8de8035f9 100644 --- a/tests/regressiontests/file_uploads/tests.py +++ b/tests/regressiontests/file_uploads/tests.py @@ -24,7 +24,7 @@ UNICODE_FILENAME = u'test-0123456789_中文_Orléans.jpg' class FileUploadTests(TestCase): def test_simple_upload(self): - with open(__file__) as fp: + with open(__file__, 'rb') as fp: post_data = { 'name': 'Ringo', 'file_field': fp, @@ -36,11 +36,11 @@ class FileUploadTests(TestCase): tdir = tempfile.gettempdir() file1 = tempfile.NamedTemporaryFile(suffix=".file1", dir=tdir) - file1.write('a' * (2 ** 21)) + file1.write(b'a' * (2 ** 21)) file1.seek(0) file2 = tempfile.NamedTemporaryFile(suffix=".file2", dir=tdir) - file2.write('a' * (10 * 2 ** 20)) + file2.write(b'a' * (10 * 2 ** 20)) file2.seek(0) post_data = { @@ -89,7 +89,7 @@ class FileUploadTests(TestCase): # This file contains chinese symbols and an accented char in the name. with open(os.path.join(tdir, UNICODE_FILENAME.encode('utf-8')), 'w+b') as file1: - file1.write('b' * (2 ** 10)) + file1.write(b'b' * (2 ** 10)) file1.seek(0) post_data = { @@ -214,7 +214,7 @@ class FileUploadTests(TestCase): 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/file_uploads/echo/', 'REQUEST_METHOD': 'POST', - 'wsgi.input': client.FakePayload(''), + 'wsgi.input': client.FakePayload(b''), } got = json.loads(self.client.request(**r).content) self.assertEqual(got, {}) @@ -222,12 +222,12 @@ class FileUploadTests(TestCase): def test_custom_upload_handler(self): # A small file (under the 5M quota) smallfile = tempfile.NamedTemporaryFile() - smallfile.write('a' * (2 ** 21)) + smallfile.write(b'a' * (2 ** 21)) smallfile.seek(0) # A big file (over the quota) bigfile = tempfile.NamedTemporaryFile() - bigfile.write('a' * (10 * 2 ** 20)) + bigfile.write(b'a' * (10 * 2 ** 20)) bigfile.seek(0) # Small file posting should work. @@ -242,7 +242,7 @@ class FileUploadTests(TestCase): def test_broken_custom_upload_handler(self): f = tempfile.NamedTemporaryFile() - f.write('a' * (2 ** 21)) + f.write(b'a' * (2 ** 21)) f.seek(0) # AttributeError: You cannot alter upload handlers after the upload has been processed. @@ -255,15 +255,15 @@ class FileUploadTests(TestCase): def test_fileupload_getlist(self): file1 = tempfile.NamedTemporaryFile() - file1.write('a' * (2 ** 23)) + file1.write(b'a' * (2 ** 23)) file1.seek(0) file2 = tempfile.NamedTemporaryFile() - file2.write('a' * (2 * 2 ** 18)) + file2.write(b'a' * (2 * 2 ** 18)) file2.seek(0) file2a = tempfile.NamedTemporaryFile() - file2a.write('a' * (5 * 2 ** 20)) + file2a.write(b'a' * (5 * 2 ** 20)) file2a.seek(0) response = self.client.post('/file_uploads/getlist_count/', { @@ -299,14 +299,14 @@ class FileUploadTests(TestCase): # this test would fail. So we need to know exactly what kind of error # it raises when there is an attempt to read more than the available bytes: try: - client.FakePayload('a').read(2) + client.FakePayload(b'a').read(2) except Exception as reference_error: pass # install the custom handler that tries to access request.POST self.client.handler = POSTAccessingHandler() - with open(__file__) as fp: + with open(__file__, 'rb') as fp: post_data = { 'name': 'Ringo', 'file_field': fp, @@ -374,7 +374,7 @@ class DirectoryCreationTests(unittest.TestCase): """Permission errors are not swallowed""" os.chmod(temp_storage.location, 0500) try: - self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x')) + self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', b'x')) except OSError as err: self.assertEqual(err.errno, errno.EACCES) except Exception: @@ -383,9 +383,9 @@ class DirectoryCreationTests(unittest.TestCase): def test_not_a_directory(self): """The correct IOError is raised when the upload directory name exists but isn't a directory""" # Create a file with the upload directory name - open(UPLOAD_TO, 'w').close() + open(UPLOAD_TO, 'wb').close() try: - self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x')) + self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', b'x')) except IOError as err: # The test needs to be done on a specific string as IOError # is raised even without the patch (just not early enough) diff --git a/tests/regressiontests/forms/tests/fields.py b/tests/regressiontests/forms/tests/fields.py index a7d98ec7d4..d66ee2c084 100644 --- a/tests/regressiontests/forms/tests/fields.py +++ b/tests/regressiontests/forms/tests/fields.py @@ -540,27 +540,27 @@ class FieldsTests(SimpleTestCase): self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None, '') self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) - self.assertRaisesMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', '')) - self.assertRaisesMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', ''), '') + self.assertRaisesMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', b'')) + self.assertRaisesMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', b''), '') self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf')) self.assertRaisesMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, 'some content that is not a file') self.assertRaisesMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', None)) - self.assertRaisesMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', '')) - self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content')))) - self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')))) - self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content'), 'files/test4.pdf'))) + self.assertRaisesMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', b'')) + self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content')))) + self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', u'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))))) + self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'), 'files/test4.pdf'))) def test_filefield_2(self): f = FileField(max_length = 5) - self.assertRaisesMessage(ValidationError, "[u'Ensure this filename has at most 5 characters (it has 18).']", f.clean, SimpleUploadedFile('test_maxlength.txt', 'hello world')) + self.assertRaisesMessage(ValidationError, "[u'Ensure this filename has at most 5 characters (it has 18).']", f.clean, SimpleUploadedFile('test_maxlength.txt', b'hello world')) self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) - self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content')))) + self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content')))) def test_filefield_3(self): f = FileField(allow_empty_file=True) self.assertEqual(SimpleUploadedFile, - type(f.clean(SimpleUploadedFile('name', '')))) + type(f.clean(SimpleUploadedFile('name', b'')))) # URLField ################################################################## diff --git a/tests/regressiontests/forms/tests/forms.py b/tests/regressiontests/forms/tests/forms.py index 3f529f23db..16cf46fc29 100644 --- a/tests/regressiontests/forms/tests/forms.py +++ b/tests/regressiontests/forms/tests/forms.py @@ -1463,17 +1463,17 @@ class FormsTestCase(TestCase): f = FileForm(data={}, files={}, auto_id=False) self.assertHTMLEqual(f.as_table(), 'File1:
  • This field is required.
') - f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', '')}, auto_id=False) + f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'')}, auto_id=False) self.assertHTMLEqual(f.as_table(), 'File1:
  • The submitted file is empty.
') f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False) self.assertHTMLEqual(f.as_table(), 'File1:
  • No file was submitted. Check the encoding type on the form.
') - f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', 'some content')}, auto_id=False) + f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'some content')}, auto_id=False) self.assertHTMLEqual(f.as_table(), 'File1:') self.assertTrue(f.is_valid()) - f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False) + f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', u'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False) self.assertHTMLEqual(f.as_table(), 'File1:') def test_basic_processing_in_view(self): diff --git a/tests/regressiontests/forms/tests/models.py b/tests/regressiontests/forms/tests/models.py index 64cd18bde6..7f569651c7 100644 --- a/tests/regressiontests/forms/tests/models.py +++ b/tests/regressiontests/forms/tests/models.py @@ -106,7 +106,7 @@ class ModelFormCallableModelDefault(TestCase): class FormsModelTestCase(TestCase): def test_unicode_filename(self): # FileModel with unicode filename and data ######################### - f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False) + f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', u'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False) self.assertTrue(f.is_valid()) self.assertTrue('file1' in f.cleaned_data) m = FileModel.objects.create(file=f.cleaned_data['file1']) @@ -177,7 +177,7 @@ class RelatedModelFormTests(TestCase): class Meta: model=A - self.assertRaises(ValueError, ModelFormMetaclass, 'Form', (ModelForm,), {'Meta': Meta}) + self.assertRaises(ValueError, ModelFormMetaclass, b'Form', (ModelForm,), {'Meta': Meta}) class B(models.Model): pass @@ -195,4 +195,4 @@ class RelatedModelFormTests(TestCase): class Meta: model=A - self.assertTrue(issubclass(ModelFormMetaclass('Form', (ModelForm,), {'Meta': Meta}), ModelForm)) + self.assertTrue(issubclass(ModelFormMetaclass(b'Form', (ModelForm,), {'Meta': Meta}), ModelForm)) diff --git a/tests/regressiontests/forms/tests/regressions.py b/tests/regressiontests/forms/tests/regressions.py index 267ef300e6..20c11f99a8 100644 --- a/tests/regressiontests/forms/tests/regressions.py +++ b/tests/regressiontests/forms/tests/regressions.py @@ -54,10 +54,11 @@ class FormsRegressionsTestCase(TestCase): # Testing choice validation with UTF-8 bytestrings as input (these are the # Russian abbreviations "мес." and "шт.". - UNITS = (('\xd0\xbc\xd0\xb5\xd1\x81.', '\xd0\xbc\xd0\xb5\xd1\x81.'), ('\xd1\x88\xd1\x82.', '\xd1\x88\xd1\x82.')) + UNITS = ((b'\xd0\xbc\xd0\xb5\xd1\x81.', b'\xd0\xbc\xd0\xb5\xd1\x81.'), + (b'\xd1\x88\xd1\x82.', b'\xd1\x88\xd1\x82.')) f = ChoiceField(choices=UNITS) self.assertEqual(f.clean(u'\u0448\u0442.'), u'\u0448\u0442.') - self.assertEqual(f.clean('\xd1\x88\xd1\x82.'), u'\u0448\u0442.') + self.assertEqual(f.clean(b'\xd1\x88\xd1\x82.'), u'\u0448\u0442.') # Translated error messages used to be buggy. with override('ru'): diff --git a/tests/regressiontests/forms/tests/widgets.py b/tests/regressiontests/forms/tests/widgets.py index 2499b7a350..8630b45666 100644 --- a/tests/regressiontests/forms/tests/widgets.py +++ b/tests/regressiontests/forms/tests/widgets.py @@ -1182,7 +1182,7 @@ class ClearableFileInputTests(TestCase): """ widget = ClearableFileInput() widget.is_required = True - f = SimpleUploadedFile('something.txt', 'content') + f = SimpleUploadedFile('something.txt', b'content') self.assertEqual(widget.value_from_datadict( data={'myfile-clear': True}, files={'myfile': f}, diff --git a/tests/regressiontests/handlers/tests.py b/tests/regressiontests/handlers/tests.py index 59d3d84528..ae2062c756 100644 --- a/tests/regressiontests/handlers/tests.py +++ b/tests/regressiontests/handlers/tests.py @@ -28,7 +28,7 @@ class HandlerTests(unittest.TestCase): def test_bad_path_info(self): """Tests for bug #15672 ('request' referenced before assignment)""" environ = RequestFactory().get('/').environ - environ['PATH_INFO'] = '\xed' + environ['PATH_INFO'] = b'\xed' handler = WSGIHandler() response = handler(environ, lambda *a, **k: None) self.assertEqual(response.status_code, 400) diff --git a/tests/regressiontests/httpwrappers/tests.py b/tests/regressiontests/httpwrappers/tests.py index 6dd2128afd..218c5b5b3b 100644 --- a/tests/regressiontests/httpwrappers/tests.py +++ b/tests/regressiontests/httpwrappers/tests.py @@ -174,7 +174,7 @@ class QueryDictTests(unittest.TestCase): QueryDicts must be able to handle invalid input encoding (in this case, bad UTF-8 encoding). """ - q = QueryDict('foo=bar&foo=\xff') + q = QueryDict(b'foo=bar&foo=\xff') self.assertEqual(q['foo'], u'\ufffd') self.assertEqual(q.getlist('foo'), [u'bar', u'\ufffd']) @@ -198,7 +198,7 @@ class QueryDictTests(unittest.TestCase): def test_non_default_encoding(self): """#13572 - QueryDict with a non-default encoding""" - q = QueryDict('sbb=one', encoding='rot_13') + q = QueryDict(b'sbb=one', encoding='rot_13') self.assertEqual(q.encoding , 'rot_13' ) self.assertEqual(q.items() , [(u'foo', u'bar')] ) self.assertEqual(q.urlencode() , 'sbb=one' ) @@ -285,8 +285,8 @@ class HttpResponseTests(unittest.TestCase): except StopIteration: break #'\xde\x9e' == unichr(1950).encode('utf-8') - self.assertEqual(result, ['1', '2', '3', '\xde\x9e']) - self.assertEqual(r.content, '123\xde\x9e') + self.assertEqual(result, ['1', '2', '3', b'\xde\x9e']) + self.assertEqual(r.content, b'123\xde\x9e') #with Content-Encoding header r = HttpResponse([1,1,2,4,8]) @@ -321,7 +321,7 @@ class CookieTests(unittest.TestCase): Test that we haven't broken normal encoding """ c = SimpleCookie() - c['test'] = "\xf0" + c['test'] = b"\xf0" c2 = SimpleCookie() c2.load(c.output()) self.assertEqual(c['test'].value, c2['test'].value) diff --git a/tests/regressiontests/i18n/tests.py b/tests/regressiontests/i18n/tests.py index faed4e55c7..5e95ee36ec 100644 --- a/tests/regressiontests/i18n/tests.py +++ b/tests/regressiontests/i18n/tests.py @@ -230,7 +230,7 @@ class TranslationTests(TestCase): """ Translating a string requiring no auto-escaping shouldn't change the "safe" status. """ - s = mark_safe('Password') + s = mark_safe(b'Password') self.assertEqual(SafeString, type(s)) with translation.override('de', deactivate=True): self.assertEqual(SafeUnicode, type(ugettext(s))) diff --git a/tests/regressiontests/localflavor/mk/tests.py b/tests/regressiontests/localflavor/mk/tests.py index f78dbdd440..3a8add6e34 100644 --- a/tests/regressiontests/localflavor/mk/tests.py +++ b/tests/regressiontests/localflavor/mk/tests.py @@ -92,7 +92,7 @@ class MKLocalFlavorTests(SimpleTestCase): """ Test that the empty option is there. """ - municipality_select_html = """\ + municipality_select_html = b"""\