1
0
mirror of https://github.com/django/django.git synced 2025-01-03 15:06:09 +00:00

Fixed #34778 -- Avoided importing modules in startapp/startproject.

This commit is contained in:
Jacob Walls 2023-08-31 20:15:22 -04:00 committed by Mariusz Felisiak
parent 9a9620dda6
commit bcd80de8b5
2 changed files with 25 additions and 7 deletions

View File

@ -5,7 +5,7 @@ import posixpath
import shutil import shutil
import stat import stat
import tempfile import tempfile
from importlib import import_module from importlib.util import find_spec
from urllib.request import build_opener from urllib.request import build_opener
import django import django
@ -275,12 +275,8 @@ class TemplateCommand(BaseCommand):
type=name_or_dir, type=name_or_dir,
) )
) )
# Check it cannot be imported. # Check that __spec__ doesn't exist.
try: if find_spec(name) is not None:
import_module(name)
except ImportError:
pass
else:
raise CommandError( raise CommandError(
"'{name}' conflicts with the name of an existing Python " "'{name}' conflicts with the name of an existing Python "
"module and cannot be used as {an} {app} {type}. Please try " "module and cannot be used as {an} {app} {type}. Please try "

View File

@ -2447,6 +2447,28 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
) )
self.assertFalse(os.path.exists(testproject_dir)) self.assertFalse(os.path.exists(testproject_dir))
def test_command_does_not_import(self):
"""
startproject doesn't import modules (and cannot be fooled by a module
raising ImportError).
"""
bad_name = "raises_import_error"
args = ["startproject", bad_name]
testproject_dir = os.path.join(self.test_dir, bad_name)
with open(os.path.join(self.test_dir, "raises_import_error.py"), "w") as f:
f.write("raise ImportError")
out, err = self.run_django_admin(args)
self.assertOutput(
err,
"CommandError: 'raises_import_error' conflicts with the name of an "
"existing Python module and cannot be used as a project name. Please try "
"another name.",
)
self.assertNoOutput(out)
self.assertFalse(os.path.exists(testproject_dir))
def test_simple_project_different_directory(self): def test_simple_project_different_directory(self):
""" """
The startproject management command creates a project in a specific The startproject management command creates a project in a specific