Browse Source

Removed default mode='r' argument from calls to open().

Jon Dufresne 6 năm trước cách đây
mục cha
commit
7e3bf2662b

+ 1 - 1
django/contrib/sessions/backends/file.py

@@ -75,7 +75,7 @@ class SessionStore(SessionBase):
     def load(self):
         session_data = {}
         try:
-            with open(self._key_to_file(), "r", encoding="ascii") as session_file:
+            with open(self._key_to_file(), encoding='ascii') as session_file:
                 file_data = session_file.read()
             # Don't fail if there is no data in the session file.
             # We may have opened the empty placeholder file.

+ 3 - 3
django/core/management/commands/makemessages.py

@@ -104,7 +104,7 @@ class BuildFile:
             return
 
         encoding = settings.FILE_CHARSET if self.command.settings_available else 'utf-8'
-        with open(self.path, 'r', encoding=encoding) as fp:
+        with open(self.path, encoding=encoding) as fp:
             src_data = fp.read()
 
         if self.domain == 'djangojs':
@@ -635,7 +635,7 @@ class Command(BaseCommand):
                 elif self.verbosity > 0:
                     self.stdout.write(errors)
         else:
-            with open(potfile, 'r', encoding='utf-8') as fp:
+            with open(potfile, encoding='utf-8') as fp:
                 msgs = fp.read()
             if not self.invoked_for_django:
                 msgs = self.copy_plural_forms(msgs, locale)
@@ -669,7 +669,7 @@ class Command(BaseCommand):
         for domain in domains:
             django_po = os.path.join(django_dir, 'conf', 'locale', locale, 'LC_MESSAGES', '%s.po' % domain)
             if os.path.exists(django_po):
-                with open(django_po, 'r', encoding='utf-8') as fp:
+                with open(django_po, encoding='utf-8') as fp:
                     m = plural_forms_re.search(fp.read())
                 if m:
                     plural_form_line = m.group('value')

+ 1 - 1
django/core/management/templates.py

@@ -148,7 +148,7 @@ class TemplateCommand(BaseCommand):
                 # Only render the Python files, as we don't want to
                 # accidentally render Django templates files
                 if new_path.endswith(extensions) or filename in extra_files:
-                    with open(old_path, 'r', encoding='utf-8') as template_file:
+                    with open(old_path, encoding='utf-8') as template_file:
                         content = template_file.read()
                     template = Engine().from_string(content)
                     content = template.render(context)

+ 1 - 1
django/db/models/fields/files.py

@@ -141,7 +141,7 @@ class FileDescriptor:
 
     Assign a file object on assignment so you can do::
 
-        >>> with open('/path/to/hello.world', 'r') as f:
+        >>> with open('/path/to/hello.world') as f:
         ...     instance.file = File(f)
     """
     def __init__(self, field):

+ 5 - 5
tests/admin_scripts/tests.py

@@ -173,7 +173,7 @@ class AdminScriptTestCase(SimpleTestCase):
         test_manage_py = os.path.join(self.test_dir, 'manage.py')
         shutil.copyfile(template_manage_py, test_manage_py)
 
-        with open(test_manage_py, 'r') as fp:
+        with open(test_manage_py) as fp:
             manage_py_contents = fp.read()
         manage_py_contents = manage_py_contents.replace(
             "{{ project_name }}", "test_project")
@@ -607,7 +607,7 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase):
         self.addCleanup(shutil.rmtree, app_path)
         self.assertNoOutput(err)
         self.assertTrue(os.path.exists(app_path))
-        with open(os.path.join(app_path, 'apps.py'), 'r') as f:
+        with open(os.path.join(app_path, 'apps.py')) as f:
             content = f.read()
             self.assertIn("class SettingsTestConfig(AppConfig)", content)
             self.assertIn("name = 'settings_test'", content)
@@ -631,7 +631,7 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase):
         self.addCleanup(shutil.rmtree, app_path)
         self.assertNoOutput(err)
         self.assertTrue(os.path.exists(app_path))
-        with open(os.path.join(app_path, 'apps.py'), 'r', encoding='utf8') as f:
+        with open(os.path.join(app_path, 'apps.py'), encoding='utf8') as f:
             content = f.read()
             self.assertIn("class こんにちはConfig(AppConfig)", content)
             self.assertIn("name = 'こんにちは'", content)
@@ -2124,7 +2124,7 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
         out, err = self.run_django_admin(args)
         self.assertNoOutput(err)
         test_manage_py = os.path.join(testproject_dir, 'manage.py')
-        with open(test_manage_py, 'r') as fp:
+        with open(test_manage_py) as fp:
             content = fp.read()
             self.assertIn("project_name = 'another_project'", content)
             self.assertIn("project_directory = '%s'" % testproject_dir, content)
@@ -2146,7 +2146,7 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
         out, err = self.run_manage(args)
         self.assertNoOutput(err)
         test_manage_py = os.path.join(testproject_dir, 'additional_dir', 'extra.py')
-        with open(test_manage_py, 'r') as fp:
+        with open(test_manage_py) as fp:
             content = fp.read()
             self.assertIn("<&>", content)
 

+ 1 - 1
tests/dbshell/test_postgresql_psycopg2.py

@@ -18,7 +18,7 @@ class PostgreSqlDbshellCommandTestCase(SimpleTestCase):
         def _mock_subprocess_call(*args):
             self.subprocess_args = list(*args)
             if 'PGPASSFILE' in os.environ:
-                with open(os.environ['PGPASSFILE'], 'r') as f:
+                with open(os.environ['PGPASSFILE']) as f:
                     self.pgpass = f.read().strip()  # ignore line endings
             else:
                 self.pgpass = None

+ 3 - 3
tests/fixtures/tests.py

@@ -67,7 +67,7 @@ class DumpDataAssertMixin:
             primary_keys=primary_keys,
         )
         if filename:
-            with open(filename, "r") as f:
+            with open(filename) as f:
                 command_output = f.read()
             os.remove(filename)
         else:
@@ -699,7 +699,7 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
         fixture_json = os.path.join(tests_dir, 'fixtures', 'fixture1.json')
         fixture_xml = os.path.join(tests_dir, 'fixtures', 'fixture3.xml')
 
-        with mock.patch('django.core.management.commands.loaddata.sys.stdin', open(fixture_json, 'r')):
+        with mock.patch('django.core.management.commands.loaddata.sys.stdin', open(fixture_json)):
             management.call_command('loaddata', '--format=json', '-', verbosity=0)
             self.assertEqual(Article.objects.count(), 2)
             self.assertQuerysetEqual(Article.objects.all(), [
@@ -707,7 +707,7 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
                 '<Article: Poker has no place on ESPN>',
             ])
 
-        with mock.patch('django.core.management.commands.loaddata.sys.stdin', open(fixture_xml, 'r')):
+        with mock.patch('django.core.management.commands.loaddata.sys.stdin', open(fixture_xml)):
             management.call_command('loaddata', '--format=xml', '-', verbosity=0)
             self.assertEqual(Article.objects.count(), 3)
             self.assertQuerysetEqual(Article.objects.all(), [

+ 20 - 20
tests/i18n/test_extraction.py

@@ -42,7 +42,7 @@ class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
         management.call_command('makemessages', locale=[LOCALE], verbosity=2, stdout=out, **options)
         output = out.getvalue()
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r') as fp:
+        with open(self.PO_FILE) as fp:
             po_contents = fp.read()
         return output, po_contents
 
@@ -59,7 +59,7 @@ class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
         return self.assertTrue(not re.search('^msgid %s' % msgid, s, re.MULTILINE))
 
     def _assertPoLocComment(self, assert_presence, po_filename, line_number, *comment_parts):
-        with open(po_filename, 'r') as fp:
+        with open(po_filename) as fp:
             po_contents = fp.read()
         if os.name == 'nt':
             # #: .\path\to\file.html:123
@@ -136,7 +136,7 @@ class BasicExtractorTests(ExtractorTests):
         """
         management.call_command('makemessages', locale=[LOCALE], verbosity=0)
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r', encoding='utf-8') as fp:
+        with open(self.PO_FILE, encoding='utf-8') as fp:
             po_contents = fp.read()
             # Check two random strings
             self.assertIn('#. Translators: One-line translator comment #1', po_contents)
@@ -145,7 +145,7 @@ class BasicExtractorTests(ExtractorTests):
     def test_comments_extractor(self):
         management.call_command('makemessages', locale=[LOCALE], verbosity=0)
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r', encoding='utf-8') as fp:
+        with open(self.PO_FILE, encoding='utf-8') as fp:
             po_contents = fp.read()
             self.assertNotIn('This comment should not be extracted', po_contents)
 
@@ -178,14 +178,14 @@ class BasicExtractorTests(ExtractorTests):
     def test_special_char_extracted(self):
         management.call_command('makemessages', locale=[LOCALE], verbosity=0)
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r', encoding='utf-8') as fp:
+        with open(self.PO_FILE, encoding='utf-8') as fp:
             po_contents = fp.read()
             self.assertMsgId("Non-breaking space\u00a0:", po_contents)
 
     def test_blocktrans_trimmed(self):
         management.call_command('makemessages', locale=[LOCALE], verbosity=0)
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r') as fp:
+        with open(self.PO_FILE) as fp:
             po_contents = fp.read()
             # should not be trimmed
             self.assertNotMsgId('Text with a few line breaks.', po_contents)
@@ -229,7 +229,7 @@ class BasicExtractorTests(ExtractorTests):
         """
         management.call_command('makemessages', locale=[LOCALE], verbosity=0)
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r') as fp:
+        with open(self.PO_FILE) as fp:
             po_contents = fp.read()
             # {% trans %}
             self.assertIn('msgctxt "Special trans context #1"', po_contents)
@@ -259,7 +259,7 @@ class BasicExtractorTests(ExtractorTests):
     def test_context_in_single_quotes(self):
         management.call_command('makemessages', locale=[LOCALE], verbosity=0)
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r') as fp:
+        with open(self.PO_FILE) as fp:
             po_contents = fp.read()
             # {% trans %}
             self.assertIn('msgctxt "Context wrapped in double quotes"', po_contents)
@@ -299,7 +299,7 @@ class BasicExtractorTests(ExtractorTests):
             )
         # Now test .po file contents
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r') as fp:
+        with open(self.PO_FILE) as fp:
             po_contents = fp.read()
 
             self.assertMsgId('Translatable literal #9a', po_contents)
@@ -391,7 +391,7 @@ class BasicExtractorTests(ExtractorTests):
         shutil.copyfile(BR_PO_BASE + '.pristine', BR_PO_BASE + '.po')
         management.call_command('makemessages', locale=['pt_BR'], verbosity=0)
         self.assertTrue(os.path.exists(BR_PO_BASE + '.po'))
-        with open(BR_PO_BASE + '.po', 'r', encoding='utf-8') as fp:
+        with open(BR_PO_BASE + '.po', encoding='utf-8') as fp:
             po_contents = fp.read()
             self.assertMsgStr("Größe", po_contents)
 
@@ -410,7 +410,7 @@ class BasicExtractorTests(ExtractorTests):
         with tempfile.NamedTemporaryFile() as pot_file:
             pot_filename = pot_file.name
         write_pot_file(pot_filename, msgs)
-        with open(pot_filename, 'r', encoding='utf-8') as fp:
+        with open(pot_filename, encoding='utf-8') as fp:
             pot_contents = fp.read()
             self.assertIn('Content-Type: text/plain; charset=UTF-8', pot_contents)
             self.assertIn('mañana; charset=CHARSET', pot_contents)
@@ -506,7 +506,7 @@ class SymlinkExtractorTests(ExtractorTests):
         os.chdir(self.test_dir)
         management.call_command('makemessages', locale=[LOCALE], verbosity=0, symlinks=True)
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r') as fp:
+        with open(self.PO_FILE) as fp:
             po_contents = fp.read()
             self.assertMsgId('This literal should be included.', po_contents)
         self.assertLocationCommentPresent(self.PO_FILE, None, 'templates_symlinked', 'test.html')
@@ -519,7 +519,7 @@ class CopyPluralFormsExtractorTests(ExtractorTests):
     def test_copy_plural_forms(self):
         management.call_command('makemessages', locale=[LOCALE], verbosity=0)
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r') as fp:
+        with open(self.PO_FILE) as fp:
             po_contents = fp.read()
             self.assertIn('Plural-Forms: nplurals=2; plural=(n != 1)', po_contents)
 
@@ -527,7 +527,7 @@ class CopyPluralFormsExtractorTests(ExtractorTests):
         """Ticket #20311."""
         management.call_command('makemessages', locale=['es'], extensions=['djtpl'], verbosity=0)
         self.assertTrue(os.path.exists(self.PO_FILE_ES))
-        with open(self.PO_FILE_ES, 'r', encoding='utf-8') as fp:
+        with open(self.PO_FILE_ES, encoding='utf-8') as fp:
             po_contents = fp.read()
             found = re.findall(r'^(?P<value>"Plural-Forms.+?\\n")\s*$', po_contents, re.MULTILINE | re.DOTALL)
             self.assertEqual(1, len(found))
@@ -540,7 +540,7 @@ class CopyPluralFormsExtractorTests(ExtractorTests):
         """
         management.call_command('makemessages', locale=[LOCALE], extensions=['html', 'djtpl'], verbosity=0)
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r') as fp:
+        with open(self.PO_FILE) as fp:
             po_contents = fp.read()
             self.assertNotIn("#-#-#-#-#  django.pot (PACKAGE VERSION)  #-#-#-#-#\\n", po_contents)
             self.assertMsgId('First `trans`, then `blocktrans` with a plural', po_contents)
@@ -552,7 +552,7 @@ class NoWrapExtractorTests(ExtractorTests):
     def test_no_wrap_enabled(self):
         management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_wrap=True)
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r') as fp:
+        with open(self.PO_FILE) as fp:
             po_contents = fp.read()
             self.assertMsgId(
                 'This literal should also be included wrapped or not wrapped '
@@ -563,7 +563,7 @@ class NoWrapExtractorTests(ExtractorTests):
     def test_no_wrap_disabled(self):
         management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_wrap=False)
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r') as fp:
+        with open(self.PO_FILE) as fp:
             po_contents = fp.read()
             self.assertMsgId(
                 '""\n"This literal should also be included wrapped or not '
@@ -595,7 +595,7 @@ class LocationCommentsTests(ExtractorTests):
         """
         management.call_command('makemessages', locale=[LOCALE], verbosity=0)
         self.assertTrue(os.path.exists(self.PO_FILE))
-        with open(self.PO_FILE, 'r') as fp:
+        with open(self.PO_FILE) as fp:
             po_contents = fp.read()
         self.assertMsgId('#: templates/test.html.py', po_contents)
         self.assertLocationCommentNotPresent(self.PO_FILE, None, '.html.py')
@@ -753,11 +753,11 @@ class CustomLayoutExtractionTests(ExtractorTests):
             self.assertTrue(os.path.exists(project_de_locale))
             self.assertTrue(os.path.exists(app_de_locale))
 
-            with open(project_de_locale, 'r') as fp:
+            with open(project_de_locale) as fp:
                 po_contents = fp.read()
                 self.assertMsgId('This app has no locale directory', po_contents)
                 self.assertMsgId('This is a project-level string', po_contents)
-            with open(app_de_locale, 'r') as fp:
+            with open(app_de_locale) as fp:
                 po_contents = fp.read()
                 self.assertMsgId('This app has a locale directory', po_contents)
 

+ 1 - 1
tests/i18n/test_percents.py

@@ -38,7 +38,7 @@ class ExtractingStringsWithPercentSigns(POFileAssertionMixin, FrenchTestCase):
 
     def setUp(self):
         super().setUp()
-        with open(self.PO_FILE, 'r') as fp:
+        with open(self.PO_FILE) as fp:
             self.po_contents = fp.read()
 
     def test_trans_tag_with_percent_symbol_at_the_end(self):

+ 6 - 6
tests/migrations/test_commands.py

@@ -771,7 +771,7 @@ class MakeMigrationsTests(MigrationTestBase):
             init_file = os.path.join(migration_dir, "__init__.py")
             self.assertTrue(os.path.exists(init_file))
 
-            with open(init_file, 'r') as fp:
+            with open(init_file) as fp:
                 content = fp.read()
             self.assertEqual(content, '')
 
@@ -779,7 +779,7 @@ class MakeMigrationsTests(MigrationTestBase):
             initial_file = os.path.join(migration_dir, "0001_initial.py")
             self.assertTrue(os.path.exists(initial_file))
 
-            with open(initial_file, 'r', encoding='utf-8') as fp:
+            with open(initial_file, encoding='utf-8') as fp:
                 content = fp.read()
                 self.assertIn('migrations.CreateModel', content)
                 self.assertIn('initial = True', content)
@@ -924,7 +924,7 @@ class MakeMigrationsTests(MigrationTestBase):
             initial_file = os.path.join(migration_dir, "0001_initial.py")
             self.assertTrue(os.path.exists(initial_file))
 
-            with open(initial_file, 'r', encoding='utf-8') as fp:
+            with open(initial_file, encoding='utf-8') as fp:
                 content = fp.read()
 
                 # Remove all whitespace to check for empty dependencies and operations
@@ -1335,7 +1335,7 @@ class MakeMigrationsTests(MigrationTestBase):
                 migration_file = os.path.join(migration_dir, "%s_%s.py" % (migration_count, migration_name))
                 # Check for existing migration file in migration folder
                 self.assertTrue(os.path.exists(migration_file))
-                with open(migration_file, "r", encoding="utf-8") as fp:
+                with open(migration_file, encoding='utf-8') as fp:
                     content = fp.read()
                     content = content.replace(" ", "")
                 return content
@@ -1455,7 +1455,7 @@ class SquashMigrationsTests(MigrationTestBase):
             call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=0)
 
             squashed_migration_file = os.path.join(migration_dir, "0001_squashed_0002_second.py")
-            with open(squashed_migration_file, "r", encoding="utf-8") as fp:
+            with open(squashed_migration_file, encoding='utf-8') as fp:
                 content = fp.read()
                 self.assertIn("initial = True", content)
 
@@ -1488,7 +1488,7 @@ class SquashMigrationsTests(MigrationTestBase):
                          interactive=False, verbosity=1, stdout=out)
 
             squashed_migration_file = os.path.join(migration_dir, "0002_second_squashed_0003_third.py")
-            with open(squashed_migration_file, "r", encoding="utf-8") as fp:
+            with open(squashed_migration_file, encoding='utf-8') as fp:
                 content = fp.read()
                 self.assertIn("        ('migrations', '0001_initial')", content)
                 self.assertNotIn("initial = True", content)

+ 1 - 1
tests/utils_tests/test_html.py

@@ -99,7 +99,7 @@ class TestUtilsHtml(SimpleTestCase):
         for filename in ('strip_tags1.html', 'strip_tags2.txt'):
             with self.subTest(filename=filename):
                 path = os.path.join(os.path.dirname(__file__), 'files', filename)
-                with open(path, 'r') as fp:
+                with open(path) as fp:
                     content = fp.read()
                     start = datetime.now()
                     stripped = strip_tags(content)