diff --git a/django/core/management/commands/sqlmigrate.py b/django/core/management/commands/sqlmigrate.py index 3e3151f0cf..076499b3e2 100644 --- a/django/core/management/commands/sqlmigrate.py +++ b/django/core/management/commands/sqlmigrate.py @@ -32,10 +32,9 @@ class Command(BaseCommand): ) def execute(self, *args, **options): - # sqlmigrate doesn't support coloring its output but we need to force - # no_color=True so that the BEGIN/COMMIT statements added by - # output_transaction don't get colored either. - options["no_color"] = True + # sqlmigrate doesn't support coloring its output, so make the + # BEGIN/COMMIT statements added by output_transaction colorless also. + self.style.SQL_KEYWORD = lambda noop: noop return super().execute(*args, **options) def handle(self, *args, **options): diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py index 6c3c67fd61..18f7e1e157 100644 --- a/tests/migrations/test_commands.py +++ b/tests/migrations/test_commands.py @@ -9,6 +9,7 @@ from unittest import mock from django.apps import apps from django.core.management import CommandError, call_command +from django.core.management.base import SystemCheckError from django.core.management.commands.makemigrations import ( Command as MakeMigrationsCommand, ) @@ -859,7 +860,7 @@ class MigrateTests(MigrationTestBase): sqlmigrate outputs forward looking SQL. """ out = io.StringIO() - call_command("sqlmigrate", "migrations", "0001", stdout=out) + call_command("sqlmigrate", "migrations", "0001", stdout=out, no_color=True) lines = out.getvalue().splitlines() @@ -921,7 +922,14 @@ class MigrateTests(MigrationTestBase): call_command("migrate", "migrations", verbosity=0) out = io.StringIO() - call_command("sqlmigrate", "migrations", "0001", stdout=out, backwards=True) + call_command( + "sqlmigrate", + "migrations", + "0001", + stdout=out, + backwards=True, + no_color=True, + ) lines = out.getvalue().splitlines() try: @@ -1098,6 +1106,30 @@ class MigrateTests(MigrationTestBase): ], ) + @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) + def test_sqlmigrate_transaction_keywords_not_colorized(self): + out = io.StringIO() + with mock.patch( + "django.core.management.color.supports_color", lambda *args: True + ): + call_command("sqlmigrate", "migrations", "0001", stdout=out, no_color=False) + self.assertNotIn("\x1b", out.getvalue()) + + @override_settings( + MIGRATION_MODULES={"migrations": "migrations.test_migrations_no_operations"}, + INSTALLED_APPS=["django.contrib.auth"], + ) + def test_sqlmigrate_system_checks_colorized(self): + with ( + mock.patch( + "django.core.management.color.supports_color", lambda *args: True + ), + self.assertRaisesMessage(SystemCheckError, "\x1b"), + ): + call_command( + "sqlmigrate", "migrations", "0001", skip_checks=False, no_color=False + ) + @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.migrated_app",