Repository: django/django
File: tests/migrations/test_loader.py (Python)

Code before:
            compileall.compile_dir(migration_dir, force=True, quiet=1, legacy=True)
            for name in os.listdir(migration_dir):
                if name.endswith(".py"):
                    os.remove(os.path.join(migration_dir, name))
            loader = MigrationLoader(connection)
            self.assertIn(("migrations", "0001_initial"), loader.disk_migrations)

    def test_invalid(self):
        """
        MigrationLoader reraises ImportErrors caused by "bad magic number" pyc
        files with a more helpful message.
        """
        with self.temporary_migration_module(
            module="migrations.test_migrations_bad_pyc"
        ) as migration_dir:
            # The -tpl suffix is to avoid the pyc exclusion in MANIFEST.in.
            os.rename(
                os.path.join(migration_dir, "0001_initial.pyc-tpl"),
                os.path.join(migration_dir, "0001_initial.pyc"),
            )
            msg = (
                r"Couldn't import '\w+.migrations.0001_initial' as it appears "
                "to be a stale .pyc file."
            )
            with self.assertRaisesRegex(ImportError, msg):
                MigrationLoader(connection)


Review comment (suggestion):
This is a bit brittle. I don't know that it's worth accounting for, but for MongoDB we have this patch:
```diff
diff --git a/tests/runtests.py b/tests/runtests.py
index 500908978a..b72b9b7de1 100755
--- a/tests/runtests.py
+++ b/tests/runtests.py
@@ -14,6 +14,7 @@ import warnings
 from pathlib import Path
 
 import django_mongodb_backend
+from bson import ObjectId
 
 try:
     import django
@@ -247,7 +248,7 @@ def setup_collect_tests(start_at, start_after, test_labels=None):
         }
     ]
     settings.LANGUAGE_CODE = "en"
-    settings.SITE_ID = 1
+    settings.SITE_ID = ObjectId("000000000000000000000001")
     settings.MIDDLEWARE = ALWAYS_MIDDLEWARE
     settings.MIGRATION_MODULES = {
         # This lets us skip creating migrations for the test models as many of
```
The written migration file doesn't have the necessary import:
```
  File "/home/tim/code/django/tests/tmpf6bu1e4h.py", line 151, in <module>
    SITE_ID = ObjectId('000000000000000000000001')
              ^^^^^^^^
NameError: name 'ObjectId' is not defined. Did you mean: 'object'?
```

Code after:
        [ ] 0002_squashed_initial <- replaces app1.0001
            depends on app1.0001_squashed_initial & app2.0001_squashed_initial
        app2
        [ ] 0001_squashed_initial <- replaces app2.0001

        When loading app1's migrations, if 0002_squashed_initial was first:
        {'0002_squashed_initial', '0001_initial', '0001_squashed_initial'}
        Then CircularDependencyError was raised, but it's resolvable as:
        {'0001_initial', '0001_squashed_initial', '0002_squashed_initial'}
        """
        # Create a test settings file to provide to the subprocess.
        MIGRATION_MODULES = {
            "app1": "migrations.test_migrations_squashed_replaced_order.app1",
            "app2": "migrations.test_migrations_squashed_replaced_order.app2",
        }
        INSTALLED_APPS = [
            "migrations.test_migrations_squashed_replaced_order.app1",
            "migrations.test_migrations_squashed_replaced_order.app2",
        ]
        tests_dir = Path(__file__).parent.parent
        with tempfile.NamedTemporaryFile(
            mode="w", encoding="utf-8", suffix=".py", dir=tests_dir, delete=False
        ) as test_settings:
            for attr, value in settings._wrapped.__dict__.items():
                if attr.isupper():
                    test_settings.write(f"{attr} = {value!r}\n")
            # Provide overrides here, instead of via decorators.
            test_settings.write(f"DATABASES = {settings.DATABASES}\n")
            test_settings.write(f"MIGRATION_MODULES = {MIGRATION_MODULES}\n")
            # Isolate away other test apps.
            test_settings.write(
                "INSTALLED_APPS=[a for a in INSTALLED_APPS if a.startswith('django')]\n"
            )
            test_settings.write(f"INSTALLED_APPS += {INSTALLED_APPS}\n")
        test_settings_name = test_settings.name
        self.addCleanup(os.remove, test_settings_name)

        test_environ = os.environ.copy()
        test_environ["PYTHONPATH"] = str(tests_dir)
        # Ensure deterministic failures.
        test_environ["PYTHONHASHSEED"] = "1"

        args = [
            sys.executable,
            "-m",
            "django",
            "showmigrations",
            "app1",
            "--skip-checks",
            "--settings",
            Path(test_settings_name).stem,