Ticket #8138: r9640based8138.diff

File r9640based8138.diff, 8.0 KB (added by Karen Tracey, 16 years ago)

Updated diff to more current trunk level

  • django/test/client.py

     
    1919from django.utils.encoding import smart_str
    2020from django.utils.http import urlencode
    2121from django.utils.itercompat import is_iterable
     22from django.db import transaction
    2223
    2324BOUNDARY = 'BoUnDaRyStRiNg'
    2425MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY
     
    6162
    6263        signals.request_started.send(sender=self.__class__)
    6364        try:
     65            transaction.enter_transaction_management()
     66            transaction.managed(True)         
    6467            request = WSGIRequest(environ)
    6568            response = self.get_response(request)
     69            transaction.commit()
     70            transaction.leave_transaction_management()
    6671
    6772            # Apply response middleware.
    6873            for middleware_method in self._response_middleware:
     
    172177        Obtains the current session variables.
    173178        """
    174179        if 'django.contrib.sessions' in settings.INSTALLED_APPS:
     180            # If a session db change hangs in a transaction, commit,
     181            # just to be sure.
     182            if transaction.is_dirty():
     183                transaction.commit()
    175184            engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
    176185            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
    177186            if cookie:
  • django/test/testcases.py

     
    88from django.core.management import call_command
    99from django.core.urlresolvers import clear_url_caches
    1010from django.db import transaction
     11from django.db.models.signals import post_save
    1112from django.http import QueryDict
    1213from django.test import _doctest as doctest
    1314from django.test.client import Client
     
    168169        # Rollback, in case of database errors. Otherwise they'd have
    169170        # side effects on other tests.
    170171        transaction.rollback_unless_managed()
     172       
     173    def run(self, test, compileflags=None, out=None, clear_globs=True):
     174        """
     175        Wraps the parent run() and encloses it in a transaction.
     176        """
     177        transaction.enter_transaction_management()
     178        transaction.managed(True)
     179        result = doctest.DocTestRunner.run(self, test, compileflags, out, clear_globs)
     180        transaction.rollback()
     181        transaction.leave_transaction_management()
     182        return result
    171183
    172 class TestCase(unittest.TestCase):
     184class TransactionTestCase(unittest.TestCase):
    173185    def _pre_setup(self):
    174186        """Performs any pre-test setup. This includes:
    175187
     
    180192              ROOT_URLCONF with it.
    181193            * Clearing the mail test outbox.
    182194        """
     195        self._fixture_setup()
     196        self._urlconf_setup()
     197        mail.outbox = []
     198
     199    def _fixture_setup(self):
    183200        call_command('flush', verbosity=0, interactive=False)
    184201        if hasattr(self, 'fixtures'):
    185202            # We have to use this slightly awkward syntax due to the fact
    186203            # that we're using *args and **kwargs together.
    187204            call_command('loaddata', *self.fixtures, **{'verbosity': 0})
     205
     206    def _urlconf_setup(self):
    188207        if hasattr(self, 'urls'):
    189208            self._old_root_urlconf = settings.ROOT_URLCONF
    190209            settings.ROOT_URLCONF = self.urls
    191210            clear_url_caches()
    192         mail.outbox = []
    193211
    194212    def __call__(self, result=None):
    195213        """
     
    206224            import sys
    207225            result.addError(self, sys.exc_info())
    208226            return
    209         super(TestCase, self).__call__(result)
     227        super(TransactionTestCase, self).__call__(result)       
    210228        try:
    211229            self._post_teardown()
    212230        except (KeyboardInterrupt, SystemExit):
     
    221239
    222240            * Putting back the original ROOT_URLCONF if it was changed.
    223241        """
     242        self._fixture_teardown()
     243        self._urlconf_teardown()
     244
     245    def _fixture_teardown(self):
     246        pass
     247
     248    def _urlconf_teardown(self):       
    224249        if hasattr(self, '_old_root_urlconf'):
    225250            settings.ROOT_URLCONF = self._old_root_urlconf
    226251            clear_url_caches()
     
    354379        self.failIf(template_name in template_names,
    355380            (u"Template '%s' was used unexpectedly in rendering the"
    356381             u" response") % template_name)
     382
     383class TestCase(TransactionTestCase):
     384    """
     385    Does basically the same as TransactionTestCase, but surrounds every test
     386    with a transaction. You have to use TransactionTestCase, if you need
     387    transaction management inside a test.
     388    """
     389
     390    # has the db been changed during the test
     391    db_was_changed = False
     392
     393    def _fixture_setup(self):
     394        transaction.enter_transaction_management()
     395        transaction.managed(True)
     396
     397        # whenever a save occured, the db must be dirty
     398        post_save.connect(self._set_db_was_changed)
     399        # this seems more elegant than patching ClientHandler
     400        #request_started.connect(self._do_commit)
     401        #request_finished.connect(self._do_commit)
     402
     403        if hasattr(self, 'fixtures'):
     404            call_command('loaddata', *self.fixtures, **{
     405                                                        'verbosity': 0,
     406                                                        'commit': False
     407                                                        })
     408            # TODO: find out, if loaddata does emit a post_save signal
     409            self._set_db_was_changed()
     410
     411    def _fixture_teardown(self):
     412        # If the transaction is not dirty, but the DB was changed,
     413        # a commit must have happened, so flush instead of rollback.
     414        # This currently doesn't catch the following case:
     415        # Inside a test a commit happens and after that more data is changed.
     416        if not transaction.is_dirty() and self.db_was_changed:
     417            transaction.leave_transaction_management()
     418            call_command('flush', verbosity=0, interactive=False)
     419        else:
     420            transaction.rollback()
     421            transaction.leave_transaction_management()
     422
     423    def _set_db_was_changed(self, *args, **kwargs):
     424        self.db_was_changed = True
     425
     426    def _do_commit(self, *args, **kwargs):
     427        transaction.commit()
  • django/test/__init__.py

     
    33"""
    44
    55from django.test.client import Client
    6 from django.test.testcases import TestCase
     6from django.test.testcases import TestCase, TransactionTestCase
  • tests/regressiontests/admin_views/tests.py

     
    11# coding: utf-8
    22
    3 from django.test import TestCase
     3from django.test import TestCase, TransactionTestCase
    44from django.contrib.auth.models import User, Permission
    55from django.contrib.contenttypes.models import ContentType
    66from django.contrib.admin.models import LogEntry
     
    173173    ct = ContentType.objects.get_for_model(Model)
    174174    return Permission.objects.get(content_type=ct, codename=perm)
    175175
    176 class AdminViewPermissionsTest(TestCase):
    177     """Tests for Admin Views Permissions."""
     176class AdminViewPermissionsTest(TransactionTestCase):
     177    """
     178    Tests for Admin Views Permissions.
    178179
     180    We need TransactionTestCase here, because some data is lodaed manually
     181    via the ORM, not via fixtures and test.Client is used.
     182    """
     183
    179184    fixtures = ['admin-views-users.xml']
    180185
    181186    def setUp(self):
     
    562567        should_contain = """<h1>Change model with string primary key</h1>"""
    563568        self.assertContains(response, should_contain)
    564569       
    565 
    566 class SecureViewTest(TestCase):
     570       
     571class SecureViewTest(TransactionTestCase):
    567572    fixtures = ['admin-views-users.xml']
    568573
    569574    def setUp(self):
Back to Top