Skip to content

Instantly share code, notes, and snippets.

@ionelmc ionelmc/conftest.py
Created May 21, 2018

Embed
What would you like to do?
pytest-django support for subprocesses
@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
You can’t perform that action at this time.