|
19 | 19 | pytest_plugins = ["sentry.testutils.pytest"] |
20 | 20 |
|
21 | 21 |
|
| 22 | +@pytest.fixture(scope="session") |
| 23 | +def django_db_setup( |
| 24 | + request: pytest.FixtureRequest, |
| 25 | + django_test_environment: None, |
| 26 | + django_db_blocker, |
| 27 | + django_db_use_migrations: bool, |
| 28 | + django_db_keepdb: bool, |
| 29 | + django_db_createdb: bool, |
| 30 | + django_db_modify_db_settings: None, |
| 31 | +): |
| 32 | + """ |
| 33 | + Debuggable wrapper around pytest-django's django_db_setup. |
| 34 | +
|
| 35 | + Enable with SENTRY_DEBUG_XDIST_DB=1 to print worker-aware DB settings after |
| 36 | + pytest-django applies xdist suffixes, but before setup_databases() runs. |
| 37 | + """ |
| 38 | + from django.conf import settings |
| 39 | + from django.test.utils import setup_databases, teardown_databases |
| 40 | + |
| 41 | + if os.environ.get("SENTRY_DEBUG_XDIST_DB") == "1": |
| 42 | + reporter = request.config.pluginmanager.get_plugin("terminalreporter") |
| 43 | + worker_id = getattr(request.config, "workerinput", {}).get("workerid", "master") |
| 44 | + if reporter: |
| 45 | + reporter.write_line(f"[db-debug] worker={worker_id} pre-setup settings.DATABASES") |
| 46 | + for alias, db in settings.DATABASES.items(): |
| 47 | + test_name = db.get("TEST", {}).get("NAME", "(not set)") |
| 48 | + if reporter: |
| 49 | + reporter.write_line( |
| 50 | + f"[db-debug] worker={worker_id} settings {alias}: NAME={db['NAME']} TEST.NAME={test_name}" |
| 51 | + ) |
| 52 | + |
| 53 | + for alias in connections: |
| 54 | + conn = connections[alias] |
| 55 | + test_name = conn.settings_dict.get("TEST", {}).get("NAME", "(not set)") |
| 56 | + if reporter: |
| 57 | + reporter.write_line( |
| 58 | + f"[db-debug] worker={worker_id} connection {alias}: " |
| 59 | + f"NAME={conn.settings_dict['NAME']} TEST.NAME={test_name}" |
| 60 | + ) |
| 61 | + |
| 62 | + setup_databases_args = {} |
| 63 | + if not django_db_use_migrations: |
| 64 | + from pytest_django.fixtures import _disable_migrations |
| 65 | + |
| 66 | + _disable_migrations() |
| 67 | + |
| 68 | + if django_db_keepdb and not django_db_createdb: |
| 69 | + setup_databases_args["keepdb"] = True |
| 70 | + |
| 71 | + with django_db_blocker.unblock(): |
| 72 | + db_cfg = setup_databases( |
| 73 | + verbosity=request.config.option.verbose, |
| 74 | + interactive=False, |
| 75 | + **setup_databases_args, |
| 76 | + ) |
| 77 | + |
| 78 | + yield |
| 79 | + |
| 80 | + if not django_db_keepdb: |
| 81 | + with django_db_blocker.unblock(): |
| 82 | + teardown_databases(db_cfg, verbosity=request.config.option.verbose) |
| 83 | + |
| 84 | + |
22 | 85 | # XXX: The below code is vendored code from https://github.com/utgwkk/pytest-github-actions-annotate-failures |
23 | 86 | # so that we can add support for pytest_rerunfailures |
24 | 87 | # retried tests will no longer be annotated in GHA |
|
0 commit comments