From 88aae4022664843366508020d934fe9a8d70e51d Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Sun, 14 Mar 2021 09:30:49 -0700 Subject: [PATCH] Run tests against read-only 'dashboard' connection, refs #18 --- conftest.py | 10 ++++++++++ django_sql_dashboard/views.py | 5 ++++- pytest_use_postgresql.py | 1 + test_project/config/settings.py | 4 +++- 4 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 conftest.py diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..99f73d3 --- /dev/null +++ b/conftest.py @@ -0,0 +1,10 @@ +import pytest + + +@pytest.fixture(scope="session") +def django_db_modify_db_settings(): + from django.conf import settings + + settings.DATABASES["dashboard"]["OPTIONS"] = { + "options": "-c default_transaction_read_only=on -c statement_timeout=100" + } diff --git a/django_sql_dashboard/views.py b/django_sql_dashboard/views.py index 6dfdf6d..61870cd 100644 --- a/django_sql_dashboard/views.py +++ b/django_sql_dashboard/views.py @@ -2,8 +2,9 @@ import time from django.contrib.auth.decorators import permission_required -from django.db import connection, transaction +from django.db import connections, transaction from django.shortcuts import get_object_or_404, render +from django.conf import settings from .models import Dashboard @@ -18,6 +19,8 @@ def _dashboard_index( request, sql_queries, title=None, description=None, saved_dashboard=False ): query_results = [] + alias = getattr(settings, "DASHBOARD_DB_ALIAS", "dashboard") + connection = connections[alias] with connection.cursor() as tables_cursor: tables_cursor.execute( """ diff --git a/pytest_use_postgresql.py b/pytest_use_postgresql.py index d7fbfef..b04196f 100644 --- a/pytest_use_postgresql.py +++ b/pytest_use_postgresql.py @@ -12,6 +12,7 @@ def pytest_load_initial_conftests(early_config, parser, args): os.environ["DJANGO_SETTINGS_MODULE"] = early_config.getini("DJANGO_SETTINGS_MODULE") settings.DATABASES["default"] = parse(_POSTGRESQL.url()) + settings.DATABASES["dashboard"] = parse(_POSTGRESQL.url()) def pytest_unconfigure(config): diff --git a/test_project/config/settings.py b/test_project/config/settings.py index c5f1e55..7f48c34 100644 --- a/test_project/config/settings.py +++ b/test_project/config/settings.py @@ -55,7 +55,9 @@ WSGI_APPLICATION = "config.wsgi.application" -DATABASES = {"default": dj_database_url.config()} +DATABASES = { + "default": dj_database_url.config(), +} # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators