Skip to content

Commit

Permalink
Enabled SimpleTestCase to be decorated by override_settings
Browse files Browse the repository at this point in the history
Refs #18417. Also fixed some test case classes which subclassed
the wrong parent.
  • Loading branch information
claudep committed Nov 25, 2012
1 parent 9f7cefd commit a5d4741
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 48 deletions.
64 changes: 35 additions & 29 deletions django/test/testcases.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -241,6 +241,40 @@ def message(self):




class SimpleTestCase(ut2.TestCase): class SimpleTestCase(ut2.TestCase):
def __call__(self, result=None):
"""
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
"""
testMethod = getattr(self, self._testMethodName)
skipped = (getattr(self.__class__, "__unittest_skip__", False) or
getattr(testMethod, "__unittest_skip__", False))

if not skipped:
try:
self._pre_setup()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
result.addError(self, sys.exc_info())
return
super(SimpleTestCase, self).__call__(result)
if not skipped:
try:
self._post_teardown()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
result.addError(self, sys.exc_info())
return

def _pre_setup(self):
pass

def _post_teardown(self):
pass

def save_warnings_state(self): def save_warnings_state(self):
""" """
Saves the state of the warnings module Saves the state of the warnings module
Expand Down Expand Up @@ -412,6 +446,7 @@ def _pre_setup(self):
ROOT_URLCONF with it. ROOT_URLCONF with it.
* Clearing the mail test outbox. * Clearing the mail test outbox.
""" """
self.client = self.client_class()
self._fixture_setup() self._fixture_setup()
self._urlconf_setup() self._urlconf_setup()
mail.outbox = [] mail.outbox = []
Expand Down Expand Up @@ -459,35 +494,6 @@ def _urlconf_setup(self):
settings.ROOT_URLCONF = self.urls settings.ROOT_URLCONF = self.urls
clear_url_caches() clear_url_caches()


def __call__(self, result=None):
"""
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
"""
testMethod = getattr(self, self._testMethodName)
skipped = (getattr(self.__class__, "__unittest_skip__", False) or
getattr(testMethod, "__unittest_skip__", False))

if not skipped:
self.client = self.client_class()
try:
self._pre_setup()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
result.addError(self, sys.exc_info())
return
super(TransactionTestCase, self).__call__(result)
if not skipped:
try:
self._post_teardown()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
result.addError(self, sys.exc_info())
return

def _post_teardown(self): def _post_teardown(self):
""" Performs any post-test things. This includes: """ Performs any post-test things. This includes:
Expand Down
6 changes: 3 additions & 3 deletions django/test/utils.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -187,11 +187,11 @@ def __exit__(self, exc_type, exc_value, traceback):
self.disable() self.disable()


def __call__(self, test_func): def __call__(self, test_func):
from django.test import TransactionTestCase from django.test import SimpleTestCase
if isinstance(test_func, type): if isinstance(test_func, type):
if not issubclass(test_func, TransactionTestCase): if not issubclass(test_func, SimpleTestCase):
raise Exception( raise Exception(
"Only subclasses of Django TransactionTestCase can be decorated " "Only subclasses of Django SimpleTestCase can be decorated "
"with override_settings") "with override_settings")
original_pre_setup = test_func._pre_setup original_pre_setup = test_func._pre_setup
original_post_teardown = test_func._post_teardown original_post_teardown = test_func._post_teardown
Expand Down
20 changes: 10 additions & 10 deletions tests/regressiontests/forms/tests/input_formats.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
from django import forms from django import forms
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils.translation import activate, deactivate from django.utils.translation import activate, deactivate
from django.utils.unittest import TestCase from django.test import SimpleTestCase




@override_settings(TIME_INPUT_FORMATS=["%I:%M:%S %p", "%I:%M %p"], USE_L10N=True) @override_settings(TIME_INPUT_FORMATS=["%I:%M:%S %p", "%I:%M %p"], USE_L10N=True)
class LocalizedTimeTests(TestCase): class LocalizedTimeTests(SimpleTestCase):
def setUp(self): def setUp(self):
activate('de') activate('de')


Expand Down Expand Up @@ -106,7 +106,7 @@ def test_localized_timeField_with_inputformat(self):




@override_settings(TIME_INPUT_FORMATS=["%I:%M:%S %p", "%I:%M %p"]) @override_settings(TIME_INPUT_FORMATS=["%I:%M:%S %p", "%I:%M %p"])
class CustomTimeInputFormatsTests(TestCase): class CustomTimeInputFormatsTests(SimpleTestCase):
def test_timeField(self): def test_timeField(self):
"TimeFields can parse dates in the default format" "TimeFields can parse dates in the default format"
f = forms.TimeField() f = forms.TimeField()
Expand Down Expand Up @@ -198,7 +198,7 @@ def test_localized_timeField_with_inputformat(self):
self.assertEqual(text, "01:30:00 PM") self.assertEqual(text, "01:30:00 PM")




class SimpleTimeFormatTests(TestCase): class SimpleTimeFormatTests(SimpleTestCase):
def test_timeField(self): def test_timeField(self):
"TimeFields can parse dates in the default format" "TimeFields can parse dates in the default format"
f = forms.TimeField() f = forms.TimeField()
Expand Down Expand Up @@ -289,7 +289,7 @@ def test_localized_timeField_with_inputformat(self):




@override_settings(DATE_INPUT_FORMATS=["%d/%m/%Y", "%d-%m-%Y"], USE_L10N=True) @override_settings(DATE_INPUT_FORMATS=["%d/%m/%Y", "%d-%m-%Y"], USE_L10N=True)
class LocalizedDateTests(TestCase): class LocalizedDateTests(SimpleTestCase):
def setUp(self): def setUp(self):
activate('de') activate('de')


Expand Down Expand Up @@ -390,7 +390,7 @@ def test_localized_dateField_with_inputformat(self):




@override_settings(DATE_INPUT_FORMATS=["%d.%m.%Y", "%d-%m-%Y"]) @override_settings(DATE_INPUT_FORMATS=["%d.%m.%Y", "%d-%m-%Y"])
class CustomDateInputFormatsTests(TestCase): class CustomDateInputFormatsTests(SimpleTestCase):
def test_dateField(self): def test_dateField(self):
"DateFields can parse dates in the default format" "DateFields can parse dates in the default format"
f = forms.DateField() f = forms.DateField()
Expand Down Expand Up @@ -481,7 +481,7 @@ def test_localized_dateField_with_inputformat(self):
text = f.widget._format_value(result) text = f.widget._format_value(result)
self.assertEqual(text, "21.12.2010") self.assertEqual(text, "21.12.2010")


class SimpleDateFormatTests(TestCase): class SimpleDateFormatTests(SimpleTestCase):
def test_dateField(self): def test_dateField(self):
"DateFields can parse dates in the default format" "DateFields can parse dates in the default format"
f = forms.DateField() f = forms.DateField()
Expand Down Expand Up @@ -572,7 +572,7 @@ def test_localized_dateField_with_inputformat(self):




@override_settings(DATETIME_INPUT_FORMATS=["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"], USE_L10N=True) @override_settings(DATETIME_INPUT_FORMATS=["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"], USE_L10N=True)
class LocalizedDateTimeTests(TestCase): class LocalizedDateTimeTests(SimpleTestCase):
def setUp(self): def setUp(self):
activate('de') activate('de')


Expand Down Expand Up @@ -673,7 +673,7 @@ def test_localized_dateTimeField_with_inputformat(self):




@override_settings(DATETIME_INPUT_FORMATS=["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"]) @override_settings(DATETIME_INPUT_FORMATS=["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"])
class CustomDateTimeInputFormatsTests(TestCase): class CustomDateTimeInputFormatsTests(SimpleTestCase):
def test_dateTimeField(self): def test_dateTimeField(self):
"DateTimeFields can parse dates in the default format" "DateTimeFields can parse dates in the default format"
f = forms.DateTimeField() f = forms.DateTimeField()
Expand Down Expand Up @@ -764,7 +764,7 @@ def test_localized_dateTimeField_with_inputformat(self):
text = f.widget._format_value(result) text = f.widget._format_value(result)
self.assertEqual(text, "01:30:00 PM 21/12/2010") self.assertEqual(text, "01:30:00 PM 21/12/2010")


class SimpleDateTimeFormatTests(TestCase): class SimpleDateTimeFormatTests(SimpleTestCase):
def test_dateTimeField(self): def test_dateTimeField(self):
"DateTimeFields can parse dates in the default format" "DateTimeFields can parse dates in the default format"
f = forms.DateTimeField() f = forms.DateTimeField()
Expand Down
12 changes: 6 additions & 6 deletions tests/regressiontests/settings_tests/tests.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from django.conf import settings, global_settings from django.conf import settings, global_settings
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.http import HttpRequest from django.http import HttpRequest
from django.test import TransactionTestCase, TestCase, signals from django.test import SimpleTestCase, TransactionTestCase, TestCase, signals
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import unittest, six from django.utils import unittest, six


Expand Down Expand Up @@ -118,19 +118,19 @@ def test_context_manager(self):
self.assertRaises(AttributeError, getattr, settings, 'TEST') self.assertRaises(AttributeError, getattr, settings, 'TEST')


def test_class_decorator(self): def test_class_decorator(self):
# TransactionTestCase can be decorated by override_settings, but not ut.TestCase # SimpleTestCase can be decorated by override_settings, but not ut.TestCase
class TransactionTestCaseSubclass(TransactionTestCase): class SimpleTestCaseSubclass(SimpleTestCase):
pass pass


class UnittestTestCaseSubclass(unittest.TestCase): class UnittestTestCaseSubclass(unittest.TestCase):
pass pass


decorated = override_settings(TEST='override')(TransactionTestCaseSubclass) decorated = override_settings(TEST='override')(SimpleTestCaseSubclass)
self.assertIsInstance(decorated, type) self.assertIsInstance(decorated, type)
self.assertTrue(issubclass(decorated, TransactionTestCase)) self.assertTrue(issubclass(decorated, SimpleTestCase))


with six.assertRaisesRegex(self, Exception, with six.assertRaisesRegex(self, Exception,
"Only subclasses of Django TransactionTestCase*"): "Only subclasses of Django SimpleTestCase*"):
decorated = override_settings(TEST='override')(UnittestTestCaseSubclass) decorated = override_settings(TEST='override')(UnittestTestCaseSubclass)


def test_signal_callback_context_manager(self): def test_signal_callback_context_manager(self):
Expand Down

0 comments on commit a5d4741

Please sign in to comment.