diff options
| author | django-bot <ops@djangoproject.com> | 2022-02-03 20:24:19 +0100 |
|---|---|---|
| committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2022-02-07 20:37:05 +0100 |
| commit | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 (patch) | |
| tree | f0506b668a013d0063e5fba3dbf4863b466713ba /tests/admin_scripts | |
| parent | f68fa8b45dfac545cfc4111d4e52804c86db68d3 (diff) | |
Refs #33476 -- Reformatted code with Black.
Diffstat (limited to 'tests/admin_scripts')
22 files changed, 916 insertions, 702 deletions
diff --git a/tests/admin_scripts/another_app_waiting_migration/migrations/0001_initial.py b/tests/admin_scripts/another_app_waiting_migration/migrations/0001_initial.py index d5fce1af36..fc3acf7f5a 100644 --- a/tests/admin_scripts/another_app_waiting_migration/migrations/0001_initial.py +++ b/tests/admin_scripts/another_app_waiting_migration/migrations/0001_initial.py @@ -5,15 +5,22 @@ class Migration(migrations.Migration): initial = True - dependencies = [ - ] + dependencies = [] operations = [ migrations.CreateModel( - name='Foo', + name="Foo", fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('name', models.CharField(max_length=255)), + ( + "id", + models.AutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("name", models.CharField(max_length=255)), ], ), ] diff --git a/tests/admin_scripts/another_app_waiting_migration/models.py b/tests/admin_scripts/another_app_waiting_migration/models.py index c089cb64e6..be73590caa 100644 --- a/tests/admin_scripts/another_app_waiting_migration/models.py +++ b/tests/admin_scripts/another_app_waiting_migration/models.py @@ -5,4 +5,4 @@ class Foo(models.Model): name = models.CharField(max_length=255) class Meta: - app_label = 'another_app_waiting_migration' + app_label = "another_app_waiting_migration" diff --git a/tests/admin_scripts/app_raising_messages/models.py b/tests/admin_scripts/app_raising_messages/models.py index 400fc8f907..eb3b605b02 100644 --- a/tests/admin_scripts/app_raising_messages/models.py +++ b/tests/admin_scripts/app_raising_messages/models.py @@ -6,7 +6,7 @@ class ModelRaisingMessages(models.Model): @classmethod def check(self, **kwargs): return [ - checks.Warning('First warning', hint='Hint', obj='obj'), - checks.Warning('Second warning', obj='a'), - checks.Error('An error', hint='Error hint'), + checks.Warning("First warning", hint="Hint", obj="obj"), + checks.Warning("Second warning", obj="a"), + checks.Error("An error", hint="Error hint"), ] diff --git a/tests/admin_scripts/app_raising_warning/models.py b/tests/admin_scripts/app_raising_warning/models.py index bc9b3b380f..5cd525ab07 100644 --- a/tests/admin_scripts/app_raising_warning/models.py +++ b/tests/admin_scripts/app_raising_warning/models.py @@ -5,4 +5,4 @@ from django.db import models class ModelRaisingMessages(models.Model): @classmethod def check(self, **kwargs): - return [checks.Warning('A warning')] + return [checks.Warning("A warning")] diff --git a/tests/admin_scripts/app_waiting_migration/migrations/0001_initial.py b/tests/admin_scripts/app_waiting_migration/migrations/0001_initial.py index aa47c4d474..7de6e2001b 100644 --- a/tests/admin_scripts/app_waiting_migration/migrations/0001_initial.py +++ b/tests/admin_scripts/app_waiting_migration/migrations/0001_initial.py @@ -5,15 +5,22 @@ class Migration(migrations.Migration): initial = True - dependencies = [ - ] + dependencies = [] operations = [ migrations.CreateModel( - name='Bar', + name="Bar", fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('name', models.CharField(max_length=255)), + ( + "id", + models.AutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("name", models.CharField(max_length=255)), ], ), ] diff --git a/tests/admin_scripts/app_waiting_migration/models.py b/tests/admin_scripts/app_waiting_migration/models.py index 46fee9c857..5bc8ef5685 100644 --- a/tests/admin_scripts/app_waiting_migration/models.py +++ b/tests/admin_scripts/app_waiting_migration/models.py @@ -5,4 +5,4 @@ class Bar(models.Model): name = models.CharField(max_length=255) class Meta: - app_label = 'app_waiting_migration' + app_label = "app_waiting_migration" diff --git a/tests/admin_scripts/complex_app/management/commands/duplicate.py b/tests/admin_scripts/complex_app/management/commands/duplicate.py index f217620ab9..839ce59666 100644 --- a/tests/admin_scripts/complex_app/management/commands/duplicate.py +++ b/tests/admin_scripts/complex_app/management/commands/duplicate.py @@ -2,6 +2,5 @@ from django.core.management.base import BaseCommand class Command(BaseCommand): - def handle(self, **options): - self.stdout.write('complex_app') + self.stdout.write("complex_app") diff --git a/tests/admin_scripts/complex_app/models/__init__.py b/tests/admin_scripts/complex_app/models/__init__.py index 7b647e74b1..cb0c126300 100644 --- a/tests/admin_scripts/complex_app/models/__init__.py +++ b/tests/admin_scripts/complex_app/models/__init__.py @@ -1,4 +1,4 @@ from .bar import Bar from .foo import Foo -__all__ = ['Foo', 'Bar'] +__all__ = ["Foo", "Bar"] diff --git a/tests/admin_scripts/complex_app/models/bar.py b/tests/admin_scripts/complex_app/models/bar.py index 8db46f4f57..85535bcd39 100644 --- a/tests/admin_scripts/complex_app/models/bar.py +++ b/tests/admin_scripts/complex_app/models/bar.py @@ -5,4 +5,4 @@ class Bar(models.Model): name = models.CharField(max_length=5) class Meta: - app_label = 'complex_app' + app_label = "complex_app" diff --git a/tests/admin_scripts/complex_app/models/foo.py b/tests/admin_scripts/complex_app/models/foo.py index 707c8982b0..3480a4ffec 100644 --- a/tests/admin_scripts/complex_app/models/foo.py +++ b/tests/admin_scripts/complex_app/models/foo.py @@ -5,4 +5,4 @@ class Foo(models.Model): name = models.CharField(max_length=5) class Meta: - app_label = 'complex_app' + app_label = "complex_app" diff --git a/tests/admin_scripts/configured_dynamic_settings_manage.py b/tests/admin_scripts/configured_dynamic_settings_manage.py index b4a9cf83fb..36693a81c5 100644 --- a/tests/admin_scripts/configured_dynamic_settings_manage.py +++ b/tests/admin_scripts/configured_dynamic_settings_manage.py @@ -7,14 +7,14 @@ from django.core.management import execute_from_command_line class Settings: def __getattr__(self, name): - if name == 'FOO': - return 'bar' + if name == "FOO": + return "bar" return getattr(global_settings, name) def __dir__(self): - return super().__dir__() + dir(global_settings) + ['FOO'] + return super().__dir__() + dir(global_settings) + ["FOO"] -if __name__ == '__main__': +if __name__ == "__main__": settings.configure(Settings()) execute_from_command_line(sys.argv) diff --git a/tests/admin_scripts/configured_settings_manage.py b/tests/admin_scripts/configured_settings_manage.py index e057e70810..d0e0264f74 100644 --- a/tests/admin_scripts/configured_settings_manage.py +++ b/tests/admin_scripts/configured_settings_manage.py @@ -4,6 +4,6 @@ import sys from django.conf import settings from django.core.management import execute_from_command_line -if __name__ == '__main__': +if __name__ == "__main__": settings.configure(DEBUG=True, CUSTOM=1) execute_from_command_line(sys.argv) diff --git a/tests/admin_scripts/management/commands/app_command.py b/tests/admin_scripts/management/commands/app_command.py index e5272dd6be..61631853ef 100644 --- a/tests/admin_scripts/management/commands/app_command.py +++ b/tests/admin_scripts/management/commands/app_command.py @@ -2,8 +2,11 @@ from django.core.management.base import AppCommand class Command(AppCommand): - help = 'Test Application-based commands' + help = "Test Application-based commands" requires_system_checks = [] def handle_app_config(self, app_config, **options): - print('EXECUTE:AppCommand name=%s, options=%s' % (app_config.name, sorted(options.items()))) + print( + "EXECUTE:AppCommand name=%s, options=%s" + % (app_config.name, sorted(options.items())) + ) diff --git a/tests/admin_scripts/management/commands/base_command.py b/tests/admin_scripts/management/commands/base_command.py index 940f04d018..26f4089963 100644 --- a/tests/admin_scripts/management/commands/base_command.py +++ b/tests/admin_scripts/management/commands/base_command.py @@ -2,14 +2,17 @@ from django.core.management.base import BaseCommand class Command(BaseCommand): - help = 'Test basic commands' + help = "Test basic commands" requires_system_checks = [] def add_arguments(self, parser): - parser.add_argument('args', nargs='*') - parser.add_argument('--option_a', '-a', default='1') - parser.add_argument('--option_b', '-b', default='2') - parser.add_argument('--option_c', '-c', default='3') + parser.add_argument("args", nargs="*") + parser.add_argument("--option_a", "-a", default="1") + parser.add_argument("--option_b", "-b", default="2") + parser.add_argument("--option_c", "-c", default="3") def handle(self, *labels, **options): - print('EXECUTE:BaseCommand labels=%s, options=%s' % (labels, sorted(options.items()))) + print( + "EXECUTE:BaseCommand labels=%s, options=%s" + % (labels, sorted(options.items())) + ) diff --git a/tests/admin_scripts/management/commands/custom_startproject.py b/tests/admin_scripts/management/commands/custom_startproject.py index b258e4b80d..f0507a1090 100644 --- a/tests/admin_scripts/management/commands/custom_startproject.py +++ b/tests/admin_scripts/management/commands/custom_startproject.py @@ -4,4 +4,6 @@ from django.core.management.commands.startproject import Command as BaseCommand class Command(BaseCommand): def add_arguments(self, parser): super().add_arguments(parser) - parser.add_argument('--extra', help='An arbitrary extra value passed to the context') + parser.add_argument( + "--extra", help="An arbitrary extra value passed to the context" + ) diff --git a/tests/admin_scripts/management/commands/label_command.py b/tests/admin_scripts/management/commands/label_command.py index 981b88ade4..87312b200e 100644 --- a/tests/admin_scripts/management/commands/label_command.py +++ b/tests/admin_scripts/management/commands/label_command.py @@ -6,4 +6,7 @@ class Command(LabelCommand): requires_system_checks = [] def handle_label(self, label, **options): - print('EXECUTE:LabelCommand label=%s, options=%s' % (label, sorted(options.items()))) + print( + "EXECUTE:LabelCommand label=%s, options=%s" + % (label, sorted(options.items())) + ) diff --git a/tests/admin_scripts/management/commands/noargs_command.py b/tests/admin_scripts/management/commands/noargs_command.py index 65ee370ab7..1a16dd8086 100644 --- a/tests/admin_scripts/management/commands/noargs_command.py +++ b/tests/admin_scripts/management/commands/noargs_command.py @@ -6,4 +6,4 @@ class Command(BaseCommand): requires_system_checks = [] def handle(self, **options): - print('EXECUTE: noargs_command options=%s' % sorted(options.items())) + print("EXECUTE: noargs_command options=%s" % sorted(options.items())) diff --git a/tests/admin_scripts/management/commands/suppress_base_options_command.py b/tests/admin_scripts/management/commands/suppress_base_options_command.py index 769ef3178c..24df0f4dd7 100644 --- a/tests/admin_scripts/management/commands/suppress_base_options_command.py +++ b/tests/admin_scripts/management/commands/suppress_base_options_command.py @@ -3,22 +3,22 @@ from django.core.management import BaseCommand class Command(BaseCommand): - help = 'Test suppress base options command.' + help = "Test suppress base options command." requires_system_checks = [] suppressed_base_arguments = { - '-v', - '--traceback', - '--settings', - '--pythonpath', - '--no-color', - '--force-color', - '--version', - 'file', + "-v", + "--traceback", + "--settings", + "--pythonpath", + "--no-color", + "--force-color", + "--version", + "file", } def add_arguments(self, parser): super().add_arguments(parser) - self.add_base_argument(parser, 'file', nargs='?', help='input file') + self.add_base_argument(parser, "file", nargs="?", help="input file") def handle(self, *labels, **options): - print('EXECUTE:SuppressBaseOptionsCommand options=%s' % sorted(options.items())) + print("EXECUTE:SuppressBaseOptionsCommand options=%s" % sorted(options.items())) diff --git a/tests/admin_scripts/simple_app/management/commands/duplicate.py b/tests/admin_scripts/simple_app/management/commands/duplicate.py index 18cd0aab08..aed15bc9f6 100644 --- a/tests/admin_scripts/simple_app/management/commands/duplicate.py +++ b/tests/admin_scripts/simple_app/management/commands/duplicate.py @@ -2,6 +2,5 @@ from django.core.management.base import BaseCommand class Command(BaseCommand): - def handle(self, **options): - self.stdout.write('simple_app') + self.stdout.write("simple_app") diff --git a/tests/admin_scripts/simple_app/models.py b/tests/admin_scripts/simple_app/models.py index d555ad80ea..5fa1d667f5 100644 --- a/tests/admin_scripts/simple_app/models.py +++ b/tests/admin_scripts/simple_app/models.py @@ -1,3 +1,3 @@ from ..complex_app.models.bar import Bar -__all__ = ['Bar'] +__all__ = ["Bar"] diff --git a/tests/admin_scripts/tests.py b/tests/admin_scripts/tests.py index c8d81e1fc0..55880802c2 100644 --- a/tests/admin_scripts/tests.py +++ b/tests/admin_scripts/tests.py @@ -18,20 +18,18 @@ from unittest import mock from django import conf, get_version from django.conf import settings from django.core.management import ( - BaseCommand, CommandError, call_command, color, execute_from_command_line, + BaseCommand, + CommandError, + call_command, + color, + execute_from_command_line, ) from django.core.management.commands.loaddata import Command as LoaddataCommand -from django.core.management.commands.runserver import ( - Command as RunserverCommand, -) -from django.core.management.commands.testserver import ( - Command as TestserverCommand, -) +from django.core.management.commands.runserver import Command as RunserverCommand +from django.core.management.commands.testserver import Command as TestserverCommand from django.db import ConnectionHandler, connection from django.db.migrations.recorder import MigrationRecorder -from django.test import ( - LiveServerTestCase, SimpleTestCase, TestCase, override_settings, -) +from django.test import LiveServerTestCase, SimpleTestCase, TestCase, override_settings from django.test.utils import captured_stderr, captured_stdout from django.urls import path from django.utils.version import PY39 @@ -39,9 +37,9 @@ from django.views.static import serve from . import urls -custom_templates_dir = os.path.join(os.path.dirname(__file__), 'custom_templates') +custom_templates_dir = os.path.join(os.path.dirname(__file__), "custom_templates") -SYSTEM_CHECK_MSG = 'System check identified no issues' +SYSTEM_CHECK_MSG = "System check identified no issues" class AdminScriptTestCase(SimpleTestCase): @@ -50,27 +48,29 @@ class AdminScriptTestCase(SimpleTestCase): self.addCleanup(tmpdir.cleanup) # os.path.realpath() is required for temporary directories on macOS, # where `/var` is a symlink to `/private/var`. - self.test_dir = os.path.realpath(os.path.join(tmpdir.name, 'test_project')) + self.test_dir = os.path.realpath(os.path.join(tmpdir.name, "test_project")) os.mkdir(self.test_dir) def write_settings(self, filename, apps=None, is_dir=False, sdict=None, extra=None): if is_dir: settings_dir = os.path.join(self.test_dir, filename) os.mkdir(settings_dir) - settings_file_path = os.path.join(settings_dir, '__init__.py') + settings_file_path = os.path.join(settings_dir, "__init__.py") else: settings_file_path = os.path.join(self.test_dir, filename) - with open(settings_file_path, 'w') as settings_file: - settings_file.write('# Settings file automatically generated by admin_scripts test case\n') + with open(settings_file_path, "w") as settings_file: + settings_file.write( + "# Settings file automatically generated by admin_scripts test case\n" + ) if extra: settings_file.write("%s\n" % extra) exports = [ - 'DATABASES', - 'DEFAULT_AUTO_FIELD', - 'ROOT_URLCONF', - 'SECRET_KEY', - 'USE_TZ', + "DATABASES", + "DEFAULT_AUTO_FIELD", + "ROOT_URLCONF", + "SECRET_KEY", + "USE_TZ", ] for s in exports: if hasattr(settings, s): @@ -80,7 +80,11 @@ class AdminScriptTestCase(SimpleTestCase): settings_file.write("%s = %s\n" % (s, o)) if apps is None: - apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts'] + apps = [ + "django.contrib.auth", + "django.contrib.contenttypes", + "admin_scripts", + ] settings_file.write("INSTALLED_APPS = %s\n" % apps) @@ -94,8 +98,8 @@ class AdminScriptTestCase(SimpleTestCase): """ paths = [] for backend in settings.DATABASES.values(): - package = backend['ENGINE'].split('.')[0] - if package != 'django': + package = backend["ENGINE"].split(".")[0] + if package != "django": backend_pkg = __import__(package) backend_dir = os.path.dirname(backend_pkg.__file__) paths.append(os.path.dirname(backend_dir)) @@ -116,13 +120,13 @@ class AdminScriptTestCase(SimpleTestCase): # Set the test environment if settings_file: - test_environ['DJANGO_SETTINGS_MODULE'] = settings_file - elif 'DJANGO_SETTINGS_MODULE' in test_environ: - del test_environ['DJANGO_SETTINGS_MODULE'] + test_environ["DJANGO_SETTINGS_MODULE"] = settings_file + elif "DJANGO_SETTINGS_MODULE" in test_environ: + del test_environ["DJANGO_SETTINGS_MODULE"] python_path = [base_dir, django_dir, tests_dir] python_path.extend(ext_backend_base_dirs) - test_environ['PYTHONPATH'] = os.pathsep.join(python_path) - test_environ['PYTHONWARNINGS'] = '' + test_environ["PYTHONPATH"] = os.pathsep.join(python_path) + test_environ["PYTHONWARNINGS"] = "" p = subprocess.run( [sys.executable, *args], @@ -131,48 +135,60 @@ class AdminScriptTestCase(SimpleTestCase): env=test_environ, text=True, # subprocess.run()'s umask was added in Python 3.9. - **({'umask': umask} if umask and PY39 else {}), + **({"umask": umask} if umask and PY39 else {}), ) return p.stdout, p.stderr def run_django_admin(self, args, settings_file=None, umask=None): - return self.run_test(['-m', 'django', *args], settings_file, umask=umask) + return self.run_test(["-m", "django", *args], settings_file, umask=umask) def run_manage(self, args, settings_file=None, manage_py=None): template_manage_py = ( os.path.join(os.path.dirname(__file__), manage_py) - if manage_py else - os.path.join(os.path.dirname(conf.__file__), 'project_template', 'manage.py-tpl') + if manage_py + else os.path.join( + os.path.dirname(conf.__file__), "project_template", "manage.py-tpl" + ) ) - test_manage_py = os.path.join(self.test_dir, 'manage.py') + test_manage_py = os.path.join(self.test_dir, "manage.py") shutil.copyfile(template_manage_py, test_manage_py) with open(test_manage_py) as fp: manage_py_contents = fp.read() manage_py_contents = manage_py_contents.replace( - "{{ project_name }}", "test_project") - with open(test_manage_py, 'w') as fp: + "{{ project_name }}", "test_project" + ) + with open(test_manage_py, "w") as fp: fp.write(manage_py_contents) - return self.run_test(['./manage.py', *args], settings_file) + return self.run_test(["./manage.py", *args], settings_file) def assertNoOutput(self, stream): "Utility assertion: assert that the given stream is empty" - self.assertEqual(len(stream), 0, "Stream should be empty: actually contains '%s'" % stream) + self.assertEqual( + len(stream), 0, "Stream should be empty: actually contains '%s'" % stream + ) def assertOutput(self, stream, msg, regex=False): "Utility assertion: assert that the given message exists in the output" if regex: self.assertIsNotNone( re.search(msg, stream), - "'%s' does not match actual output text '%s'" % (msg, stream) + "'%s' does not match actual output text '%s'" % (msg, stream), ) else: - self.assertIn(msg, stream, "'%s' does not match actual output text '%s'" % (msg, stream)) + self.assertIn( + msg, + stream, + "'%s' does not match actual output text '%s'" % (msg, stream), + ) def assertNotInOutput(self, stream, msg): "Utility assertion: assert that the given message doesn't exist in the output" - self.assertNotIn(msg, stream, "'%s' matches actual output text '%s'" % (msg, stream)) + self.assertNotIn( + msg, stream, "'%s' matches actual output text '%s'" % (msg, stream) + ) + ########################################################################## # DJANGO ADMIN TESTS @@ -186,22 +202,22 @@ class DjangoAdminNoSettings(AdminScriptTestCase): def test_builtin_command(self): "no settings: django-admin builtin commands fail with an error when no settings provided" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) - self.assertOutput(err, 'settings are not configured') + self.assertOutput(err, "settings are not configured") def test_builtin_with_bad_settings(self): "no settings: django-admin builtin commands fail if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) @@ -210,8 +226,8 @@ class DjangoAdminNoSettings(AdminScriptTestCase): Commands that don't require settings succeed if the settings file doesn't exist. """ - args = ['startproject'] - out, err = self.run_django_admin(args, settings_file='bad_settings') + args = ["startproject"] + out, err = self.run_django_admin(args, settings_file="bad_settings") self.assertNoOutput(out) self.assertOutput(err, "You must provide a project name", regex=True) @@ -221,48 +237,49 @@ class DjangoAdminDefaultSettings(AdminScriptTestCase): A series of tests for django-admin when using a settings.py file that contains the test application. """ + def setUp(self): super().setUp() - self.write_settings('settings.py') + self.write_settings("settings.py") def test_builtin_command(self): "default: django-admin builtin commands fail with an error when no settings provided" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) - self.assertOutput(err, 'settings are not configured') + self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): "default: django-admin builtin commands succeed if settings are provided as argument" - args = ['check', '--settings=test_project.settings', 'admin_scripts'] + args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "default: django-admin builtin commands succeed if settings are provided in the environment" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'test_project.settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "default: django-admin builtin commands fail if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "default: django-admin builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "default: django-admin can't execute user commands if it isn't provided settings" - args = ['noargs_command'] + args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") @@ -270,15 +287,15 @@ class DjangoAdminDefaultSettings(AdminScriptTestCase): def test_custom_command_with_settings(self): "default: django-admin can execute user commands if settings are provided as argument" - args = ['noargs_command', '--settings=test_project.settings'] + args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "default: django-admin can execute user commands if settings are provided in environment" - args = ['noargs_command'] - out, err = self.run_django_admin(args, 'test_project.settings') + args = ["noargs_command"] + out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") @@ -288,49 +305,57 @@ class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase): A series of tests for django-admin when using a settings.py file that contains the test application specified using a full path. """ + def setUp(self): super().setUp() - self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes', - 'admin_scripts', 'admin_scripts.complex_app']) + self.write_settings( + "settings.py", + [ + "django.contrib.auth", + "django.contrib.contenttypes", + "admin_scripts", + "admin_scripts.complex_app", + ], + ) def test_builtin_command(self): "fulldefault: django-admin builtin commands fail with an error when no settings provided" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) - self.assertOutput(err, 'settings are not configured') + self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): "fulldefault: django-admin builtin commands succeed if a settings file is provided" - args = ['check', '--settings=test_project.settings', 'admin_scripts'] + args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "fulldefault: django-admin builtin commands succeed if the environment contains settings" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'test_project.settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "fulldefault: django-admin builtin commands fail if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "fulldefault: django-admin builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "fulldefault: django-admin can't execute user commands unless settings are provided" - args = ['noargs_command'] + args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") @@ -338,15 +363,15 @@ class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase): def test_custom_command_with_settings(self): "fulldefault: django-admin can execute user commands if settings are provided as argument" - args = ['noargs_command', '--settings=test_project.settings'] + args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "fulldefault: django-admin can execute user commands if settings are provided in environment" - args = ['noargs_command'] - out, err = self.run_django_admin(args, 'test_project.settings') + args = ["noargs_command"] + out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") @@ -356,48 +381,51 @@ class DjangoAdminMinimalSettings(AdminScriptTestCase): A series of tests for django-admin when using a settings.py file that doesn't contain the test application. """ + def setUp(self): super().setUp() - self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) + self.write_settings( + "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] + ) def test_builtin_command(self): "minimal: django-admin builtin commands fail with an error when no settings provided" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) - self.assertOutput(err, 'settings are not configured') + self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): "minimal: django-admin builtin commands fail if settings are provided as argument" - args = ['check', '--settings=test_project.settings', 'admin_scripts'] + args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_environment(self): "minimal: django-admin builtin commands fail if settings are provided in the environment" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'test_project.settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_bad_settings(self): "minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "minimal: django-admin can't execute user commands unless settings are provided" - args = ['noargs_command'] + args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") @@ -405,15 +433,15 @@ class DjangoAdminMinimalSettings(AdminScriptTestCase): def test_custom_command_with_settings(self): "minimal: django-admin can't execute user commands, even if settings are provided as argument" - args = ['noargs_command', '--settings=test_project.settings'] + args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): "minimal: django-admin can't execute user commands, even if settings are provided in environment" - args = ['noargs_command'] - out, err = self.run_django_admin(args, 'test_project.settings') + args = ["noargs_command"] + out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") @@ -423,48 +451,49 @@ class DjangoAdminAlternateSettings(AdminScriptTestCase): A series of tests for django-admin when using a settings file with a name other than 'settings.py'. """ + def setUp(self): super().setUp() - self.write_settings('alternate_settings.py') + self.write_settings("alternate_settings.py") def test_builtin_command(self): "alternate: django-admin builtin commands fail with an error when no settings provided" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) - self.assertOutput(err, 'settings are not configured') + self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): "alternate: django-admin builtin commands succeed if settings are provided as argument" - args = ['check', '--settings=test_project.alternate_settings', 'admin_scripts'] + args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "alternate: django-admin builtin commands succeed if settings are provided in the environment" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'test_project.alternate_settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "alternate: django-admin can't execute user commands unless settings are provided" - args = ['noargs_command'] + args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") @@ -472,15 +501,15 @@ class DjangoAdminAlternateSettings(AdminScriptTestCase): def test_custom_command_with_settings(self): "alternate: django-admin can execute user commands if settings are provided as argument" - args = ['noargs_command', '--settings=test_project.alternate_settings'] + args = ["noargs_command", "--settings=test_project.alternate_settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "alternate: django-admin can execute user commands if settings are provided in environment" - args = ['noargs_command'] - out, err = self.run_django_admin(args, 'test_project.alternate_settings') + args = ["noargs_command"] + out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") @@ -492,48 +521,51 @@ class DjangoAdminMultipleSettings(AdminScriptTestCase): file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ + def setUp(self): super().setUp() - self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) - self.write_settings('alternate_settings.py') + self.write_settings( + "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] + ) + self.write_settings("alternate_settings.py") def test_builtin_command(self): "alternate: django-admin builtin commands fail with an error when no settings provided" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) - self.assertOutput(err, 'settings are not configured') + self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): "alternate: django-admin builtin commands succeed if settings are provided as argument" - args = ['check', '--settings=test_project.alternate_settings', 'admin_scripts'] + args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "alternate: django-admin builtin commands succeed if settings are provided in the environment" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'test_project.alternate_settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "alternate: django-admin can't execute user commands unless settings are provided" - args = ['noargs_command'] + args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") @@ -541,15 +573,15 @@ class DjangoAdminMultipleSettings(AdminScriptTestCase): def test_custom_command_with_settings(self): "alternate: django-admin can execute user commands if settings are provided as argument" - args = ['noargs_command', '--settings=test_project.alternate_settings'] + args = ["noargs_command", "--settings=test_project.alternate_settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "alternate: django-admin can execute user commands if settings are provided in environment" - args = ['noargs_command'] - out, err = self.run_django_admin(args, 'test_project.alternate_settings') + args = ["noargs_command"] + out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") @@ -562,65 +594,65 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase): def setUp(self): super().setUp() - self.write_settings('settings', is_dir=True) + self.write_settings("settings", is_dir=True) def test_setup_environ(self): "directory: startapp creates the correct directory" - args = ['startapp', 'settings_test'] - app_path = os.path.join(self.test_dir, 'settings_test') - out, err = self.run_django_admin(args, 'test_project.settings') + args = ["startapp", "settings_test"] + app_path = os.path.join(self.test_dir, "settings_test") + out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) - with open(os.path.join(app_path, 'apps.py')) 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) def test_setup_environ_custom_template(self): "directory: startapp creates the correct directory with a custom template" - template_path = os.path.join(custom_templates_dir, 'app_template') - args = ['startapp', '--template', template_path, 'custom_settings_test'] - app_path = os.path.join(self.test_dir, 'custom_settings_test') - out, err = self.run_django_admin(args, 'test_project.settings') + template_path = os.path.join(custom_templates_dir, "app_template") + args = ["startapp", "--template", template_path, "custom_settings_test"] + app_path = os.path.join(self.test_dir, "custom_settings_test") + out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) - self.assertTrue(os.path.exists(os.path.join(app_path, 'api.py'))) + self.assertTrue(os.path.exists(os.path.join(app_path, "api.py"))) def test_startapp_unicode_name(self): """startapp creates the correct directory with Unicode characters.""" - args = ['startapp', 'こんにちは'] - app_path = os.path.join(self.test_dir, 'こんにちは') - out, err = self.run_django_admin(args, 'test_project.settings') + args = ["startapp", "こんにちは"] + app_path = os.path.join(self.test_dir, "こんにちは") + out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) - with open(os.path.join(app_path, 'apps.py'), 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) def test_builtin_command(self): "directory: django-admin builtin commands fail with an error when no settings provided" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) - self.assertOutput(err, 'settings are not configured') + self.assertOutput(err, "settings are not configured") def test_builtin_with_bad_settings(self): "directory: django-admin builtin commands fail if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "directory: django-admin builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "directory: django-admin can't execute user commands unless settings are provided" - args = ['noargs_command'] + args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") @@ -628,15 +660,15 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase): def test_builtin_with_settings(self): "directory: django-admin builtin commands succeed if settings are provided as argument" - args = ['check', '--settings=test_project.settings', 'admin_scripts'] + args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "directory: django-admin builtin commands succeed if settings are provided in the environment" - args = ['check', 'admin_scripts'] - out, err = self.run_django_admin(args, 'test_project.settings') + args = ["check", "admin_scripts"] + out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) @@ -647,13 +679,17 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase): # of the generated manage.py script ########################################################################## + class ManageManuallyConfiguredSettings(AdminScriptTestCase): """Customized manage.py calling settings.configure().""" + def test_non_existent_command_output(self): - out, err = self.run_manage(['invalid_command'], manage_py='configured_settings_manage.py') + out, err = self.run_manage( + ["invalid_command"], manage_py="configured_settings_manage.py" + ) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'invalid_command'") - self.assertNotInOutput(err, 'No Django settings specified') + self.assertNotInOutput(err, "No Django settings specified") class ManageNoSettings(AdminScriptTestCase): @@ -661,22 +697,24 @@ class ManageNoSettings(AdminScriptTestCase): def test_builtin_command(self): "no settings: manage.py builtin commands fail with an error when no settings provided" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) - self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True) + self.assertOutput( + err, r"No module named '?(test_project\.)?settings'?", regex=True + ) def test_builtin_with_bad_settings(self): "no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "no settings: manage.py builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_manage(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) @@ -685,63 +723,64 @@ class ManageDefaultSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that contains the test application. """ + def setUp(self): super().setUp() - self.write_settings('settings.py') + self.write_settings("settings.py") def test_builtin_command(self): "default: manage.py builtin commands succeed when default settings are appropriate" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_settings(self): "default: manage.py builtin commands succeed if settings are provided as argument" - args = ['check', '--settings=test_project.settings', 'admin_scripts'] + args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "default: manage.py builtin commands succeed if settings are provided in the environment" - args = ['check', 'admin_scripts'] - out, err = self.run_manage(args, 'test_project.settings') + args = ["check", "admin_scripts"] + out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "default: manage.py builtin commands succeed if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "default: manage.py builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_manage(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "default: manage.py can execute user commands when default settings are appropriate" - args = ['noargs_command'] + args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_settings(self): "default: manage.py can execute user commands when settings are provided as argument" - args = ['noargs_command', '--settings=test_project.settings'] + args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "default: manage.py can execute user commands when settings are provided in environment" - args = ['noargs_command'] - out, err = self.run_manage(args, 'test_project.settings') + args = ["noargs_command"] + out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") @@ -750,63 +789,67 @@ class ManageFullPathDefaultSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that contains the test application specified using a full path. """ + def setUp(self): super().setUp() - self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts']) + self.write_settings( + "settings.py", + ["django.contrib.auth", "django.contrib.contenttypes", "admin_scripts"], + ) def test_builtin_command(self): "fulldefault: manage.py builtin commands succeed when default settings are appropriate" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_settings(self): "fulldefault: manage.py builtin commands succeed if settings are provided as argument" - args = ['check', '--settings=test_project.settings', 'admin_scripts'] + args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "fulldefault: manage.py builtin commands succeed if settings are provided in the environment" - args = ['check', 'admin_scripts'] - out, err = self.run_manage(args, 'test_project.settings') + args = ["check", "admin_scripts"] + out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "fulldefault: manage.py builtin commands succeed if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "fulldefault: manage.py builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_manage(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "fulldefault: manage.py can execute user commands when default settings are appropriate" - args = ['noargs_command'] + args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_settings(self): "fulldefault: manage.py can execute user commands when settings are provided as argument" - args = ['noargs_command', '--settings=test_project.settings'] + args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "fulldefault: manage.py can execute user commands when settings are provided in environment" - args = ['noargs_command'] - out, err = self.run_manage(args, 'test_project.settings') + args = ["noargs_command"] + out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") @@ -815,63 +858,66 @@ class ManageMinimalSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that doesn't contain the test application. """ + def setUp(self): super().setUp() - self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) + self.write_settings( + "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] + ) def test_builtin_command(self): "minimal: manage.py builtin commands fail with an error when no settings provided" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_settings(self): "minimal: manage.py builtin commands fail if settings are provided as argument" - args = ['check', '--settings=test_project.settings', 'admin_scripts'] + args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_environment(self): "minimal: manage.py builtin commands fail if settings are provided in the environment" - args = ['check', 'admin_scripts'] - out, err = self.run_manage(args, 'test_project.settings') + args = ["check", "admin_scripts"] + out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_bad_settings(self): "minimal: manage.py builtin commands fail if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "minimal: manage.py builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_manage(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "minimal: manage.py can't execute user commands without appropriate settings" - args = ['noargs_command'] + args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "minimal: manage.py can't execute user commands, even if settings are provided as argument" - args = ['noargs_command', '--settings=test_project.settings'] + args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): "minimal: manage.py can't execute user commands, even if settings are provided in environment" - args = ['noargs_command'] - out, err = self.run_manage(args, 'test_project.settings') + args = ["noargs_command"] + out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") @@ -880,85 +926,90 @@ class ManageAlternateSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings file with a name other than 'settings.py'. """ + def setUp(self): super().setUp() - self.write_settings('alternate_settings.py') + self.write_settings("alternate_settings.py") def test_builtin_command(self): "alternate: manage.py builtin commands fail with an error when no default settings provided" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) - self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True) + self.assertOutput( + err, r"No module named '?(test_project\.)?settings'?", regex=True + ) def test_builtin_with_settings(self): "alternate: manage.py builtin commands work with settings provided as argument" - args = ['check', '--settings=alternate_settings', 'admin_scripts'] + args = ["check", "--settings=alternate_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertOutput(out, SYSTEM_CHECK_MSG) self.assertNoOutput(err) def test_builtin_with_environment(self): "alternate: manage.py builtin commands work if settings are provided in the environment" - args = ['check', 'admin_scripts'] - out, err = self.run_manage(args, 'alternate_settings') + args = ["check", "admin_scripts"] + out, err = self.run_manage(args, "alternate_settings") self.assertOutput(out, SYSTEM_CHECK_MSG) self.assertNoOutput(err) def test_builtin_with_bad_settings(self): "alternate: manage.py builtin commands fail if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "alternate: manage.py builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_manage(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "alternate: manage.py can't execute user commands without settings" - args = ['noargs_command'] + args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(out) - self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True) + self.assertOutput( + err, r"No module named '?(test_project\.)?settings'?", regex=True + ) def test_custom_command_with_settings(self): "alternate: manage.py can execute user commands if settings are provided as argument" - args = ['noargs_command', '--settings=alternate_settings'] + args = ["noargs_command", "--settings=alternate_settings"] out, err = self.run_manage(args) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', " - "'alternate_settings'), ('traceback', False), ('verbosity', 1)]" + "'alternate_settings'), ('traceback', False), ('verbosity', 1)]", ) self.assertNoOutput(err) def test_custom_command_with_environment(self): "alternate: manage.py can execute user commands if settings are provided in environment" - args = ['noargs_command'] - out, err = self.run_manage(args, 'alternate_settings') + args = ["noargs_command"] + out, err = self.run_manage(args, "alternate_settings") self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', None), " - "('traceback', False), ('verbosity', 1)]" + "('traceback', False), ('verbosity', 1)]", ) self.assertNoOutput(err) def test_custom_command_output_color(self): "alternate: manage.py output syntax color can be deactivated with the `--no-color` option" - args = ['noargs_command', '--no-color', '--settings=alternate_settings'] + args = ["noargs_command", "--no-color", "--settings=alternate_settings"] out, err = self.run_manage(args) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', True), ('pythonpath', None), ('settings', " - "'alternate_settings'), ('traceback', False), ('verbosity', 1)]" + "'alternate_settings'), ('traceback', False), ('verbosity', 1)]", ) self.assertNoOutput(err) @@ -969,64 +1020,67 @@ class ManageMultipleSettings(AdminScriptTestCase): file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ + def setUp(self): super().setUp() - self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) - self.write_settings('alternate_settings.py') + self.write_settings( + "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] + ) + self.write_settings("alternate_settings.py") def test_builtin_command(self): "multiple: manage.py builtin commands fail with an error when no settings provided" - args = ['check', 'admin_scripts'] + args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_settings(self): "multiple: manage.py builtin commands succeed if settings are provided as argument" - args = ['check', '--settings=alternate_settings', 'admin_scripts'] + args = ["check", "--settings=alternate_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "multiple: manage.py can execute builtin commands if settings are provided in the environment" - args = ['check', 'admin_scripts'] - out, err = self.run_manage(args, 'alternate_settings') + args = ["check", "admin_scripts"] + out, err = self.run_manage(args, "alternate_settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "multiple: manage.py builtin commands fail if settings file (from argument) doesn't exist" - args = ['check', '--settings=bad_settings', 'admin_scripts'] + args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "multiple: manage.py builtin commands fail if settings file (from environment) doesn't exist" - args = ['check', 'admin_scripts'] - out, err = self.run_manage(args, 'bad_settings') + args = ["check", "admin_scripts"] + out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "multiple: manage.py can't execute user commands using default settings" - args = ['noargs_command'] + args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "multiple: manage.py can execute user commands if settings are provided as argument" - args = ['noargs_command', '--settings=alternate_settings'] + args = ["noargs_command", "--settings=alternate_settings"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "multiple: manage.py can execute user commands if settings are provided in environment" - args = ['noargs_command'] - out, err = self.run_manage(args, 'alternate_settings') + args = ["noargs_command"] + out, err = self.run_manage(args, "alternate_settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") @@ -1036,19 +1090,24 @@ class ManageSettingsWithSettingsErrors(AdminScriptTestCase): Tests for manage.py when using the default settings.py file containing runtime errors. """ + def write_settings_with_import_error(self, filename): settings_file_path = os.path.join(self.test_dir, filename) - with open(settings_file_path, 'w') as settings_file: - settings_file.write('# Settings file automatically generated by admin_scripts test case\n') - settings_file.write('# The next line will cause an import error:\nimport foo42bar\n') + with open(settings_file_path, "w") as settings_file: + settings_file.write( + "# Settings file automatically generated by admin_scripts test case\n" + ) + settings_file.write( + "# The next line will cause an import error:\nimport foo42bar\n" + ) def test_import_error(self): """ import error: manage.py builtin commands shows useful diagnostic info when settings with import errors is provided (#14130). """ - self.write_settings_with_import_error('settings.py') - args = ['check', 'admin_scripts'] + self.write_settings_with_import_error("settings.py") + args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named") @@ -1059,15 +1118,15 @@ class ManageSettingsWithSettingsErrors(AdminScriptTestCase): manage.py builtin commands does not swallow attribute error due to bad settings (#18845). """ - self.write_settings('settings.py', sdict={'BAD_VAR': 'INSTALLED_APPS.crash'}) - args = ['collectstatic', 'admin_scripts'] + self.write_settings("settings.py", sdict={"BAD_VAR": "INSTALLED_APPS.crash"}) + args = ["collectstatic", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "AttributeError: 'list' object has no attribute 'crash'") def test_key_error(self): - self.write_settings('settings.py', sdict={'BAD_VAR': 'DATABASES["blah"]'}) - args = ['collectstatic', 'admin_scripts'] + self.write_settings("settings.py", sdict={"BAD_VAR": 'DATABASES["blah"]'}) + args = ["collectstatic", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "KeyError: 'blah'") @@ -1078,13 +1137,13 @@ class ManageSettingsWithSettingsErrors(AdminScriptTestCase): available. """ self.write_settings( - 'settings.py', - extra='from django.core.exceptions import ImproperlyConfigured\n' - 'raise ImproperlyConfigured()', + "settings.py", + extra="from django.core.exceptions import ImproperlyConfigured\n" + "raise ImproperlyConfigured()", ) - args = ['help'] + args = ["help"] out, err = self.run_manage(args) - self.assertOutput(out, 'only Django core commands are listed') + self.assertOutput(out, "only Django core commands are listed") self.assertNoOutput(err) @@ -1092,101 +1151,101 @@ class ManageCheck(AdminScriptTestCase): def test_nonexistent_app(self): """check reports an error on a nonexistent app in INSTALLED_APPS.""" self.write_settings( - 'settings.py', - apps=['admin_scriptz.broken_app'], - sdict={'USE_I18N': False}, + "settings.py", + apps=["admin_scriptz.broken_app"], + sdict={"USE_I18N": False}, ) - args = ['check'] + args = ["check"] out, err = self.run_manage(args) self.assertNoOutput(out) - self.assertOutput(err, 'ModuleNotFoundError') - self.assertOutput(err, 'No module named') - self.assertOutput(err, 'admin_scriptz') + self.assertOutput(err, "ModuleNotFoundError") + self.assertOutput(err, "No module named") + self.assertOutput(err, "admin_scriptz") def test_broken_app(self): - """ manage.py check reports an ImportError if an app's models.py - raises one on import """ + """manage.py check reports an ImportError if an app's models.py + raises one on import""" - self.write_settings('settings.py', apps=['admin_scripts.broken_app']) - args = ['check'] + self.write_settings("settings.py", apps=["admin_scripts.broken_app"]) + args = ["check"] out, err = self.run_manage(args) self.assertNoOutput(out) - self.assertOutput(err, 'ImportError') + self.assertOutput(err, "ImportError") def test_complex_app(self): - """ manage.py check does not raise an ImportError validating a - complex app with nested calls to load_app """ + """manage.py check does not raise an ImportError validating a + complex app with nested calls to load_app""" self.write_settings( - 'settings.py', + "settings.py", apps=[ - 'admin_scripts.complex_app', - 'admin_scripts.simple_app', - 'django.contrib.admin.apps.SimpleAdminConfig', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.messages', + "admin_scripts.complex_app", + "admin_scripts.simple_app", + "django.contrib.admin.apps.SimpleAdminConfig", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.messages", ], sdict={ - 'DEBUG': True, - 'MIDDLEWARE': [ - 'django.contrib.messages.middleware.MessageMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.sessions.middleware.SessionMiddleware', + "DEBUG": True, + "MIDDLEWARE": [ + "django.contrib.messages.middleware.MessageMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", ], - 'TEMPLATES': [ + "TEMPLATES": [ { - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], - 'APP_DIRS': True, - 'OPTIONS': { - 'context_processors': [ - 'django.template.context_processors.request', - 'django.contrib.auth.context_processors.auth', - 'django.contrib.messages.context_processors.messages', + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", ], }, }, ], - } + }, ) - args = ['check'] + args = ["check"] out, err = self.run_manage(args) self.assertNoOutput(err) - self.assertEqual(out, 'System check identified no issues (0 silenced).\n') + self.assertEqual(out, "System check identified no issues (0 silenced).\n") def test_app_with_import(self): - """ manage.py check does not raise errors when an app imports a base - class that itself has an abstract base. """ + """manage.py check does not raise errors when an app imports a base + class that itself has an abstract base.""" self.write_settings( - 'settings.py', + "settings.py", apps=[ - 'admin_scripts.app_with_import', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sites', + "admin_scripts.app_with_import", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sites", ], - sdict={'DEBUG': True}, + sdict={"DEBUG": True}, ) - args = ['check'] + args = ["check"] out, err = self.run_manage(args) self.assertNoOutput(err) - self.assertEqual(out, 'System check identified no issues (0 silenced).\n') + self.assertEqual(out, "System check identified no issues (0 silenced).\n") def test_output_format(self): - """ All errors/warnings should be sorted by level and by message. """ + """All errors/warnings should be sorted by level and by message.""" self.write_settings( - 'settings.py', + "settings.py", apps=[ - 'admin_scripts.app_raising_messages', - 'django.contrib.auth', - 'django.contrib.contenttypes', + "admin_scripts.app_raising_messages", + "django.contrib.auth", + "django.contrib.contenttypes", ], - sdict={'DEBUG': True}, + sdict={"DEBUG": True}, ) - args = ['check'] + args = ["check"] out, err = self.run_manage(args) expected_err = ( "SystemCheckError: System check identified some issues:\n" @@ -1215,15 +1274,15 @@ class ManageCheck(AdminScriptTestCase): """ self.write_settings( - 'settings.py', + "settings.py", apps=[ - 'admin_scripts.app_raising_warning', - 'django.contrib.auth', - 'django.contrib.contenttypes', + "admin_scripts.app_raising_warning", + "django.contrib.auth", + "django.contrib.contenttypes", ], - sdict={'DEBUG': True}, + sdict={"DEBUG": True}, ) - args = ['check'] + args = ["check"] out, err = self.run_manage(args) expected_err = ( "System check identified some issues:\n" # No "CommandError: " part @@ -1254,101 +1313,104 @@ class ManageRunserver(SimpleTestCase): def test_runserver_addrport(self): call_command(self.cmd) - self.assertServerSettings('127.0.0.1', '8000') + self.assertServerSettings("127.0.0.1", "8000") call_command(self.cmd, addrport="1.2.3.4:8000") - self.assertServerSettings('1.2.3.4', '8000') + self.assertServerSettings("1.2.3.4", "8000") call_command(self.cmd, addrport="7000") - self.assertServerSettings('127.0.0.1', '7000') + self.assertServerSettings("127.0.0.1", "7000") @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_addrport_ipv6(self): call_command(self.cmd, addrport="", use_ipv6=True) - self.assertServerSettings('::1', '8000', ipv6=True, raw_ipv6=True) + self.assertServerSettings("::1", "8000", ipv6=True, raw_ipv6=True) call_command(self.cmd, addrport="7000", use_ipv6=True) - self.assertServerSettings('::1', '7000', ipv6=True, raw_ipv6=True) + self.assertServerSettings("::1", "7000", ipv6=True, raw_ipv6=True) call_command(self.cmd, addrport="[2001:0db8:1234:5678::9]:7000") - self.assertServerSettings('2001:0db8:1234:5678::9', '7000', ipv6=True, raw_ipv6=True) + self.assertServerSettings( + "2001:0db8:1234:5678::9", "7000", ipv6=True, raw_ipv6=True + ) def test_runner_hostname(self): call_command(self.cmd, addrport="localhost:8000") - self.assertServerSettings('localhost', '8000') + self.assertServerSettings("localhost", "8000") call_command(self.cmd, addrport="test.domain.local:7000") - self.assertServerSettings('test.domain.local', '7000') + self.assertServerSettings("test.domain.local", "7000") @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_hostname_ipv6(self): call_command(self.cmd, addrport="test.domain.local:7000", use_ipv6=True) - self.assertServerSettings('test.domain.local', '7000', ipv6=True) + self.assertServerSettings("test.domain.local", "7000", ipv6=True) def test_runner_custom_defaults(self): - self.cmd.default_addr = '0.0.0.0' - self.cmd.default_port = '5000' + self.cmd.default_addr = "0.0.0.0" + self.cmd.default_port = "5000" call_command(self.cmd) - self.assertServerSettings('0.0.0.0', '5000') + self.assertServerSettings("0.0.0.0", "5000") @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_custom_defaults_ipv6(self): - self.cmd.default_addr_ipv6 = '::' + self.cmd.default_addr_ipv6 = "::" call_command(self.cmd, use_ipv6=True) - self.assertServerSettings('::', '8000', ipv6=True, raw_ipv6=True) + self.assertServerSettings("::", "8000", ipv6=True, raw_ipv6=True) def test_runner_ambiguous(self): # Only 4 characters, all of which could be in an ipv6 address call_command(self.cmd, addrport="beef:7654") - self.assertServerSettings('beef', '7654') + self.assertServerSettings("beef", "7654") # Uses only characters that could be in an ipv6 address call_command(self.cmd, addrport="deadbeef:7654") - self.assertServerSettings('deadbeef', '7654') + self.assertServerSettings("deadbeef", "7654") def test_no_database(self): """ Ensure runserver.check_migrations doesn't choke on empty DATABASES. """ tested_connections = ConnectionHandler({}) - with mock.patch('django.core.management.base.connections', new=tested_connections): + with mock.patch( + "django.core.management.base.connections", new=tested_connections + ): self.cmd.check_migrations() def test_readonly_database(self): """ runserver.check_migrations() doesn't choke when a database is read-only. """ - with mock.patch.object(MigrationRecorder, 'has_table', return_value=False): + with mock.patch.object(MigrationRecorder, "has_table", return_value=False): self.cmd.check_migrations() # You have # ... - self.assertIn('unapplied migration(s)', self.output.getvalue()) + self.assertIn("unapplied migration(s)", self.output.getvalue()) - @mock.patch('django.core.management.commands.runserver.run') - @mock.patch('django.core.management.base.BaseCommand.check_migrations') - @mock.patch('django.core.management.base.BaseCommand.check') + @mock.patch("django.core.management.commands.runserver.run") + @mock.patch("django.core.management.base.BaseCommand.check_migrations") + @mock.patch("django.core.management.base.BaseCommand.check") def test_skip_checks(self, mocked_check, *mocked_objects): call_command( - 'runserver', + "runserver", use_reloader=False, skip_checks=True, stdout=self.output, ) - self.assertNotIn('Performing system checks...', self.output.getvalue()) + self.assertNotIn("Performing system checks...", self.output.getvalue()) mocked_check.assert_not_called() self.output.truncate(0) call_command( - 'runserver', + "runserver", use_reloader=False, skip_checks=False, stdout=self.output, ) - self.assertIn('Performing system checks...', self.output.getvalue()) + self.assertIn("Performing system checks...", self.output.getvalue()) mocked_check.assert_called() class ManageRunserverMigrationWarning(TestCase): - def setUp(self): self.stdout = StringIO() self.runserver_command = RunserverCommand(stdout=self.stdout) @@ -1357,8 +1419,8 @@ class ManageRunserverMigrationWarning(TestCase): def test_migration_warning_one_app(self): self.runserver_command.check_migrations() output = self.stdout.getvalue() - self.assertIn('You have 1 unapplied migration(s)', output) - self.assertIn('apply the migrations for app(s): app_waiting_migration.', output) + self.assertIn("You have 1 unapplied migration(s)", output) + self.assertIn("apply the migrations for app(s): app_waiting_migration.", output) @override_settings( INSTALLED_APPS=[ @@ -1369,56 +1431,71 @@ class ManageRunserverMigrationWarning(TestCase): def test_migration_warning_multiple_apps(self): self.runserver_command.check_migrations() output = self.stdout.getvalue() - self.assertIn('You have 2 unapplied migration(s)', output) + self.assertIn("You have 2 unapplied migration(s)", output) self.assertIn( - 'apply the migrations for app(s): another_app_waiting_migration, ' - 'app_waiting_migration.', output + "apply the migrations for app(s): another_app_waiting_migration, " + "app_waiting_migration.", + output, ) class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase): def setUp(self): super().setUp() - self.write_settings('settings.py', sdict={ - 'ALLOWED_HOSTS': [], - 'DEBUG': False, - }) + self.write_settings( + "settings.py", + sdict={ + "ALLOWED_HOSTS": [], + "DEBUG": False, + }, + ) def test_empty_allowed_hosts_error(self): - out, err = self.run_manage(['runserver']) + out, err = self.run_manage(["runserver"]) self.assertNoOutput(out) - self.assertOutput(err, 'CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.') + self.assertOutput( + err, "CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False." + ) class ManageRunserverHelpOutput(AdminScriptTestCase): def test_suppressed_options(self): """runserver doesn't support --verbosity and --trackback options.""" - out, err = self.run_manage(['runserver', '--help']) - self.assertNotInOutput(out, '--verbosity') - self.assertNotInOutput(out, '--trackback') - self.assertOutput(out, '--settings') + out, err = self.run_manage(["runserver", "--help"]) + self.assertNotInOutput(out, "--verbosity") + self.assertNotInOutput(out, "--trackback") + self.assertOutput(out, "--settings") class ManageTestserver(SimpleTestCase): - - @mock.patch.object(TestserverCommand, 'handle', return_value='') + @mock.patch.object(TestserverCommand, "handle", return_value="") def test_testserver_handle_params(self, mock_handle): out = StringIO() - call_command('testserver', 'blah.json', stdout=out) + call_command("testserver", "blah.json", stdout=out) mock_handle.assert_called_with( - 'blah.json', - stdout=out, settings=None, pythonpath=None, verbosity=1, - traceback=False, addrport='', no_color=False, use_ipv6=False, - skip_checks=True, interactive=True, force_color=False, + "blah.json", + stdout=out, + settings=None, + pythonpath=None, + verbosity=1, + traceback=False, + addrport="", + no_color=False, + use_ipv6=False, + skip_checks=True, + interactive=True, + force_color=False, ) - @mock.patch('django.db.connection.creation.create_test_db', return_value='test_db') - @mock.patch.object(LoaddataCommand, 'handle', return_value='') - @mock.patch.object(RunserverCommand, 'handle', return_value='') - def test_params_to_runserver(self, mock_runserver_handle, mock_loaddata_handle, mock_create_test_db): - call_command('testserver', 'blah.json') + @mock.patch("django.db.connection.creation.create_test_db", return_value="test_db") + @mock.patch.object(LoaddataCommand, "handle", return_value="") + @mock.patch.object(RunserverCommand, "handle", return_value="") + def test_params_to_runserver( + self, mock_runserver_handle, mock_loaddata_handle, mock_create_test_db + ): + call_command("testserver", "blah.json") mock_runserver_handle.assert_called_with( - addrport='', + addrport="", force_color=False, insecure_serving=False, no_color=False, @@ -1447,113 +1524,118 @@ class ColorCommand(BaseCommand): requires_system_checks = [] def handle(self, *args, **options): - self.stdout.write('Hello, world!', self.style.ERROR) - self.stderr.write('Hello, world!', self.style.ERROR) + self.stdout.write("Hello, world!", self.style.ERROR) + self.stderr.write("Hello, world!", self.style.ERROR) class CommandTypes(AdminScriptTestCase): "Tests for the various types of base command types that can be defined." + def setUp(self): super().setUp() - self.write_settings('settings.py') + self.write_settings("settings.py") def test_version(self): "version is handled as a special case" - args = ['version'] + args = ["version"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, get_version()) def test_version_alternative(self): "--version is equivalent to version" - args1, args2 = ['version'], ['--version'] + args1, args2 = ["version"], ["--version"] # It's possible one outputs on stderr and the other on stdout, hence the set self.assertEqual(set(self.run_manage(args1)), set(self.run_manage(args2))) def test_help(self): "help is handled as a special case" - args = ['help'] + args = ["help"] out, err = self.run_manage(args) - self.assertOutput(out, "Type 'manage.py help <subcommand>' for help on a specific subcommand.") - self.assertOutput(out, '[django]') - self.assertOutput(out, 'startapp') - self.assertOutput(out, 'startproject') + self.assertOutput( + out, "Type 'manage.py help <subcommand>' for help on a specific subcommand." + ) + self.assertOutput(out, "[django]") + self.assertOutput(out, "startapp") + self.assertOutput(out, "startproject") def test_help_commands(self): "help --commands shows the list of all available commands" - args = ['help', '--commands'] + args = ["help", "--commands"] out, err = self.run_manage(args) - self.assertNotInOutput(out, 'usage:') - self.assertNotInOutput(out, 'Options:') - self.assertNotInOutput(out, '[django]') - self.assertOutput(out, 'startapp') - self.assertOutput(out, 'startproject') - self.assertNotInOutput(out, '\n\n') + self.assertNotInOutput(out, "usage:") + self.assertNotInOutput(out, "Options:") + self.assertNotInOutput(out, "[django]") + self.assertOutput(out, "startapp") + self.assertOutput(out, "startproject") + self.assertNotInOutput(out, "\n\n") def test_help_alternative(self): "--help is equivalent to help" - args1, args2 = ['help'], ['--help'] + args1, args2 = ["help"], ["--help"] self.assertEqual(self.run_manage(args1), self.run_manage(args2)) def test_help_short_altert(self): "-h is handled as a short form of --help" - args1, args2 = ['--help'], ['-h'] + args1, args2 = ["--help"], ["-h"] self.assertEqual(self.run_manage(args1), self.run_manage(args2)) def test_specific_help(self): "--help can be used on a specific command" - args = ['check', '--help'] + args = ["check", "--help"] out, err = self.run_manage(args) self.assertNoOutput(err) # Command-specific options like --tag appear before options common to # all commands like --version. - tag_location = out.find('--tag') - version_location = out.find('--version') + tag_location = out.find("--tag") + version_location = out.find("--version") self.assertNotEqual(tag_location, -1) self.assertNotEqual(version_location, -1) self.assertLess(tag_location, version_location) - self.assertOutput(out, "Checks the entire Django project for potential problems.") + self.assertOutput( + out, "Checks the entire Django project for potential problems." + ) def test_help_default_options_with_custom_arguments(self): - args = ['base_command', '--help'] + args = ["base_command", "--help"] out, err = self.run_manage(args) self.assertNoOutput(err) expected_options = [ - '-h', - '--option_a OPTION_A', - '--option_b OPTION_B', - '--option_c OPTION_C', - '--version', - '-v {0,1,2,3}', - '--settings SETTINGS', - '--pythonpath PYTHONPATH', - '--traceback', - '--no-color', - '--force-color', - 'args ...', + "-h", + "--option_a OPTION_A", + "--option_b OPTION_B", + "--option_c OPTION_C", + "--version", + "-v {0,1,2,3}", + "--settings SETTINGS", + "--pythonpath PYTHONPATH", + "--traceback", + "--no-color", + "--force-color", + "args ...", ] for option in expected_options: - self.assertOutput(out, f'[{option}]') - self.assertOutput(out, '--option_a OPTION_A, -a OPTION_A') - self.assertOutput(out, '--option_b OPTION_B, -b OPTION_B') - self.assertOutput(out, '--option_c OPTION_C, -c OPTION_C') - self.assertOutput(out, '-v {0,1,2,3}, --verbosity {0,1,2,3}') + self.assertOutput(out, f"[{option}]") + self.assertOutput(out, "--option_a OPTION_A, -a OPTION_A") + self.assertOutput(out, "--option_b OPTION_B, -b OPTION_B") + self.assertOutput(out, "--option_c OPTION_C, -c OPTION_C") + self.assertOutput(out, "-v {0,1,2,3}, --verbosity {0,1,2,3}") def test_color_style(self): style = color.no_style() - self.assertEqual(style.ERROR('Hello, world!'), 'Hello, world!') + self.assertEqual(style.ERROR("Hello, world!"), "Hello, world!") - style = color.make_style('nocolor') - self.assertEqual(style.ERROR('Hello, world!'), 'Hello, world!') + style = color.make_style("nocolor") + self.assertEqual(style.ERROR("Hello, world!"), "Hello, world!") - style = color.make_style('dark') - self.assertIn('Hello, world!', style.ERROR('Hello, world!')) - self.assertNotEqual(style.ERROR('Hello, world!'), 'Hello, world!') + style = color.make_style("dark") + self.assertIn("Hello, world!", style.ERROR("Hello, world!")) + self.assertNotEqual(style.ERROR("Hello, world!"), "Hello, world!") # Default palette has color. - style = color.make_style('') - self.assertIn('Hello, world!', style.ERROR('Hello, world!')) - self.assertNotEqual(style.ERROR('Hello, world!'), 'Hello, world!') + style = color.make_style("") + self.assertIn("Hello, world!", style.ERROR("Hello, world!")) + self.assertNotEqual(style.ERROR("Hello, world!"), "Hello, world!") def test_command_color(self): out = StringIO() @@ -1561,13 +1643,13 @@ class CommandTypes(AdminScriptTestCase): command = ColorCommand(stdout=out, stderr=err) call_command(command) if color.supports_color(): - self.assertIn('Hello, world!\n', out.getvalue()) - self.assertIn('Hello, world!\n', err.getvalue()) - self.assertNotEqual(out.getvalue(), 'Hello, world!\n') - self.assertNotEqual(err.getvalue(), 'Hello, world!\n') + self.assertIn("Hello, world!\n", out.getvalue()) + self.assertIn("Hello, world!\n", err.getvalue()) + self.assertNotEqual(out.getvalue(), "Hello, world!\n") + self.assertNotEqual(err.getvalue(), "Hello, world!\n") else: - self.assertEqual(out.getvalue(), 'Hello, world!\n') - self.assertEqual(err.getvalue(), 'Hello, world!\n') + self.assertEqual(out.getvalue(), "Hello, world!\n") + self.assertEqual(err.getvalue(), "Hello, world!\n") def test_command_no_color(self): "--no-color prevent colorization of the output" @@ -1575,33 +1657,33 @@ class CommandTypes(AdminScriptTestCase): err = StringIO() command = ColorCommand(stdout=out, stderr=err, no_color=True) call_command(command) - self.assertEqual(out.getvalue(), 'Hello, world!\n') - self.assertEqual(err.getvalue(), 'Hello, world!\n') + self.assertEqual(out.getvalue(), "Hello, world!\n") + self.assertEqual(err.getvalue(), "Hello, world!\n") out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err) call_command(command, no_color=True) - self.assertEqual(out.getvalue(), 'Hello, world!\n') - self.assertEqual(err.getvalue(), 'Hello, world!\n') + self.assertEqual(out.getvalue(), "Hello, world!\n") + self.assertEqual(err.getvalue(), "Hello, world!\n") def test_force_color_execute(self): out = StringIO() err = StringIO() - with mock.patch.object(sys.stdout, 'isatty', lambda: False): + with mock.patch.object(sys.stdout, "isatty", lambda: False): command = ColorCommand(stdout=out, stderr=err) call_command(command, force_color=True) - self.assertEqual(out.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m') - self.assertEqual(err.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m') + self.assertEqual(out.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m") + self.assertEqual(err.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m") def test_force_color_command_init(self): out = StringIO() err = StringIO() - with mock.patch.object(sys.stdout, 'isatty', lambda: False): + with mock.patch.object(sys.stdout, "isatty", lambda: False): command = ColorCommand(stdout=out, stderr=err, force_color=True) call_command(command) - self.assertEqual(out.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m') - self.assertEqual(err.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m') + self.assertEqual(out.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m") + self.assertEqual(err.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m") def test_no_color_force_color_mutually_exclusive_execute(self): msg = "The --no-color and --force-color options can't be used together." @@ -1649,37 +1731,37 @@ class CommandTypes(AdminScriptTestCase): def test_base_command(self): "User BaseCommands can execute when a label is provided" - args = ['base_command', 'testlabel'] + args = ["base_command", "testlabel"] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels) def test_base_command_no_label(self): "User BaseCommands can execute when no labels are provided" - args = ['base_command'] + args = ["base_command"] expected_labels = "()" self._test_base_command(args, expected_labels) def test_base_command_multiple_label(self): "User BaseCommands can execute when no labels are provided" - args = ['base_command', 'testlabel', 'anotherlabel'] + args = ["base_command", "testlabel", "anotherlabel"] expected_labels = "('testlabel', 'anotherlabel')" self._test_base_command(args, expected_labels) def test_base_command_with_option(self): "User BaseCommands can execute with options when a label is provided" - args = ['base_command', 'testlabel', '--option_a=x'] + args = ["base_command", "testlabel", "--option_a=x"] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels, option_a="'x'") def test_base_command_with_options(self): "User BaseCommands can execute with multiple options when a label is provided" - args = ['base_command', 'testlabel', '-a', 'x', '--option_b=y'] + args = ["base_command", "testlabel", "-a", "x", "--option_b=y"] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels, option_a="'x'", option_b="'y'") def test_base_command_with_wrong_option(self): "User BaseCommands outputs command usage when wrong option is specified" - args = ['base_command', '--invalid'] + args = ["base_command", "--invalid"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "usage: manage.py base_command") @@ -1693,7 +1775,8 @@ class CommandTypes(AdminScriptTestCase): "options=[('force_color', False), ('no_color', False), " "('option_a', %s), ('option_b', %s), ('option_c', '3'), " "('pythonpath', None), ('settings', None), ('traceback', False), " - "('verbosity', 1)]") % (labels, option_a, option_b) + "('verbosity', 1)]" + ) % (labels, option_a, option_b) self.assertNoOutput(err) self.assertOutput(out, expected_out) @@ -1713,7 +1796,7 @@ class CommandTypes(AdminScriptTestCase): # If the Exception is not CommandError it should always # raise the original exception. with self.assertRaises(TypeError): - command.run_from_argv(['', '']) + command.run_from_argv(["", ""]) # If the Exception is CommandError and --traceback is not present # this command should raise a SystemExit and don't print any @@ -1721,7 +1804,7 @@ class CommandTypes(AdminScriptTestCase): command.execute = raise_command_error err.truncate(0) with self.assertRaises(SystemExit): - command.run_from_argv(['', '']) + command.run_from_argv(["", ""]) err_message = err.getvalue() self.assertNotIn("Traceback", err_message) self.assertIn("CommandError", err_message) @@ -1731,13 +1814,14 @@ class CommandTypes(AdminScriptTestCase): # were not a CommandError. err.truncate(0) with self.assertRaises(CommandError): - command.run_from_argv(['', '', '--traceback']) + command.run_from_argv(["", "", "--traceback"]) def test_run_from_argv_non_ascii_error(self): """ Non-ASCII message of CommandError does not raise any UnicodeDecodeError in run_from_argv. """ + def raise_command_error(*args, **kwargs): raise CommandError("Erreur personnalisée") @@ -1745,7 +1829,7 @@ class CommandTypes(AdminScriptTestCase): command.execute = raise_command_error with self.assertRaises(SystemExit): - command.run_from_argv(['', '']) + command.run_from_argv(["", ""]) def test_run_from_argv_closes_connections(self): """ @@ -1755,32 +1839,32 @@ class CommandTypes(AdminScriptTestCase): command = BaseCommand() command.check = lambda: [] command.handle = lambda *args, **kwargs: args - with mock.patch('django.core.management.base.connections') as mock_connections: - command.run_from_argv(['', '']) + with mock.patch("django.core.management.base.connections") as mock_connections: + command.run_from_argv(["", ""]) # Test connections have been closed self.assertTrue(mock_connections.close_all.called) def test_noargs(self): "NoArg Commands can be executed" - args = ['noargs_command'] + args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', None), " - "('traceback', False), ('verbosity', 1)]" + "('traceback', False), ('verbosity', 1)]", ) def test_noargs_with_args(self): "NoArg Commands raise an error if an argument is provided" - args = ['noargs_command', 'argument'] + args = ["noargs_command", "argument"] out, err = self.run_manage(args) self.assertOutput(err, "error: unrecognized arguments: argument") def test_app_command(self): "User AppCommands can execute when a single app name is provided" - args = ['app_command', 'auth'] + args = ["app_command", "auth"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=") @@ -1788,18 +1872,18 @@ class CommandTypes(AdminScriptTestCase): out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " - "('verbosity', 1)]" + "('verbosity', 1)]", ) def test_app_command_no_apps(self): "User AppCommands raise an error when no app name is provided" - args = ['app_command'] + args = ["app_command"] out, err = self.run_manage(args) - self.assertOutput(err, 'error: Enter at least one application label.') + self.assertOutput(err, "error: Enter at least one application label.") def test_app_command_multiple_apps(self): "User AppCommands raise an error when multiple app names are provided" - args = ['app_command', 'auth', 'contenttypes'] + args = ["app_command", "auth", "contenttypes"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=") @@ -1807,82 +1891,84 @@ class CommandTypes(AdminScriptTestCase): out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " - "('verbosity', 1)]" + "('verbosity', 1)]", + ) + self.assertOutput( + out, "EXECUTE:AppCommand name=django.contrib.contenttypes, options=" ) - self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.contenttypes, options=") self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " - "('verbosity', 1)]" + "('verbosity', 1)]", ) def test_app_command_invalid_app_label(self): "User AppCommands can execute when a single app name is provided" - args = ['app_command', 'NOT_AN_APP'] + args = ["app_command", "NOT_AN_APP"] out, err = self.run_manage(args) self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.") def test_app_command_some_invalid_app_labels(self): "User AppCommands can execute when some of the provided app names are invalid" - args = ['app_command', 'auth', 'NOT_AN_APP'] + args = ["app_command", "auth", "NOT_AN_APP"] out, err = self.run_manage(args) self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.") def test_label_command(self): "User LabelCommands can execute when a label is provided" - args = ['label_command', 'testlabel'] + args = ["label_command", "testlabel"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:LabelCommand label=testlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), ('settings', " - "None), ('traceback', False), ('verbosity', 1)]" + "None), ('traceback', False), ('verbosity', 1)]", ) def test_label_command_no_label(self): "User LabelCommands raise an error if no label is provided" - args = ['label_command'] + args = ["label_command"] out, err = self.run_manage(args) - self.assertOutput(err, 'Enter at least one label') + self.assertOutput(err, "Enter at least one label") def test_label_command_multiple_label(self): "User LabelCommands are executed multiple times if multiple labels are provided" - args = ['label_command', 'testlabel', 'anotherlabel'] + args = ["label_command", "testlabel", "anotherlabel"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:LabelCommand label=testlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), " - "('settings', None), ('traceback', False), ('verbosity', 1)]" + "('settings', None), ('traceback', False), ('verbosity', 1)]", ) self.assertOutput( out, "EXECUTE:LabelCommand label=anotherlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), " - "('settings', None), ('traceback', False), ('verbosity', 1)]" + "('settings', None), ('traceback', False), ('verbosity', 1)]", ) def test_suppress_base_options_command_help(self): - args = ['suppress_base_options_command', '--help'] + args = ["suppress_base_options_command", "--help"] out, err = self.run_manage(args) self.assertNoOutput(err) - self.assertOutput(out, 'Test suppress base options command.') - self.assertNotInOutput(out, 'input file') - self.assertOutput(out, '-h, --help') - self.assertNotInOutput(out, '--version') - self.assertNotInOutput(out, '--verbosity') - self.assertNotInOutput(out, '-v {0,1,2,3}') - self.assertNotInOutput(out, '--settings') - self.assertNotInOutput(out, '--pythonpath') - self.assertNotInOutput(out, '--traceback') - self.assertNotInOutput(out, '--no-color') - self.assertNotInOutput(out, '--force-color') + self.assertOutput(out, "Test suppress base options command.") + self.assertNotInOutput(out, "input file") + self.assertOutput(out, "-h, --help") + self.assertNotInOutput(out, "--version") + self.assertNotInOutput(out, "--verbosity") + self.assertNotInOutput(out, "-v {0,1,2,3}") + self.assertNotInOutput(out, "--settings") + self.assertNotInOutput(out, "--pythonpath") + self.assertNotInOutput(out, "--traceback") + self.assertNotInOutput(out, "--no-color") + self.assertNotInOutput(out, "--force-color") def test_suppress_base_options_command_defaults(self): - args = ['suppress_base_options_command'] + args = ["suppress_base_options_command"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( @@ -1890,30 +1976,37 @@ class CommandTypes(AdminScriptTestCase): "EXECUTE:SuppressBaseOptionsCommand options=[('file', None), " "('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), " - "('traceback', False), ('verbosity', 1)]" + "('traceback', False), ('verbosity', 1)]", ) class Discovery(SimpleTestCase): - def test_precedence(self): """ Apps listed first in INSTALLED_APPS have precedence. """ - with self.settings(INSTALLED_APPS=['admin_scripts.complex_app', - 'admin_scripts.simple_app', - 'django.contrib.auth', - 'django.contrib.contenttypes']): + with self.settings( + INSTALLED_APPS=[ + "admin_scripts.complex_app", + "admin_scripts.simple_app", + "django.contrib.auth", + "django.contrib.contenttypes", + ] + ): out = StringIO() - call_command('duplicate', stdout=out) - self.assertEqual(out.getvalue().strip(), 'complex_app') - with self.settings(INSTALLED_APPS=['admin_scripts.simple_app', - 'admin_scripts.complex_app', - 'django.contrib.auth', - 'django.contrib.contenttypes']): + call_command("duplicate", stdout=out) + self.assertEqual(out.getvalue().strip(), "complex_app") + with self.settings( + INSTALLED_APPS=[ + "admin_scripts.simple_app", + "admin_scripts.complex_app", + "django.contrib.auth", + "django.contrib.contenttypes", + ] + ): out = StringIO() - call_command('duplicate', stdout=out) - self.assertEqual(out.getvalue().strip(), 'simple_app') + call_command("duplicate", stdout=out) + self.assertEqual(out.getvalue().strip(), "simple_app") class ArgumentOrder(AdminScriptTestCase): @@ -1925,35 +2018,54 @@ class ArgumentOrder(AdminScriptTestCase): passed to the command parser, which extracts commands of interest to the individual command. """ + def setUp(self): super().setUp() - self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) - self.write_settings('alternate_settings.py') + self.write_settings( + "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] + ) + self.write_settings("alternate_settings.py") def test_setting_then_option(self): - """ Options passed after settings are correctly handled. """ - args = ['base_command', 'testlabel', '--settings=alternate_settings', '--option_a=x'] + """Options passed after settings are correctly handled.""" + args = [ + "base_command", + "testlabel", + "--settings=alternate_settings", + "--option_a=x", + ] self._test(args) def test_setting_then_short_option(self): - """ Short options passed after settings are correctly handled. """ - args = ['base_command', 'testlabel', '--settings=alternate_settings', '-a', 'x'] + """Short options passed after settings are correctly handled.""" + args = ["base_command", "testlabel", "--settings=alternate_settings", "-a", "x"] self._test(args) def test_option_then_setting(self): - """ Options passed before settings are correctly handled. """ - args = ['base_command', 'testlabel', '--option_a=x', '--settings=alternate_settings'] + """Options passed before settings are correctly handled.""" + args = [ + "base_command", + "testlabel", + "--option_a=x", + "--settings=alternate_settings", + ] self._test(args) def test_short_option_then_setting(self): - """ Short options passed before settings are correctly handled. """ - args = ['base_command', 'testlabel', '-a', 'x', '--settings=alternate_settings'] + """Short options passed before settings are correctly handled.""" + args = ["base_command", "testlabel", "-a", "x", "--settings=alternate_settings"] self._test(args) def test_option_then_setting_then_option(self): - """ Options are correctly handled when they are passed before and after - a setting. """ - args = ['base_command', 'testlabel', '--option_a=x', '--settings=alternate_settings', '--option_b=y'] + """Options are correctly handled when they are passed before and after + a setting.""" + args = [ + "base_command", + "testlabel", + "--option_a=x", + "--settings=alternate_settings", + "--option_b=y", + ] self._test(args, option_b="'y'") def _test(self, args, option_b="'2'"): @@ -1965,7 +2077,7 @@ class ArgumentOrder(AdminScriptTestCase): "('force_color', False), ('no_color', False), ('option_a', 'x'), " "('option_b', %s), ('option_c', '3'), ('pythonpath', None), " "('settings', 'alternate_settings'), ('traceback', False), " - "('verbosity', 1)]" % option_b + "('verbosity', 1)]" % option_b, ) @@ -1975,35 +2087,35 @@ class ExecuteFromCommandLine(SimpleTestCase): Program name is computed from the execute_from_command_line()'s argv argument, not sys.argv. """ - args = ['help', 'shell'] + args = ["help", "shell"] with captured_stdout() as out, captured_stderr() as err: - with mock.patch('sys.argv', [None] + args): - execute_from_command_line(['django-admin'] + args) - self.assertIn('usage: django-admin shell', out.getvalue()) - self.assertEqual(err.getvalue(), '') + with mock.patch("sys.argv", [None] + args): + execute_from_command_line(["django-admin"] + args) + self.assertIn("usage: django-admin shell", out.getvalue()) + self.assertEqual(err.getvalue(), "") -@override_settings(ROOT_URLCONF='admin_scripts.urls') +@override_settings(ROOT_URLCONF="admin_scripts.urls") class StartProject(LiveServerTestCase, AdminScriptTestCase): available_apps = [ - 'admin_scripts', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', + "admin_scripts", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", ] def test_wrong_args(self): "Make sure passing the wrong kinds of arguments outputs an error and prints usage" - out, err = self.run_django_admin(['startproject']) + out, err = self.run_django_admin(["startproject"]) self.assertNoOutput(out) self.assertOutput(err, "usage:") self.assertOutput(err, "You must provide a project name.") def test_simple_project(self): "Make sure the startproject management command creates a project" - args = ['startproject', 'testproject'] - testproject_dir = os.path.join(self.test_dir, 'testproject') + args = ["startproject", "testproject"] + testproject_dir = os.path.join(self.test_dir, "testproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) @@ -2021,16 +2133,16 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): def test_invalid_project_name(self): "Make sure the startproject management command validates a project name" - for bad_name in ('7testproject', '../testproject'): + for bad_name in ("7testproject", "../testproject"): with self.subTest(project_name=bad_name): - args = ['startproject', bad_name] + args = ["startproject", bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "Error: '%s' is not a valid project name. Please make " - "sure the name is a valid identifier." % bad_name + "sure the name is a valid identifier." % bad_name, ) self.assertFalse(os.path.exists(testproject_dir)) @@ -2039,8 +2151,8 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): startproject validates that project name doesn't clash with existing Python modules. """ - bad_name = 'os' - args = ['startproject', bad_name] + bad_name = "os" + args = ["startproject", bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) @@ -2048,19 +2160,19 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): err, "CommandError: 'os' conflicts with the name of an existing " "Python module and cannot be used as a project name. Please try " - "another name." + "another name.", ) self.assertFalse(os.path.exists(testproject_dir)) def test_simple_project_different_directory(self): "Make sure the startproject management command creates a project in a specific directory" - args = ['startproject', 'testproject', 'othertestproject'] - testproject_dir = os.path.join(self.test_dir, 'othertestproject') + args = ["startproject", "testproject", "othertestproject"] + testproject_dir = os.path.join(self.test_dir, "othertestproject") os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) - self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'manage.py'))) + self.assertTrue(os.path.exists(os.path.join(testproject_dir, "manage.py"))) # running again.. out, err = self.run_django_admin(args) @@ -2068,133 +2180,160 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): self.assertOutput( err, "already exists. Overlaying a project into an existing directory " - "won't replace conflicting files." + "won't replace conflicting files.", ) def test_custom_project_template(self): "Make sure the startproject management command is able to use a different project template" - template_path = os.path.join(custom_templates_dir, 'project_template') - args = ['startproject', '--template', template_path, 'customtestproject'] - testproject_dir = os.path.join(self.test_dir, 'customtestproject') + template_path = os.path.join(custom_templates_dir, "project_template") + args = ["startproject", "--template", template_path, "customtestproject"] + testproject_dir = os.path.join(self.test_dir, "customtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) - self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'additional_dir'))) + self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir"))) def test_template_dir_with_trailing_slash(self): "Ticket 17475: Template dir passed has a trailing path separator" - template_path = os.path.join(custom_templates_dir, 'project_template' + os.sep) - args = ['startproject', '--template', template_path, 'customtestproject'] - testproject_dir = os.path.join(self.test_dir, 'customtestproject') + template_path = os.path.join(custom_templates_dir, "project_template" + os.sep) + args = ["startproject", "--template", template_path, "customtestproject"] + testproject_dir = os.path.join(self.test_dir, "customtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) - self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'additional_dir'))) + self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir"))) def test_custom_project_template_from_tarball_by_path(self): "Make sure the startproject management command is able to use a different project template from a tarball" - template_path = os.path.join(custom_templates_dir, 'project_template.tgz') - args = ['startproject', '--template', template_path, 'tarballtestproject'] - testproject_dir = os.path.join(self.test_dir, 'tarballtestproject') + template_path = os.path.join(custom_templates_dir, "project_template.tgz") + args = ["startproject", "--template", template_path, "tarballtestproject"] + testproject_dir = os.path.join(self.test_dir, "tarballtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) - self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) + self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py"))) def test_custom_project_template_from_tarball_to_alternative_location(self): "Startproject can use a project template from a tarball and create it in a specified location" - template_path = os.path.join(custom_templates_dir, 'project_template.tgz') - args = ['startproject', '--template', template_path, 'tarballtestproject', 'altlocation'] - testproject_dir = os.path.join(self.test_dir, 'altlocation') + template_path = os.path.join(custom_templates_dir, "project_template.tgz") + args = [ + "startproject", + "--template", + template_path, + "tarballtestproject", + "altlocation", + ] + testproject_dir = os.path.join(self.test_dir, "altlocation") os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) - self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) + self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py"))) def test_custom_project_template_from_tarball_by_url(self): """ The startproject management command is able to use a different project template from a tarball via a URL. """ - template_url = '%s/custom_templates/project_template.tgz' % self.live_server_url + template_url = "%s/custom_templates/project_template.tgz" % self.live_server_url - args = ['startproject', '--template', template_url, 'urltestproject'] - testproject_dir = os.path.join(self.test_dir, 'urltestproject') + args = ["startproject", "--template", template_url, "urltestproject"] + testproject_dir = os.path.join(self.test_dir, "urltestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) - self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) + self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py"))) def test_custom_project_template_from_tarball_by_url_django_user_agent(self): user_agent = None def serve_template(request, *args, **kwargs): nonlocal user_agent - user_agent = request.headers['User-Agent'] + user_agent = request.headers["User-Agent"] return serve(request, *args, **kwargs) old_urlpatterns = urls.urlpatterns[:] try: urls.urlpatterns += [ path( - 'user_agent_check/<path:path>', + "user_agent_check/<path:path>", serve_template, - {'document_root': os.path.join(urls.here, 'custom_templates')}, + {"document_root": os.path.join(urls.here, "custom_templates")}, ), ] - template_url = f'{self.live_server_url}/user_agent_check/project_template.tgz' - args = ['startproject', '--template', template_url, 'urltestproject'] + template_url = ( + f"{self.live_server_url}/user_agent_check/project_template.tgz" + ) + args = ["startproject", "--template", template_url, "urltestproject"] _, err = self.run_django_admin(args) self.assertNoOutput(err) - self.assertIn('Django/%s' % get_version(), user_agent) + self.assertIn("Django/%s" % get_version(), user_agent) finally: urls.urlpatterns = old_urlpatterns def test_project_template_tarball_url(self): "Startproject management command handles project template tar/zip balls from non-canonical urls" - template_url = '%s/custom_templates/project_template.tgz/' % self.live_server_url + template_url = ( + "%s/custom_templates/project_template.tgz/" % self.live_server_url + ) - args = ['startproject', '--template', template_url, 'urltestproject'] - testproject_dir = os.path.join(self.test_dir, 'urltestproject') + args = ["startproject", "--template", template_url, "urltestproject"] + testproject_dir = os.path.join(self.test_dir, "urltestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) - self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) + self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py"))) def test_file_without_extension(self): "Make sure the startproject management command is able to render custom files" - template_path = os.path.join(custom_templates_dir, 'project_template') - args = ['startproject', '--template', template_path, 'customtestproject', '-e', 'txt', '-n', 'Procfile'] - testproject_dir = os.path.join(self.test_dir, 'customtestproject') + template_path = os.path.join(custom_templates_dir, "project_template") + args = [ + "startproject", + "--template", + template_path, + "customtestproject", + "-e", + "txt", + "-n", + "Procfile", + ] + testproject_dir = os.path.join(self.test_dir, "customtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) - self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'additional_dir'))) - base_path = os.path.join(testproject_dir, 'additional_dir') - for f in ('Procfile', 'additional_file.py', 'requirements.txt'): + self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir"))) + base_path = os.path.join(testproject_dir, "additional_dir") + for f in ("Procfile", "additional_file.py", "requirements.txt"): self.assertTrue(os.path.exists(os.path.join(base_path, f))) with open(os.path.join(base_path, f)) as fh: - self.assertEqual(fh.read().strip(), '# some file for customtestproject test project') + self.assertEqual( + fh.read().strip(), "# some file for customtestproject test project" + ) def test_custom_project_template_context_variables(self): "Make sure template context variables are rendered with proper values" - template_path = os.path.join(custom_templates_dir, 'project_template') - args = ['startproject', '--template', template_path, 'another_project', 'project_dir'] - testproject_dir = os.path.join(self.test_dir, 'project_dir') + template_path = os.path.join(custom_templates_dir, "project_template") + args = [ + "startproject", + "--template", + template_path, + "another_project", + "project_dir", + ] + testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) - test_manage_py = os.path.join(testproject_dir, 'manage.py') + test_manage_py = os.path.join(testproject_dir, "manage.py") with open(test_manage_py) as fp: content = fp.read() self.assertIn("project_name = 'another_project'", content) @@ -2203,18 +2342,23 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): def test_no_escaping_of_project_variables(self): "Make sure template context variables are not html escaped" # We're using a custom command so we need the alternate settings - self.write_settings('alternate_settings.py') - template_path = os.path.join(custom_templates_dir, 'project_template') + self.write_settings("alternate_settings.py") + template_path = os.path.join(custom_templates_dir, "project_template") args = [ - 'custom_startproject', '--template', template_path, - 'another_project', 'project_dir', '--extra', '<&>', - '--settings=alternate_settings', + "custom_startproject", + "--template", + template_path, + "another_project", + "project_dir", + "--extra", + "<&>", + "--settings=alternate_settings", ] - testproject_dir = os.path.join(self.test_dir, 'project_dir') + testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) out, err = self.run_manage(args) self.assertNoOutput(err) - test_manage_py = os.path.join(testproject_dir, 'additional_dir', 'extra.py') + test_manage_py = os.path.join(testproject_dir, "additional_dir", "extra.py") with open(test_manage_py) as fp: content = fp.read() self.assertIn("<&>", content) @@ -2224,12 +2368,22 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): Make sure an exception is raised when the provided destination directory doesn't exist """ - template_path = os.path.join(custom_templates_dir, 'project_template') - args = ['startproject', '--template', template_path, 'yet_another_project', 'project_dir2'] - testproject_dir = os.path.join(self.test_dir, 'project_dir2') + template_path = os.path.join(custom_templates_dir, "project_template") + args = [ + "startproject", + "--template", + template_path, + "yet_another_project", + "project_dir2", + ] + testproject_dir = os.path.join(self.test_dir, "project_dir2") out, err = self.run_django_admin(args) self.assertNoOutput(out) - self.assertOutput(err, "Destination directory '%s' does not exist, please create it first." % testproject_dir) + self.assertOutput( + err, + "Destination directory '%s' does not exist, please create it first." + % testproject_dir, + ) self.assertFalse(os.path.exists(testproject_dir)) def test_custom_project_template_with_non_ascii_templates(self): @@ -2237,35 +2391,42 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): The startproject management command is able to render templates with non-ASCII content. """ - template_path = os.path.join(custom_templates_dir, 'project_template') - args = ['startproject', '--template', template_path, '--extension=txt', 'customtestproject'] - testproject_dir = os.path.join(self.test_dir, 'customtestproject') + template_path = os.path.join(custom_templates_dir, "project_template") + args = [ + "startproject", + "--template", + template_path, + "--extension=txt", + "customtestproject", + ] + testproject_dir = os.path.join(self.test_dir, "customtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) - path = os.path.join(testproject_dir, 'ticket-18091-non-ascii-template.txt') - with open(path, encoding='utf-8') as f: - self.assertEqual(f.read().splitlines(False), [ - 'Some non-ASCII text for testing ticket #18091:', - 'üäö €']) + path = os.path.join(testproject_dir, "ticket-18091-non-ascii-template.txt") + with open(path, encoding="utf-8") as f: + self.assertEqual( + f.read().splitlines(False), + ["Some non-ASCII text for testing ticket #18091:", "üäö €"], + ) def test_custom_project_template_hidden_directory_default_excluded(self): """Hidden directories are excluded by default.""" - template_path = os.path.join(custom_templates_dir, 'project_template') + template_path = os.path.join(custom_templates_dir, "project_template") args = [ - 'startproject', - '--template', + "startproject", + "--template", template_path, - 'custom_project_template_hidden_directories', - 'project_dir', + "custom_project_template_hidden_directories", + "project_dir", ] - testproject_dir = os.path.join(self.test_dir, 'project_dir') + testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) _, err = self.run_django_admin(args) self.assertNoOutput(err) - hidden_dir = os.path.join(testproject_dir, '.hidden') + hidden_dir = os.path.join(testproject_dir, ".hidden") self.assertIs(os.path.exists(hidden_dir), False) def test_custom_project_template_hidden_directory_included(self): @@ -2273,25 +2434,25 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): Template context variables in hidden directories are rendered, if not excluded. """ - template_path = os.path.join(custom_templates_dir, 'project_template') - project_name = 'custom_project_template_hidden_directories_included' + template_path = os.path.join(custom_templates_dir, "project_template") + project_name = "custom_project_template_hidden_directories_included" args = [ - 'startproject', - '--template', + "startproject", + "--template", template_path, project_name, - 'project_dir', - '--exclude', + "project_dir", + "--exclude", ] - testproject_dir = os.path.join(self.test_dir, 'project_dir') + testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) _, err = self.run_django_admin(args) self.assertNoOutput(err) - render_py_path = os.path.join(testproject_dir, '.hidden', 'render.py') + render_py_path = os.path.join(testproject_dir, ".hidden", "render.py") with open(render_py_path) as fp: self.assertIn( - f'# The {project_name} should be rendered.', + f"# The {project_name} should be rendered.", fp.read(), ) @@ -2300,29 +2461,29 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): Excluded directories (in addition to .git and __pycache__) are not included in the project. """ - template_path = os.path.join(custom_templates_dir, 'project_template') - project_name = 'custom_project_with_excluded_directories' + template_path = os.path.join(custom_templates_dir, "project_template") + project_name = "custom_project_with_excluded_directories" args = [ - 'startproject', - '--template', + "startproject", + "--template", template_path, project_name, - 'project_dir', - '--exclude', - 'additional_dir', - '-x', - '.hidden', + "project_dir", + "--exclude", + "additional_dir", + "-x", + ".hidden", ] - testproject_dir = os.path.join(self.test_dir, 'project_dir') + testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) _, err = self.run_django_admin(args) self.assertNoOutput(err) excluded_directories = [ - '.hidden', - 'additional_dir', - '.git', - '__pycache__', + ".hidden", + "additional_dir", + ".git", + "__pycache__", ] for directory in excluded_directories: self.assertIs( @@ -2333,19 +2494,19 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): self.assertIs(os.path.exists(not_excluded), True) @unittest.skipIf( - sys.platform == 'win32', - 'Windows only partially supports umasks and chmod.', + sys.platform == "win32", + "Windows only partially supports umasks and chmod.", ) @unittest.skipUnless(PY39, "subprocess.run()'s umask was added in Python 3.9.") def test_honor_umask(self): - _, err = self.run_django_admin(['startproject', 'testproject'], umask=0o077) + _, err = self.run_django_admin(["startproject", "testproject"], umask=0o077) self.assertNoOutput(err) - testproject_dir = os.path.join(self.test_dir, 'testproject') + testproject_dir = os.path.join(self.test_dir, "testproject") self.assertIs(os.path.isdir(testproject_dir), True) tests = [ - (['manage.py'], 0o700), - (['testproject'], 0o700), - (['testproject', 'settings.py'], 0o600), + (["manage.py"], 0o700), + (["testproject"], 0o700), + (["testproject", "settings.py"], 0o600), ] for paths, expected_mode in tests: file_path = os.path.join(testproject_dir, *paths) @@ -2357,19 +2518,18 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): class StartApp(AdminScriptTestCase): - def test_invalid_name(self): """startapp validates that app name is a valid Python identifier.""" - for bad_name in ('7testproject', '../testproject'): + for bad_name in ("7testproject", "../testproject"): with self.subTest(app_name=bad_name): - args = ['startapp', bad_name] + args = ["startapp", bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: '{}' is not a valid app name. Please make " - "sure the name is a valid identifier.".format(bad_name) + "sure the name is a valid identifier.".format(bad_name), ) self.assertFalse(os.path.exists(testproject_dir)) @@ -2378,8 +2538,8 @@ class StartApp(AdminScriptTestCase): startapp validates that app name doesn't clash with existing Python modules. """ - bad_name = 'os' - args = ['startapp', bad_name] + bad_name = "os" + args = ["startapp", bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) @@ -2387,55 +2547,61 @@ class StartApp(AdminScriptTestCase): err, "CommandError: 'os' conflicts with the name of an existing " "Python module and cannot be used as an app name. Please try " - "another name." + "another name.", ) self.assertFalse(os.path.exists(testproject_dir)) def test_invalid_target_name(self): - for bad_target in ('invalid.dir_name', '7invalid_dir_name', '.invalid_dir_name'): + for bad_target in ( + "invalid.dir_name", + "7invalid_dir_name", + ".invalid_dir_name", + ): with self.subTest(bad_target): - _, err = self.run_django_admin(['startapp', 'app', bad_target]) + _, err = self.run_django_admin(["startapp", "app", bad_target]) self.assertOutput( err, "CommandError: '%s' is not a valid app directory. Please " - "make sure the directory is a valid identifier." % bad_target + "make sure the directory is a valid identifier." % bad_target, ) def test_importable_target_name(self): - _, err = self.run_django_admin(['startapp', 'app', 'os']) + _, err = self.run_django_admin(["startapp", "app", "os"]) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing Python " "module and cannot be used as an app directory. Please try " - "another directory." + "another directory.", ) def test_trailing_slash_in_target_app_directory_name(self): - app_dir = os.path.join(self.test_dir, 'apps', 'app1') + app_dir = os.path.join(self.test_dir, "apps", "app1") os.makedirs(app_dir) - _, err = self.run_django_admin(['startapp', 'app', os.path.join('apps', 'app1', '')]) + _, err = self.run_django_admin( + ["startapp", "app", os.path.join("apps", "app1", "")] + ) self.assertNoOutput(err) - self.assertIs(os.path.exists(os.path.join(app_dir, 'apps.py')), True) + self.assertIs(os.path.exists(os.path.join(app_dir, "apps.py")), True) def test_overlaying_app(self): # Use a subdirectory so it is outside the PYTHONPATH. - os.makedirs(os.path.join(self.test_dir, 'apps/app1')) - self.run_django_admin(['startapp', 'app1', 'apps/app1']) - out, err = self.run_django_admin(['startapp', 'app2', 'apps/app1']) + os.makedirs(os.path.join(self.test_dir, "apps/app1")) + self.run_django_admin(["startapp", "app1", "apps/app1"]) + out, err = self.run_django_admin(["startapp", "app2", "apps/app1"]) self.assertOutput( err, "already exists. Overlaying an app into an existing directory " - "won't replace conflicting files." + "won't replace conflicting files.", ) def test_template(self): - out, err = self.run_django_admin(['startapp', 'new_app']) + out, err = self.run_django_admin(["startapp", "new_app"]) self.assertNoOutput(err) - app_path = os.path.join(self.test_dir, 'new_app') + app_path = os.path.join(self.test_dir, "new_app") self.assertIs(os.path.exists(app_path), True) - with open(os.path.join(app_path, 'apps.py')) as f: + with open(os.path.join(app_path, "apps.py")) as f: content = f.read() - self.assertIn('class NewAppConfig(AppConfig)', content) + self.assertIn("class NewAppConfig(AppConfig)", content) self.assertIn( "default_auto_field = 'django.db.models.BigAutoField'", content, @@ -2448,31 +2614,35 @@ class DiffSettings(AdminScriptTestCase): def test_basic(self): """Runs without error and emits settings diff.""" - self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'}) - args = ['diffsettings', '--settings=settings_to_diff'] + self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'}) + args = ["diffsettings", "--settings=settings_to_diff"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "FOO = 'bar' ###") # Attributes from django.conf.Settings don't appear. - self.assertNotInOutput(out, 'is_overridden = ') + self.assertNotInOutput(out, "is_overridden = ") def test_settings_configured(self): - out, err = self.run_manage(['diffsettings'], manage_py='configured_settings_manage.py') + out, err = self.run_manage( + ["diffsettings"], manage_py="configured_settings_manage.py" + ) self.assertNoOutput(err) - self.assertOutput(out, 'CUSTOM = 1 ###\nDEBUG = True') + self.assertOutput(out, "CUSTOM = 1 ###\nDEBUG = True") # Attributes from django.conf.UserSettingsHolder don't appear. - self.assertNotInOutput(out, 'default_settings = ') + self.assertNotInOutput(out, "default_settings = ") def test_dynamic_settings_configured(self): # Custom default settings appear. - out, err = self.run_manage(['diffsettings'], manage_py='configured_dynamic_settings_manage.py') + out, err = self.run_manage( + ["diffsettings"], manage_py="configured_dynamic_settings_manage.py" + ) self.assertNoOutput(err) self.assertOutput(out, "FOO = 'bar' ###") def test_all(self): """The all option also shows settings with the default value.""" - self.write_settings('settings_to_diff.py', sdict={'STATIC_URL': 'None'}) - args = ['diffsettings', '--settings=settings_to_diff', '--all'] + self.write_settings("settings_to_diff.py", sdict={"STATIC_URL": "None"}) + args = ["diffsettings", "--settings=settings_to_diff", "--all"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "### STATIC_URL = None") @@ -2482,17 +2652,27 @@ class DiffSettings(AdminScriptTestCase): The --default option specifies an alternate settings module for comparison. """ - self.write_settings('settings_default.py', sdict={'FOO': '"foo"', 'BAR': '"bar1"'}) - self.write_settings('settings_to_diff.py', sdict={'FOO': '"foo"', 'BAR': '"bar2"'}) - out, err = self.run_manage(['diffsettings', '--settings=settings_to_diff', '--default=settings_default']) + self.write_settings( + "settings_default.py", sdict={"FOO": '"foo"', "BAR": '"bar1"'} + ) + self.write_settings( + "settings_to_diff.py", sdict={"FOO": '"foo"', "BAR": '"bar2"'} + ) + out, err = self.run_manage( + [ + "diffsettings", + "--settings=settings_to_diff", + "--default=settings_default", + ] + ) self.assertNoOutput(err) self.assertNotInOutput(out, "FOO") self.assertOutput(out, "BAR = 'bar2'") def test_unified(self): """--output=unified emits settings diff in unified mode.""" - self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'}) - args = ['diffsettings', '--settings=settings_to_diff', '--output=unified'] + self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'}) + args = ["diffsettings", "--settings=settings_to_diff", "--output=unified"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "+ FOO = 'bar'") @@ -2505,8 +2685,13 @@ class DiffSettings(AdminScriptTestCase): --output=unified --all emits settings diff in unified mode and includes settings with the default value. """ - self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'}) - args = ['diffsettings', '--settings=settings_to_diff', '--output=unified', '--all'] + self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'}) + args = [ + "diffsettings", + "--settings=settings_to_diff", + "--output=unified", + "--all", + ] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, " APPEND_SLASH = True") @@ -2519,14 +2704,14 @@ class Dumpdata(AdminScriptTestCase): def setUp(self): super().setUp() - self.write_settings('settings.py') + self.write_settings("settings.py") def test_pks_parsing(self): """Regression for #20509 Test would raise an exception rather than printing an error message. """ - args = ['dumpdata', '--pks=1'] + args = ["dumpdata", "--pks=1"] out, err = self.run_manage(args) self.assertOutput(err, "You can only use --pks option with one model") self.assertNoOutput(out) @@ -2536,23 +2721,26 @@ class MainModule(AdminScriptTestCase): """python -m django works like django-admin.""" def test_program_name_in_help(self): - out, err = self.run_test(['-m', 'django', 'help']) - self.assertOutput(out, "Type 'python -m django help <subcommand>' for help on a specific subcommand.") + out, err = self.run_test(["-m", "django", "help"]) + self.assertOutput( + out, + "Type 'python -m django help <subcommand>' for help on a specific subcommand.", + ) class DjangoAdminSuggestions(AdminScriptTestCase): def setUp(self): super().setUp() - self.write_settings('settings.py') + self.write_settings("settings.py") def test_suggestions(self): - args = ['rnserver', '--settings=test_project.settings'] + args = ["rnserver", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'rnserver'. Did you mean runserver?") def test_no_suggestions(self): - args = ['abcdef', '--settings=test_project.settings'] + args = ["abcdef", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(out) - self.assertNotInOutput(err, 'Did you mean') + self.assertNotInOutput(err, "Did you mean") diff --git a/tests/admin_scripts/urls.py b/tests/admin_scripts/urls.py index b5bb443926..a6cc7fe1b5 100644 --- a/tests/admin_scripts/urls.py +++ b/tests/admin_scripts/urls.py @@ -6,6 +6,9 @@ from django.views.static import serve here = os.path.dirname(__file__) urlpatterns = [ - path('custom_templates/<path:path>', serve, { - 'document_root': os.path.join(here, 'custom_templates')}), + path( + "custom_templates/<path:path>", + serve, + {"document_root": os.path.join(here, "custom_templates")}, + ), ] |
