Created
May 21, 2018 14:49
-
-
Save ionelmc/d0cdc24a9c6171c3fcc8a7b0a52d3547 to your computer and use it in GitHub Desktop.
pytest-django support for subprocesses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@pytest.fixture(scope='session') | |
def django_db_setup(request, | |
django_test_environment, | |
django_db_blocker, | |
django_db_use_migrations, | |
django_db_keepdb, | |
django_db_modify_db_settings): | |
import pytest_django.compat | |
def teardown_databases(db_cfg, verbosity, _teardown_databases=pytest_django.compat.teardown_databases): | |
""" | |
Some nasty stuff to kill the hanging connections. Sometimes teardown can't be performed cause of these hanging | |
connections. | |
""" | |
from django.db import connections | |
conn = connections['default'] | |
cursor = conn.cursor() | |
cursor.execute(""" | |
SELECT pg_terminate_backend(pg_stat_activity.pid) | |
FROM pg_stat_activity | |
WHERE pg_stat_activity.datname = '%s' | |
AND pid <> pg_backend_pid(); | |
""" % conn.creation._get_test_db_name()) | |
return _teardown_databases(db_cfg, verbosity) | |
pytest_django.compat.teardown_databases = teardown_databases | |
try: | |
from pytest_django.fixtures import django_db_setup | |
return django_db_setup(request, | |
django_test_environment, | |
django_db_blocker, | |
django_db_use_migrations, | |
django_db_keepdb, | |
django_db_modify_db_settings) | |
finally: | |
from django.db import connections | |
from django.conf import settings | |
conn = connections['default'] | |
db_name = conn.creation._get_test_db_name() | |
conn.force_debug_cursor = True | |
os.environ['DJANGO_DATABASE_NAME'] = db_name # assuming subprocesses inherit env (they should!) | |
# this will make them (eg: celery) use the right db. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment