Browse Source

Refs #27777 -- Improved docs/added test for File context manager change.

Ingo Klöcker 8 years ago
parent
commit
6bb3b2bff4
3 changed files with 18 additions and 3 deletions
  1. 5 2
      docs/ref/files/file.txt
  2. 2 1
      docs/releases/2.0.txt
  3. 11 0
      tests/model_fields/test_filefield.py

+ 5 - 2
docs/ref/files/file.txt

@@ -56,8 +56,11 @@ The ``File`` class
         was originally opened with; ``None`` means to reopen with the original
         mode.
 
-        Returns ``self``, so that it can be used similar to Python's
-        built-in :func:`python:open()` with the ``with`` statement.
+        It can be used as a context manager, e.g. ``with file.open() as f:``.
+
+        .. versionchanged:: 2.0
+
+            Context manager support was added.
 
     .. method:: __iter__()
 

+ 2 - 1
docs/releases/2.0.txt

@@ -150,7 +150,8 @@ Email
 File Storage
 ~~~~~~~~~~~~
 
-* ...
+* :meth:`File.open() <django.core.files.File.open>` can be used as a context
+  manager, e.g. ``with file.open() as f:``.
 
 File Uploads
 ~~~~~~~~~~~~

+ 11 - 0
tests/model_fields/test_filefield.py

@@ -3,6 +3,7 @@ import sys
 import unittest
 
 from django.core.files import temp
+from django.core.files.base import ContentFile
 from django.core.files.uploadedfile import TemporaryUploadedFile
 from django.db.utils import IntegrityError
 from django.test import TestCase, override_settings
@@ -83,3 +84,13 @@ class FileFieldTests(TestCase):
             tmp_file_path = tmp_file.temporary_file_path()
             Document.objects.create(myfile=tmp_file)
             self.assertFalse(os.path.exists(tmp_file_path), 'Temporary file still exists')
+
+    def test_open_returns_self(self):
+        """
+        FieldField.open() returns self so it can be used as a context manager.
+        """
+        d = Document.objects.create(myfile='something.txt')
+        # Replace the FileField's file with an in-memory ContentFile, so that
+        # open() doesn't write to disk.
+        d.myfile.file = ContentFile(b'', name='bla')
+        self.assertEqual(d.myfile, d.myfile.open())