Ticket #1763: unittest.patch

File unittest.patch, 18.7 KB (added by crankycoder@…, 19 years ago)

Patch to Django to let you replace the django.db module cleanly to facilitate unit testing of applications

  • django/db/models/base.py

     
    77from django.db.models.related import RelatedObject
    88from django.db.models.query import orderlist2sql, delete_objects
    99from django.db.models.options import Options, AdminOptions
    10 from django.db import connection, backend, transaction
     10from django.db import backend, transaction
     11import django.db
    1112from django.db.models import signals
    1213from django.db.models.loading import register_models
    1314from django.dispatch import dispatcher
     
    146147        dispatcher.send(signal=signals.pre_save, sender=self.__class__, instance=self)
    147148
    148149        non_pks = [f for f in self._meta.fields if not f.primary_key]
    149         cursor = connection.cursor()
     150        cursor = django.db.connection.cursor()
    150151
    151152        # First, try an UPDATE. If that doesn't update anything, do an INSERT.
    152153        pk_val = self._get_pk_val()
     
    353354        rel = rel_field.rel.to
    354355        m2m_table = rel_field.m2m_db_table()
    355356        this_id = self._get_pk_val()
    356         cursor = connection.cursor()
     357        cursor = django.db.connection.cursor()
    357358        cursor.execute("DELETE FROM %s WHERE %s = %%s" % \
    358359            (backend.quote_name(m2m_table),
    359360            backend.quote_name(rel_field.m2m_column_name())), [this_id])
     
    371372# ORDERING METHODS #########################
    372373
    373374def method_set_order(ordered_obj, self, id_list):
    374     cursor = connection.cursor()
     375    cursor = django.db.connection.cursor()
    375376    # Example: "UPDATE poll_choices SET _order = %s WHERE poll_id = %s AND id = %s"
    376377    sql = "UPDATE %s SET %s = %%s WHERE %s = %%s AND %s = %%s" % \
    377378        (backend.quote_name(ordered_obj.db_table), backend.quote_name('_order'),
     
    382383    transaction.commit_unless_managed()
    383384
    384385def method_get_order(ordered_obj, self):
    385     cursor = connection.cursor()
     386    cursor = django.db.connection.cursor()
    386387    # Example: "SELECT id FROM poll_choices WHERE poll_id = %s ORDER BY _order"
    387388    sql = "SELECT %s FROM %s WHERE %s = %%s ORDER BY %s" % \
    388389        (backend.quote_name(ordered_obj._meta.pk.column),
  • django/db/models/manager.py

     
    11from django.utils.functional import curry
    2 from django.db import backend, connection
     2from django.db import backend
    33from django.db.models.query import QuerySet
    44from django.dispatch import dispatcher
    55from django.db.models import signals
  • django/db/models/fields/related.py

     
    1 from django.db import backend, connection, transaction
     1from django.db import backend, transaction
    22from django.db.models import signals
    33from django.db.models.fields import AutoField, Field, IntegerField, get_ul_class
    44from django.db.models.related import RelatedObject
     
    77from django.core import validators
    88from django import forms
    99from django.dispatch import dispatcher
     10import django.db
    1011
    1112# For Python 2.3
    1213if not hasattr(__builtins__, 'set'):
     
    282283            # source_col_name: the PK colname in join_table for the source object
    283284            # target_col_name: the PK colname in join_table for the target object
    284285            # *objs - objects to add
    285             from django.db import connection
    286286
    287287            # Add the newly created or already existing objects to the join table.
    288288            # First find out which items are already added, to avoid adding them twice
    289289            new_ids = set([obj._get_pk_val() for obj in objs])
    290             cursor = connection.cursor()
     290            cursor = django.db.connection.cursor()
    291291            cursor.execute("SELECT %s FROM %s WHERE %s = %%s AND %s IN (%s)" % \
    292292                (target_col_name, self.join_table, source_col_name,
    293293                target_col_name, ",".join(['%s'] * len(new_ids))),
     
    308308            # source_col_name: the PK colname in join_table for the source object
    309309            # target_col_name: the PK colname in join_table for the target object
    310310            # *objs - objects to remove
    311             from django.db import connection
    312311
    313312            for obj in objs:
    314313                if not isinstance(obj, self.model):
    315314                    raise ValueError, "objects to remove() must be %s instances" % self.model._meta.object_name
    316315            # Remove the specified objects from the join table
    317             cursor = connection.cursor()
     316            cursor = django.db.connection.cursor()
    318317            for obj in objs:
    319318                cursor.execute("DELETE FROM %s WHERE %s = %%s AND %s = %%s" % \
    320319                    (self.join_table, source_col_name, target_col_name),
     
    323322
    324323        def _clear_items(self, source_col_name):
    325324            # source_col_name: the PK colname in join_table for the source object
    326             from django.db import connection
    327             cursor = connection.cursor()
     325            cursor = django.db.connection.cursor()
    328326            cursor.execute("DELETE FROM %s WHERE %s = %%s" % \
    329327                (self.join_table, source_col_name),
    330328                [self._pk_val])
  • django/db/models/__init__.py

     
    11from django.conf import settings
    22from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
    33from django.core import validators
    4 from django.db import backend, connection
     4from django.db import backend
    55from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models
    66from django.db.models.query import Q
    77from django.db.models.manager import Manager
  • django/db/models/query.py

     
    1 from django.db import backend, connection, transaction
     1from django.db import backend, transaction
    22from django.db.models.fields import DateField, FieldDoesNotExist
    33from django.db.models import signals
    44from django.dispatch import dispatcher
    55from django.utils.datastructures import SortedDict
    6 
     6import django.db
    77import operator
    88
    99# For Python 2.3
     
    152152        # undefined, so we convert it to a list of tuples.
    153153        extra_select = self._select.items()
    154154
    155         cursor = connection.cursor()
     155        cursor = django.db.connection.cursor()
    156156        select, sql, params = self._get_sql_clause()
    157157        cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params)
    158158        fill_cache = self._select_related
     
    178178        counter._limit = None
    179179        counter._select_related = False
    180180        select, sql, params = counter._get_sql_clause()
    181         cursor = connection.cursor()
     181        cursor = django.db.connection.cursor()
    182182        cursor.execute("SELECT COUNT(*)" + sql, params)
    183183        return cursor.fetchone()[0]
    184184
     
    457457            columns = [f.column for f in self.model._meta.fields]
    458458            field_names = [f.attname for f in self.model._meta.fields]
    459459
    460         cursor = connection.cursor()
     460        cursor = django.db.connection.cursor()
    461461        select, sql, params = self._get_sql_clause()
    462462        select = ['%s.%s' % (backend.quote_name(self.model._meta.db_table), backend.quote_name(c)) for c in columns]
    463463        cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params)
     
    484484        sql = 'SELECT %s %s GROUP BY 1 ORDER BY 1 %s' % \
    485485            (backend.get_date_trunc_sql(self._kind, '%s.%s' % (backend.quote_name(self.model._meta.db_table),
    486486            backend.quote_name(self._field.column))), sql, self._order)
    487         cursor = connection.cursor()
     487        cursor = django.db.connection.cursor()
    488488        cursor.execute(sql, params)
    489489        # We have to manually run typecast_timestamp(str()) on the results, because
    490490        # MySQL doesn't automatically cast the result of date functions as datetime
     
    829829    ordered_classes = seen_objs.keys()
    830830    ordered_classes.reverse()
    831831
    832     cursor = connection.cursor()
     832    cursor = django.db.connection.cursor()
    833833
    834834    for cls in ordered_classes:
    835835        seen_objs[cls] = seen_objs[cls].items()
  • django/db/transaction.py

     
    1313"""
    1414
    1515import thread
    16 from django.db import connection
     16import django.db
    1717from django.conf import settings
    1818
    1919class TransactionManagementError(Exception):
     
    120120    if top:
    121121        top[-1] = flag
    122122        if not flag and is_dirty():
    123             connection._commit()
     123            django.db.connection._commit()
    124124            set_clean()
    125125    else:
    126126        raise TransactionManagementError("This code isn't under transaction management")
     
    130130    Commits changes if the system is not in managed transaction mode.
    131131    """
    132132    if not is_managed():
    133         connection._commit()
     133        django.db.connection._commit()
    134134    else:
    135135        set_dirty()
    136136
     
    139139    Rolls back changes if the system is not in managed transaction mode.
    140140    """
    141141    if not is_managed():
    142         connection._rollback()
     142        django.db.connection._rollback()
    143143    else:
    144144        set_dirty()
    145145
     
    147147    """
    148148    Does the commit itself and resets the dirty flag.
    149149    """
    150     connection._commit()
     150    django.db.connection._commit()
    151151    set_clean()
    152152
    153153def rollback():
    154154    """
    155155    This function does the rollback itself and resets the dirty flag.
    156156    """
    157     connection._rollback()
     157    django.db.connection._rollback()
    158158    set_clean()
    159159
    160160##############
  • django/core/context_processors.py

     
    2525    context_extras = {}
    2626    if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
    2727        context_extras['debug'] = True
    28         from django.db import connection
    29         context_extras['sql_queries'] = connection.queries
     28        import django.db
     29        context_extras['sql_queries'] = django.db.connection.queries
    3030    return context_extras
    3131
    3232def i18n(request):
  • django/core/management.py

     
    6363
    6464def _get_table_list():
    6565    "Gets a list of all db tables that are physically installed."
    66     from django.db import connection, get_introspection_module
    67     cursor = connection.cursor()
     66    from django.db import get_introspection_module
     67    cursor = django.db.connection.cursor()
    6868    return get_introspection_module().get_table_list(cursor)
    6969
    7070# If the foreign key points to an AutoField, a PositiveIntegerField or a
     
    244244
    245245def get_sql_delete(app):
    246246    "Returns a list of the DROP TABLE SQL statements for the given app."
    247     from django.db import backend, connection, models, get_introspection_module
     247    from django.db import backend, models, get_introspection_module
    248248    introspection = get_introspection_module()
    249249
    250250    # This should work even if a connecton isn't available
    251251    try:
    252         cursor = connection.cursor()
     252        cursor = django.db.connection.cursor()
    253253    except:
    254254        cursor = None
    255255
     
    308308    # directly into a database client, to avoid locking issues.
    309309    if cursor:
    310310        cursor.close()
    311         connection.close()
     311        django.db.connection.close()
    312312
    313313    return output[::-1] # Reverse it, to deal with table dependencies.
    314314get_sql_delete.help_doc = "Prints the DROP TABLE SQL statements for the given app name(s)."
     
    409409
    410410def syncdb():
    411411    "Creates the database tables for all apps in INSTALLED_APPS whose tables haven't already been created."
    412     from django.db import connection, transaction, models, get_creation_module
     412    from django.db import transaction, models, get_creation_module
    413413    from django.db.models import signals
    414414    from django.conf import settings
    415415    from django.dispatch import dispatcher
     
    429429
    430430    data_types = get_creation_module().DATA_TYPES
    431431
    432     cursor = connection.cursor()
     432    cursor = django.db.connection.cursor()
    433433
    434434    # Get a list of all existing database tables,
    435435    # so we know what needs to be added.
     
    543543
    544544def install(app):
    545545    "Executes the equivalent of 'get_sql_all' in the current database."
    546     from django.db import connection, transaction
     546    from django.db import transaction
    547547
    548548    app_name = app.__name__.split('.')[-2]
    549549
     
    555555    sql_list = get_sql_all(app)
    556556
    557557    try:
    558         cursor = connection.cursor()
     558        cursor = django.db.connection.cursor()
    559559        for sql in sql_list:
    560560            cursor.execute(sql)
    561561    except Exception, e:
     
    573573
    574574def reset(app):
    575575    "Executes the equivalent of 'get_sql_reset' in the current database."
    576     from django.db import connection, transaction
     576    from django.db import transaction
    577577    from cStringIO import StringIO
    578578    app_name = app.__name__.split('.')[-2]
    579579
     
    591591Type 'yes' to continue, or 'no' to cancel: """)
    592592    if confirm == 'yes':
    593593        try:
    594             cursor = connection.cursor()
     594            cursor = django.db.connection.cursor()
    595595            for sql in sql_list:
    596596                cursor.execute(sql)
    597597        except Exception, e:
     
    670670
    671671def inspectdb():
    672672    "Generator that introspects the tables in the given database name and returns a Django model, one line at a time."
    673     from django.db import connection, get_introspection_module
     673    from django.db import get_introspection_module
    674674    from django.conf import settings
    675675    import keyword
    676676
     
    680680        object_name = table_name.title().replace('_', '')
    681681        return object_name.endswith('s') and object_name[:-1] or object_name
    682682
    683     cursor = connection.cursor()
     683    cursor = django.db.connection.cursor()
    684684    yield "# This is an auto-generated Django model module."
    685685    yield "# You'll have to do the following manually to clean this up:"
    686686    yield "#     * Rearrange models' order"
     
    999999
    10001000def createcachetable(tablename):
    10011001    "Creates the table needed to use the SQL cache backend"
    1002     from django.db import backend, connection, transaction, get_creation_module, models
     1002    from django.db import backend, transaction, get_creation_module, models
    10031003    data_types = get_creation_module().DATA_TYPES
    10041004    fields = (
    10051005        # "key" is a reserved word in MySQL, so use "cache_key" instead.
     
    10261026    for i, line in enumerate(table_output):
    10271027        full_statement.append('    %s%s' % (line, i < len(table_output)-1 and ',' or ''))
    10281028    full_statement.append(');')
    1029     curs = connection.cursor()
     1029    curs = django.db.connection.cursor()
    10301030    curs.execute("\n".join(full_statement))
    10311031    for statement in index_output:
    10321032        curs.execute(statement)
  • django/core/cache/backends/db.py

     
    11"Database cache backend."
    22
    33from django.core.cache.backends.base import BaseCache
    4 from django.db import connection, transaction
     4from django.db import transaction
    55import base64, time
    66from datetime import datetime
    77try:
     
    2525            self._cull_frequency = 3
    2626
    2727    def get(self, key, default=None):
    28         cursor = connection.cursor()
     28        cursor = django.db.connection.cursor()
    2929        cursor.execute("SELECT cache_key, value, expires FROM %s WHERE cache_key = %%s" % self._table, [key])
    3030        row = cursor.fetchone()
    3131        if row is None:
     
    4040    def set(self, key, value, timeout=None):
    4141        if timeout is None:
    4242            timeout = self.default_timeout
    43         cursor = connection.cursor()
     43        cursor = django.db.connection.cursor()
    4444        cursor.execute("SELECT COUNT(*) FROM %s" % self._table)
    4545        num = cursor.fetchone()[0]
    4646        now = datetime.now().replace(microsecond=0)
     
    6161            transaction.commit_unless_managed()
    6262
    6363    def delete(self, key):
    64         cursor = connection.cursor()
     64        cursor = django.db.connection.cursor()
    6565        cursor.execute("DELETE FROM %s WHERE cache_key = %%s" % self._table, [key])
    6666        transaction.commit_unless_managed()
    6767
    6868    def has_key(self, key):
    69         cursor = connection.cursor()
     69        cursor = django.db.connection.cursor()
    7070        cursor.execute("SELECT cache_key FROM %s WHERE cache_key = %%s" % self._table, [key])
    7171        return cursor.fetchone() is not None
    7272
  • django/contrib/auth/models.py

     
    11from django.core import validators
    2 from django.db import backend, connection, models
     2from django.db import backend, models
     3import django.db
    34from django.contrib.contenttypes.models import ContentType
    45from django.utils.translation import gettext_lazy as _
    56import datetime
     
    130131        "Returns a list of permission strings that this user has through his/her groups."
    131132        if not hasattr(self, '_group_perm_cache'):
    132133            import sets
    133             cursor = connection.cursor()
     134            cursor = django.db.connection.cursor()
    134135            # The SQL below works out to the following, after DB quoting:
    135136            # cursor.execute("""
    136137            #     SELECT ct."app_label", p."codename"
  • django/bin/daily_cleanup.py

     
    11"Daily cleanup file"
    22
    3 from django.db import backend, connection, transaction
     3from django.db import backend, transaction
     4import django.db
    45
    56DOCUMENTATION_DIRECTORY = '/home/html/documentation/'
    67
    78def clean_up():
    89    # Clean up old database records
    9     cursor = connection.cursor()
     10    cursor = django.db.connection.cursor()
    1011    cursor.execute("DELETE FROM %s WHERE %s < NOW()" % \
    1112        (backend.quote_name('core_sessions'), backend.quote_name('expire_date')))
    1213    cursor.execute("DELETE FROM %s WHERE %s < NOW() - INTERVAL '1 week'" % \
Back to Top