From 38408f8007eae21b9f1cbbcc7f86d4b2042ff86a Mon Sep 17 00:00:00 2001 From: Claude Paroz Date: Sat, 19 May 2012 17:43:34 +0200 Subject: Marked bytestrings with b prefix. Refs #18269 This is a preparation for unicode literals general usage in Django (Python 3 compatibility). --- 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 +- tests/regressiontests/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 ++++----- tests/regressiontests/model_forms_regress/tests.py | 6 +- tests/regressiontests/requests/tests.py | 88 +++++++++++----------- tests/regressiontests/signing/tests.py | 6 +- tests/regressiontests/staticfiles_tests/tests.py | 52 ++++++------- tests/regressiontests/string_lookup/tests.py | 2 +- tests/regressiontests/templates/tests.py | 14 ++-- tests/regressiontests/templates/unicode.py | 12 +-- .../regressiontests/test_client_regress/models.py | 72 +++++++++--------- tests/regressiontests/views/__init__.py | 6 +- 28 files changed, 241 insertions(+), 240 deletions(-) (limited to 'tests') 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"""\