Created
February 2, 2010 12:08
-
-
Save hotsyk/292608 to your computer and use it in GitHub Desktop.
This file contains 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
''' | |
# $Id: db_mock.py 149 2007-08-30 08:12:24Z akhavr $ | |
# Copyright (C) 2007 KDS Software Group http://www.kds.com.ua/ | |
''' | |
import copy | |
import django.conf | |
from django.core.management import call_command | |
from django.db import backend, connection | |
import django.db.backends.sqlite3.base as django_sqlite | |
from django.db.backends import util | |
try: | |
from sqlite3 import dbapi2 as sqlite | |
except ImportError: | |
from pysqlite2 import dbapi2 as sqlite | |
def syncdb(): | |
'initializes django db' | |
call_command('syncdb') | |
def temp_django_db_conn(): | |
'create temporary django db connection' | |
sqlite_conn = django_sqlite.DatabaseWrapper() | |
sqlite_conn.connection = sqlite.connect( | |
database=':memory:', | |
detect_types=sqlite.PARSE_DECLTYPES | sqlite.PARSE_COLNAMES) | |
sqlite_conn.connection.text_factory = str | |
# define some functions that are missing from sqlite | |
sqlite_conn.connection.create_function('concat', 2, | |
lambda *args: ''.join(args)) | |
return sqlite_conn | |
def subst_django_db_conn(new_conn): | |
''' | |
substitute django db connection by <new_conn> | |
warning: black magic involved | |
''' | |
# black magic ;) | |
klass = connection.__class__ | |
orig_conn = klass.__new__(klass) | |
orig_conn.__dict__.update(connection.__dict__) | |
connection.__class__ = new_conn.__class__ | |
connection.__dict__.update(new_conn.__dict__) | |
return orig_conn | |
class DbMock: | |
def setup(self): | |
'db mockup setup' | |
self.sqlite_conn = temp_django_db_conn() | |
self.orig_conn = subst_django_db_conn(self.sqlite_conn) | |
self.orig_db_engine = django.conf.settings.DATABASE_ENGINE | |
django.conf.settings.DATABASE_ENGINE = 'sqlite3' | |
self.orig_db_name = django.conf.settings.DATABASE_NAME | |
django.conf.settings.DATABASE_NAME = ':memory:' | |
try: | |
self.supports_constraints = backend.supports_constraints | |
except AttributeError: | |
pass | |
backend.supports_constraints = False | |
self.operator_mapping = copy.deepcopy(backend.DatabaseWrapper.operators) | |
backend.DatabaseWrapper.operators.update( | |
django_sqlite.DatabaseWrapper.operators) | |
syncdb() | |
return | |
def teardown(self): | |
'db mockup teardown' | |
subst_django_db_conn(self.orig_conn) | |
django.conf.settings.DATABASE_ENGINE = self.orig_db_engine | |
django.conf.settings.DATABASE_NAME = self.orig_db_name | |
try: | |
backend.supports_constraints = self.supports_constraints | |
except AttributeError: | |
pass | |
backend.OPERATOR_MAPPING = self.operator_mapping | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment