Skip to content

Instantly share code, notes, and snippets.

@smcoll
Created July 19, 2017 15:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smcoll/bb2533e4b53ae570e11eb2ab011b887b to your computer and use it in GitHub Desktop.
Save smcoll/bb2533e4b53ae570e11eb2ab011b887b to your computer and use it in GitHub Desktop.
Django test runner which installs HSTORE extension
class TestRunner(runner.DiscoverRunner):
""" When migrations are disabled for the test runner, the `pre_migrate` signal
does not emit. So we need another hook for installing the extension. Prior to
Django 1.9, the `pre_syncdb` signal worked for that.
"""
def setup_databases(self, **kwargs):
"""
Always create PostgreSQL HSTORE extension if it doesn't already exist
on the database before syncing the database. Requires PostgreSQL >= 9.1
"""
def wrap_create_test_db(function):
def decorated_create_test_db(self, verbosity, autoclobber, keepdb):
test_database_name = function(self, verbosity, autoclobber, keepdb)
self.connection.close()
self.connection.settings_dict["NAME"] = test_database_name
cursor = self.connection.cursor()
cursor.execute('CREATE EXTENSION IF NOT EXISTS hstore')
return test_database_name
return decorated_create_test_db
# Overriding class method from outside is ugly, but it's just for unit
# testing anyway.
from django.db.backends.base import creation
creation.BaseDatabaseCreation._create_test_db = wrap_create_test_db(
creation.BaseDatabaseCreation._create_test_db
)
return super(TestRunner, self).setup_databases(**kwargs)
@Wallar1
Copy link

Wallar1 commented Jun 15, 2020

Thank you for this 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment