diff options
| author | Claude Paroz <claude@2xlibre.net> | 2012-05-05 14:01:38 +0200 |
|---|---|---|
| committer | Claude Paroz <claude@2xlibre.net> | 2012-05-05 14:06:36 +0200 |
| commit | 865cd35c9b357e20994f6c6a51f2ae000ba0a3ee (patch) | |
| tree | 9db42053673c856a2527d5573d7f8fd682334182 /tests | |
| parent | ec5423df05dedeee6651c36dd4d90fec0d8cca7c (diff) | |
Made more extensive usage of context managers with open.
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/modeltests/model_forms/tests.py | 6 | ||||
| -rw-r--r-- | tests/regressiontests/admin_scripts/tests.py | 53 | ||||
| -rw-r--r-- | tests/regressiontests/bug639/tests.py | 3 | ||||
| -rw-r--r-- | tests/regressiontests/file_uploads/tests.py | 58 | ||||
| -rw-r--r-- | tests/regressiontests/mail/tests.py | 6 | ||||
| -rw-r--r-- | tests/regressiontests/views/tests/static.py | 19 | ||||
| -rwxr-xr-x | tests/runtests.py | 1 |
7 files changed, 76 insertions, 70 deletions
diff --git a/tests/modeltests/model_forms/tests.py b/tests/modeltests/model_forms/tests.py index fe20d79a29..47902f3a83 100644 --- a/tests/modeltests/model_forms/tests.py +++ b/tests/modeltests/model_forms/tests.py @@ -1242,8 +1242,10 @@ class OldFormForXTests(TestCase): # it comes to validation. This specifically tests that #6302 is fixed for # both file fields and image fields. - image_data = open(os.path.join(os.path.dirname(__file__), "test.png"), 'rb').read() - image_data2 = open(os.path.join(os.path.dirname(__file__), "test2.png"), 'rb').read() + with open(os.path.join(os.path.dirname(__file__), "test.png"), 'rb') as fp: + image_data = fp.read() + with open(os.path.join(os.path.dirname(__file__), "test2.png"), 'rb') as fp: + image_data2 = fp.read() f = ImageFileForm( data={'description': u'An image'}, diff --git a/tests/regressiontests/admin_scripts/tests.py b/tests/regressiontests/admin_scripts/tests.py index 4c4edbbb71..98492ffbdd 100644 --- a/tests/regressiontests/admin_scripts/tests.py +++ b/tests/regressiontests/admin_scripts/tests.py @@ -27,32 +27,32 @@ class AdminScriptTestCase(unittest.TestCase): if is_dir: settings_dir = os.path.join(test_dir, filename) os.mkdir(settings_dir) - settings_file = open(os.path.join(settings_dir, '__init__.py'), 'w') + settings_file_path = os.path.join(settings_dir, '__init__.py') else: - settings_file = open(os.path.join(test_dir, filename), 'w') - settings_file.write('# Settings file automatically generated by regressiontests.admin_scripts test case\n') - exports = [ - 'DATABASES', - 'ROOT_URLCONF', - 'SECRET_KEY', - ] - for s in exports: - if hasattr(settings, s): - o = getattr(settings, s) - if not isinstance(o, dict): - o = "'%s'" % o - settings_file.write("%s = %s\n" % (s, o)) + settings_file_path = os.path.join(test_dir, filename) - if apps is None: - apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'regressiontests.admin_scripts'] + with open(settings_file_path, 'w') as settings_file: + settings_file.write('# Settings file automatically generated by regressiontests.admin_scripts test case\n') + exports = [ + 'DATABASES', + 'ROOT_URLCONF', + 'SECRET_KEY', + ] + for s in exports: + if hasattr(settings, s): + o = getattr(settings, s) + if not isinstance(o, dict): + o = "'%s'" % o + settings_file.write("%s = %s\n" % (s, o)) - settings_file.write("INSTALLED_APPS = %s\n" % apps) + if apps is None: + apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'regressiontests.admin_scripts'] - if sdict: - for k, v in sdict.items(): - settings_file.write("%s = %s\n" % (k, v)) + settings_file.write("INSTALLED_APPS = %s\n" % apps) - settings_file.close() + if sdict: + for k, v in sdict.items(): + settings_file.write("%s = %s\n" % (k, v)) def remove_settings(self, filename, is_dir=False): full_name = os.path.join(test_dir, filename) @@ -989,13 +989,12 @@ class ManageSettingsWithImportError(AdminScriptTestCase): if is_dir: settings_dir = os.path.join(test_dir, filename) os.mkdir(settings_dir) - settings_file = open(os.path.join(settings_dir, '__init__.py'), 'w') + settings_file_path = os.path.join(settings_dir, '__init__.py') else: - settings_file = open(os.path.join(test_dir, filename), 'w') - settings_file.write('# Settings file automatically generated by regressiontests.admin_scripts test case\n') - settings_file.write('# The next line will cause an import error:\nimport foo42bar\n') - - settings_file.close() + settings_file_path = os.path.join(test_dir, filename) + with open(settings_file_path, 'w') as settings_file: + settings_file.write('# Settings file automatically generated by regressiontests.admin_scripts test case\n') + settings_file.write('# The next line will cause an import error:\nimport foo42bar\n') def test_builtin_command(self): "import error: manage.py builtin commands shows useful diagnostic info when settings with import errors is provided" diff --git a/tests/regressiontests/bug639/tests.py b/tests/regressiontests/bug639/tests.py index 9d30517520..b7547696d4 100644 --- a/tests/regressiontests/bug639/tests.py +++ b/tests/regressiontests/bug639/tests.py @@ -24,7 +24,8 @@ class Bug639Test(unittest.TestCase): """ # Grab an image for testing. filename = os.path.join(os.path.dirname(__file__), "test.jpg") - img = open(filename, "rb").read() + with open(filename, "rb") as fp: + img = fp.read() # Fake a POST QueryDict and FILES MultiValueDict. data = {'title': 'Testing'} diff --git a/tests/regressiontests/file_uploads/tests.py b/tests/regressiontests/file_uploads/tests.py index b9ce3c2753..de552d88ec 100644 --- a/tests/regressiontests/file_uploads/tests.py +++ b/tests/regressiontests/file_uploads/tests.py @@ -24,11 +24,12 @@ UNICODE_FILENAME = u'test-0123456789_中文_Orléans.jpg' class FileUploadTests(TestCase): def test_simple_upload(self): - post_data = { - 'name': 'Ringo', - 'file_field': open(__file__), - } - response = self.client.post('/file_uploads/upload/', post_data) + with open(__file__) as fp: + post_data = { + 'name': 'Ringo', + 'file_field': fp, + } + response = self.client.post('/file_uploads/upload/', post_data) self.assertEqual(response.status_code, 200) def test_large_upload(self): @@ -87,17 +88,16 @@ class FileUploadTests(TestCase): tdir = tempfile.gettempdir() # This file contains chinese symbols and an accented char in the name. - file1 = open(os.path.join(tdir, UNICODE_FILENAME.encode('utf-8')), 'w+b') - file1.write('b' * (2 ** 10)) - file1.seek(0) + with open(os.path.join(tdir, UNICODE_FILENAME.encode('utf-8')), 'w+b') as file1: + file1.write('b' * (2 ** 10)) + file1.seek(0) - post_data = { - 'file_unicode': file1, - } + post_data = { + 'file_unicode': file1, + } - response = self.client.post('/file_uploads/unicode_name/', post_data) + response = self.client.post('/file_uploads/unicode_name/', post_data) - file1.close() try: os.unlink(file1.name) except: @@ -294,10 +294,6 @@ class FileUploadTests(TestCase): p = request.POST return ret - post_data = { - 'name': 'Ringo', - 'file_field': open(__file__), - } # Maybe this is a little more complicated that it needs to be; but if # the django.test.client.FakePayload.read() implementation changes then # this test would fail. So we need to know exactly what kind of error @@ -310,16 +306,21 @@ class FileUploadTests(TestCase): # install the custom handler that tries to access request.POST self.client.handler = POSTAccessingHandler() - try: - response = self.client.post('/file_uploads/upload_errors/', post_data) - except reference_error.__class__ as err: - self.assertFalse( - str(err) == str(reference_error), - "Caught a repeated exception that'll cause an infinite loop in file uploads." - ) - except Exception as err: - # CustomUploadError is the error that should have been raised - self.assertEqual(err.__class__, uploadhandler.CustomUploadError) + with open(__file__) as fp: + post_data = { + 'name': 'Ringo', + 'file_field': fp, + } + try: + response = self.client.post('/file_uploads/upload_errors/', post_data) + except reference_error.__class__ as err: + self.assertFalse( + str(err) == str(reference_error), + "Caught a repeated exception that'll cause an infinite loop in file uploads." + ) + except Exception as err: + # CustomUploadError is the error that should have been raised + self.assertEqual(err.__class__, uploadhandler.CustomUploadError) def test_filename_case_preservation(self): """ @@ -382,8 +383,7 @@ 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 - fd = open(UPLOAD_TO, 'w') - fd.close() + open(UPLOAD_TO, 'w').close() try: self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x')) except IOError as err: diff --git a/tests/regressiontests/mail/tests.py b/tests/regressiontests/mail/tests.py index ed85918f17..a4cefd8322 100644 --- a/tests/regressiontests/mail/tests.py +++ b/tests/regressiontests/mail/tests.py @@ -517,7 +517,8 @@ class FileBackendTests(BaseEmailBackendTests, TestCase): def get_mailbox_content(self): messages = [] for filename in os.listdir(self.tmp_dir): - session = open(os.path.join(self.tmp_dir, filename)).read().split('\n' + ('-' * 79) + '\n') + with open(os.path.join(self.tmp_dir, filename)) as fp: + session = fp.read().split('\n' + ('-' * 79) + '\n') messages.extend(email.message_from_string(m) for m in session if m) return messages @@ -528,7 +529,8 @@ class FileBackendTests(BaseEmailBackendTests, TestCase): connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 1) - message = email.message_from_file(open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0]))) + with open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0])) as fp: + message = email.message_from_file(fp) self.assertEqual(message.get_content_type(), 'text/plain') self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), 'from@example.com') diff --git a/tests/regressiontests/views/tests/static.py b/tests/regressiontests/views/tests/static.py index 3088a86eab..6cabf6453c 100644 --- a/tests/regressiontests/views/tests/static.py +++ b/tests/regressiontests/views/tests/static.py @@ -29,7 +29,8 @@ class StaticTests(TestCase): for filename in media_files: response = self.client.get('/views/%s/%s' % (self.prefix, filename)) file_path = path.join(media_dir, filename) - self.assertEqual(open(file_path).read(), response.content) + with open(file_path) as fp: + self.assertEqual(fp.read(), response.content) self.assertEqual(len(response.content), int(response['Content-Length'])) self.assertEqual(mimetypes.guess_type(file_path)[1], response.get('Content-Encoding', None)) @@ -40,15 +41,15 @@ class StaticTests(TestCase): def test_copes_with_empty_path_component(self): file_name = 'file.txt' response = self.client.get('/views/%s//%s' % (self.prefix, file_name)) - file = open(path.join(media_dir, file_name)) - self.assertEqual(file.read(), response.content) + with open(path.join(media_dir, file_name)) as fp: + self.assertEqual(fp.read(), response.content) def test_is_modified_since(self): file_name = 'file.txt' response = self.client.get('/views/%s/%s' % (self.prefix, file_name), HTTP_IF_MODIFIED_SINCE='Thu, 1 Jan 1970 00:00:00 GMT') - file = open(path.join(media_dir, file_name)) - self.assertEqual(file.read(), response.content) + with open(path.join(media_dir, file_name)) as fp: + self.assertEqual(fp.read(), response.content) def test_not_modified_since(self): file_name = 'file.txt' @@ -70,8 +71,8 @@ class StaticTests(TestCase): invalid_date = 'Mon, 28 May 999999999999 28:25:26 GMT' response = self.client.get('/views/%s/%s' % (self.prefix, file_name), HTTP_IF_MODIFIED_SINCE=invalid_date) - file = open(path.join(media_dir, file_name)) - self.assertEqual(file.read(), response.content) + with open(path.join(media_dir, file_name)) as fp: + self.assertEqual(fp.read(), response.content) self.assertEqual(len(response.content), int(response['Content-Length'])) @@ -85,8 +86,8 @@ class StaticTests(TestCase): invalid_date = ': 1291108438, Wed, 20 Oct 2010 14:05:00 GMT' response = self.client.get('/views/%s/%s' % (self.prefix, file_name), HTTP_IF_MODIFIED_SINCE=invalid_date) - file = open(path.join(media_dir, file_name)) - self.assertEqual(file.read(), response.content) + with open(path.join(media_dir, file_name)) as fp: + self.assertEqual(fp.read(), response.content) self.assertEqual(len(response.content), int(response['Content-Length'])) diff --git a/tests/runtests.py b/tests/runtests.py index f1edc5d8ba..50744122e9 100755 --- a/tests/runtests.py +++ b/tests/runtests.py @@ -61,6 +61,7 @@ def get_test_modules(): for f in os.listdir(dirpath): if (f.startswith('__init__') or f.startswith('.') or + f == '__pycache__' or f.startswith('sql') or os.path.basename(f) in REGRESSION_SUBDIRS_TO_SKIP): continue |
