[1.8.x] Normalized usage of the tempfile module.

Specifically stopped using the dir argument.

Backport of a8fe12417f from master
This commit is contained in:
Aymeric Augustin 2015-02-21 19:18:54 +01:00 committed by Tim Graham
parent fae31f2348
commit e3953de900
6 changed files with 31 additions and 36 deletions

View File

@ -3322,8 +3322,7 @@ class AdminInlineFileUploadTest(TestCase):
# Set up test Picture and Gallery. # Set up test Picture and Gallery.
# These must be set up here instead of in fixtures in order to allow Picture # These must be set up here instead of in fixtures in order to allow Picture
# to use a NamedTemporaryFile. # to use a NamedTemporaryFile.
tdir = tempfile.gettempdir() file1 = tempfile.NamedTemporaryFile(suffix=".file1")
file1 = tempfile.NamedTemporaryFile(suffix=".file1", dir=tdir)
file1.write(b'a' * (2 ** 21)) file1.write(b'a' * (2 ** 21))
filename = file1.name filename = file1.name
file1.close() file1.close()

View File

@ -50,10 +50,8 @@ class FileUploadTests(TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_large_upload(self): def test_large_upload(self):
tdir = tempfile.gettempdir()
file = tempfile.NamedTemporaryFile file = tempfile.NamedTemporaryFile
with file(suffix=".file1", dir=tdir) as file1, file(suffix=".file2", dir=tdir) as file2: with file(suffix=".file1") as file1, file(suffix=".file2") as file2:
file1.write(b'a' * (2 ** 21)) file1.write(b'a' * (2 ** 21))
file1.seek(0) file1.seek(0)
@ -262,11 +260,8 @@ class FileUploadTests(TestCase):
"Got a long file name (%s characters)." % len(got)) "Got a long file name (%s characters)." % len(got))
def test_file_content(self): def test_file_content(self):
tdir = tempfile.gettempdir()
file = tempfile.NamedTemporaryFile file = tempfile.NamedTemporaryFile
with file(suffix=".ctype_extra", dir=tdir) as no_content_type, \ with file(suffix=".ctype_extra") as no_content_type, file(suffix=".ctype_extra") as simple_file:
file(suffix=".ctype_extra", dir=tdir) as simple_file:
no_content_type.write(b'no content') no_content_type.write(b'no content')
no_content_type.seek(0) no_content_type.seek(0)
@ -291,10 +286,8 @@ class FileUploadTests(TestCase):
def test_content_type_extra(self): def test_content_type_extra(self):
"""Uploaded files may have content type parameters available.""" """Uploaded files may have content type parameters available."""
tdir = tempfile.gettempdir()
file = tempfile.NamedTemporaryFile file = tempfile.NamedTemporaryFile
with file(suffix=".ctype_extra", dir=tdir) as no_content_type, file(suffix=".ctype_extra", dir=tdir) as simple_file: with file(suffix=".ctype_extra") as no_content_type, file(suffix=".ctype_extra") as simple_file:
no_content_type.write(b'something') no_content_type.write(b'something')
no_content_type.seek(0) no_content_type.seek(0)

View File

@ -1,7 +1,7 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import re import re
from tempfile import NamedTemporaryFile import tempfile
from django.contrib.gis import gdal from django.contrib.gis import gdal
from django.contrib.gis.geos import HAS_GEOS from django.contrib.gis.geos import HAS_GEOS
@ -219,10 +219,10 @@ class GeoModelTest(TestCase):
self.assertIn('"point": "%s"' % houston.point.ewkt, result) self.assertIn('"point": "%s"' % houston.point.ewkt, result)
# Reload now dumped data # Reload now dumped data
with NamedTemporaryFile(mode='w', suffix='.json') as tempfile: with tempfile.NamedTemporaryFile(mode='w', suffix='.json') as tmp:
tempfile.write(result) tmp.write(result)
tempfile.seek(0) tmp.seek(0)
call_command('loaddata', tempfile.name, verbosity=0) call_command('loaddata', tmp.name, verbosity=0)
self.assertListEqual(original_data, list(City.objects.all().order_by('name'))) self.assertListEqual(original_data, list(City.objects.all().order_by('name')))

View File

@ -80,14 +80,16 @@ print(article.headline)"""
article_text="This is an article", article_text="This is an article",
) )
with NamedTemporaryFile(mode='w+', suffix=".py", dir='.') as script: with NamedTemporaryFile(mode='w+', suffix=".py") as script:
script.write(script_template % pickle.dumps(a)) script.write(script_template % pickle.dumps(a))
script.flush() script.flush()
pythonpath = [os.path.dirname(script.name)] + sys.path
env = { env = {
# Needed to run test outside of tests directory # Needed to run test outside of tests directory
str('PYTHONPATH'): os.pathsep.join(sys.path), str('PYTHONPATH'): os.pathsep.join(pythonpath),
# Needed on Windows because http://bugs.python.org/issue8557 # Needed on Windows because http://bugs.python.org/issue8557
str('PATH'): os.environ['PATH'], str('PATH'): os.environ['PATH'],
str('TMPDIR'): os.environ['TMPDIR'],
str('LANG'): os.environ.get('LANG', ''), str('LANG'): os.environ.get('LANG', ''),
} }
if 'SYSTEMROOT' in os.environ: # Windows http://bugs.python.org/issue20614 if 'SYSTEMROOT' in os.environ: # Windows http://bugs.python.org/issue20614

View File

@ -5,6 +5,7 @@ from importlib import import_module
from django import conf from django import conf
from django.contrib import admin from django.contrib import admin
from django.test import TestCase, override_settings from django.test import TestCase, override_settings
from django.test.utils import extend_sys_path
from django.utils._os import npath, upath from django.utils._os import npath, upath
from django.utils.autoreload import gen_filenames from django.utils.autoreload import gen_filenames
@ -88,12 +89,12 @@ class TestFilenameGenerator(TestCase):
self.assertFalse(any(f.endswith('.pyc') for f in gen_filenames())) self.assertFalse(any(f.endswith('.pyc') for f in gen_filenames()))
def test_deleted_removed(self): def test_deleted_removed(self):
fd, filepath = tempfile.mkstemp(dir=os.path.dirname(upath(__file__)), suffix='.py') dirname = tempfile.mkdtemp()
try: filename = os.path.join(dirname, 'test_deleted_removed_module.py')
_, filename = os.path.split(filepath) with open(filename, 'w'):
import_module('.%s' % filename.replace('.py', ''), package='utils_tests') pass
self.assertIn(npath(filepath), gen_filenames()) with extend_sys_path(dirname):
finally: import_module('test_deleted_removed_module')
os.close(fd) self.assertIn(npath(filename), gen_filenames())
os.remove(filepath) os.unlink(filename)
self.assertNotIn(filepath, gen_filenames()) self.assertNotIn(filename, gen_filenames())

View File

@ -9,7 +9,7 @@ import os
import re import re
import shutil import shutil
import sys import sys
from tempfile import NamedTemporaryFile, mkdtemp, mkstemp import tempfile
from unittest import skipIf from unittest import skipIf
from django.core import mail from django.core import mail
@ -142,8 +142,8 @@ class DebugViewTests(TestCase):
def test_template_loader_postmortem(self): def test_template_loader_postmortem(self):
"""Tests for not existing file""" """Tests for not existing file"""
template_name = "notfound.html" template_name = "notfound.html"
with NamedTemporaryFile(prefix=template_name) as tempfile: with tempfile.NamedTemporaryFile(prefix=template_name) as tmpfile:
tempdir = os.path.dirname(tempfile.name) tempdir = os.path.dirname(tmpfile.name)
template_path = os.path.join(tempdir, template_name) template_path = os.path.join(tempdir, template_name)
with override_settings(TEMPLATES=[{ with override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
@ -155,9 +155,9 @@ class DebugViewTests(TestCase):
@skipIf(sys.platform == "win32", "Python on Windows doesn't have working os.chmod() and os.access().") @skipIf(sys.platform == "win32", "Python on Windows doesn't have working os.chmod() and os.access().")
def test_template_loader_postmortem_notreadable(self): def test_template_loader_postmortem_notreadable(self):
"""Tests for not readable file""" """Tests for not readable file"""
with NamedTemporaryFile() as tempfile: with tempfile.NamedTemporaryFile() as tmpfile:
template_name = tempfile.name template_name = tmpfile.name
tempdir = os.path.dirname(tempfile.name) tempdir = os.path.dirname(tmpfile.name)
template_path = os.path.join(tempdir, template_name) template_path = os.path.join(tempdir, template_name)
os.chmod(template_path, 0o0222) os.chmod(template_path, 0o0222)
with override_settings(TEMPLATES=[{ with override_settings(TEMPLATES=[{
@ -170,7 +170,7 @@ class DebugViewTests(TestCase):
def test_template_loader_postmortem_notafile(self): def test_template_loader_postmortem_notafile(self):
"""Tests for not being a file""" """Tests for not being a file"""
try: try:
template_path = mkdtemp() template_path = tempfile.mkdtemp()
template_name = os.path.basename(template_path) template_name = os.path.basename(template_path)
tempdir = os.path.dirname(template_path) tempdir = os.path.dirname(template_path)
with override_settings(TEMPLATES=[{ with override_settings(TEMPLATES=[{
@ -295,7 +295,7 @@ class ExceptionReporterTests(TestCase):
reporter = ExceptionReporter(None, None, None, None) reporter = ExceptionReporter(None, None, None, None)
for newline in ['\n', '\r\n', '\r']: for newline in ['\n', '\r\n', '\r']:
fd, filename = mkstemp(text=False) fd, filename = tempfile.mkstemp(text=False)
os.write(fd, force_bytes(newline.join(LINES) + newline)) os.write(fd, force_bytes(newline.join(LINES) + newline))
os.close(fd) os.close(fd)