diff options
| author | Russell Keith-Magee <russell@keith-magee.com> | 2010-10-11 12:55:17 +0000 |
|---|---|---|
| committer | Russell Keith-Magee <russell@keith-magee.com> | 2010-10-11 12:55:17 +0000 |
| commit | 121d2e36785dc0ce8e7d1c48883fc7b719b21afc (patch) | |
| tree | 7cddebe1474071a6fed69767378fc3433fd39dbb /tests | |
| parent | 1070c57b83efdfd4fbed09280fcdaafc6d9c1a81 (diff) | |
Fixed #12991 -- Added unittest2 support. Thanks to PaulM for the draft patch, and to Luke, Karen, Justin, Alex, Łukasz Rekucki, and Chuck Harmston for their help testing and reviewing the final patch.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@14139 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'tests')
61 files changed, 731 insertions, 741 deletions
diff --git a/tests/modeltests/basic/models.py b/tests/modeltests/basic/models.py index ad2e965810..ffce4cba6b 100644 --- a/tests/modeltests/basic/models.py +++ b/tests/modeltests/basic/models.py @@ -4,7 +4,7 @@ This is a basic model with only two non-primary-key fields. """ -from django.db import models, DEFAULT_DB_ALIAS +from django.db import models, DEFAULT_DB_ALIAS, connection class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') @@ -359,9 +359,7 @@ AttributeError: Manager isn't accessible via Article instances from django.conf import settings -building_docs = getattr(settings, 'BUILDING_DOCS', False) - -if building_docs or settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.postgresql': +if connection.features.supports_microsecond_precision: __test__['API_TESTS'] += """ # In PostgreSQL, microsecond-level precision is available. >>> a9 = Article(headline='Article 9', pub_date=datetime(2005, 7, 31, 12, 30, 45, 180)) @@ -369,8 +367,7 @@ if building_docs or settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db >>> Article.objects.get(id__exact=9).pub_date datetime.datetime(2005, 7, 31, 12, 30, 45, 180) """ - -if building_docs or settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.mysql': +else: __test__['API_TESTS'] += """ # In MySQL, microsecond-level precision isn't available. You'll lose # microsecond-level precision once the data is saved. diff --git a/tests/modeltests/custom_pk/tests.py b/tests/modeltests/custom_pk/tests.py index 6ef4bdd433..22975a8417 100644 --- a/tests/modeltests/custom_pk/tests.py +++ b/tests/modeltests/custom_pk/tests.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- from django.conf import settings from django.db import DEFAULT_DB_ALIAS, transaction, IntegrityError -from django.test import TestCase +from django.test import TestCase, skipIfDBFeature from models import Employee, Business, Bar, Foo @@ -168,16 +168,15 @@ class CustomPKTests(TestCase): self.assertEqual(f, new_foo), self.assertEqual(f.bar, new_bar) - # SQLite lets objects be saved with an empty primary key, even though an # integer is expected. So we can't check for an error being raised in that # case for SQLite. Remove it from the suite for this next bit. - if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.sqlite3': - def test_required_pk(self): - # The primary key must be specified, so an error is raised if you - # try to create an object without it. - sid = transaction.savepoint() - self.assertRaises(IntegrityError, - Employee.objects.create, first_name="Tom", last_name="Smith" - ) - transaction.savepoint_rollback(sid) + @skipIfDBFeature('supports_unspecified_pk') + def test_required_pk(self): + # The primary key must be specified, so an error is raised if you + # try to create an object without it. + sid = transaction.savepoint() + self.assertRaises(IntegrityError, + Employee.objects.create, first_name="Tom", last_name="Smith" + ) + transaction.savepoint_rollback(sid) diff --git a/tests/modeltests/fixtures/tests.py b/tests/modeltests/fixtures/tests.py index 799a7328da..3c08e26867 100644 --- a/tests/modeltests/fixtures/tests.py +++ b/tests/modeltests/fixtures/tests.py @@ -1,13 +1,14 @@ import StringIO import sys -from django.test import TestCase, TransactionTestCase from django.conf import settings from django.core import management from django.db import DEFAULT_DB_ALIAS +from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from models import Article, Blog, Book, Category, Person, Spy, Tag, Visa + class TestCaseFixtureLoadingTests(TestCase): fixtures = ['fixture1.json', 'fixture2.json'] @@ -291,46 +292,46 @@ class FixtureLoadingTests(TestCase): self._dumpdata_assert(['fixtures'], """<?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"><object pk="1" model="fixtures.category"><field type="CharField" name="title">News Stories</field><field type="TextField" name="description">Latest news stories</field></object><object pk="3" model="fixtures.article"><field type="CharField" name="headline">Time to reform copyright</field><field type="DateTimeField" name="pub_date">2006-06-16 13:00:00</field></object><object pk="2" model="fixtures.article"><field type="CharField" name="headline">Poker has no place on ESPN</field><field type="DateTimeField" name="pub_date">2006-06-16 12:00:00</field></object><object pk="1" model="fixtures.article"><field type="CharField" name="headline">Python program becomes self aware</field><field type="DateTimeField" name="pub_date">2006-06-16 11:00:00</field></object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">law</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">Prince</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli</field></object></django-objects>""", format='xml', natural_keys=True) -if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.mysql': - class FixtureTransactionTests(TransactionTestCase): - def _dumpdata_assert(self, args, output, format='json'): - new_io = StringIO.StringIO() - management.call_command('dumpdata', *args, **{'format':format, 'stdout':new_io}) - command_output = new_io.getvalue().strip() - self.assertEqual(command_output, output) +class FixtureTransactionTests(TransactionTestCase): + def _dumpdata_assert(self, args, output, format='json'): + new_io = StringIO.StringIO() + management.call_command('dumpdata', *args, **{'format':format, 'stdout':new_io}) + command_output = new_io.getvalue().strip() + self.assertEqual(command_output, output) - def test_format_discovery(self): - # Load fixture 1 again, using format discovery - management.call_command('loaddata', 'fixture1', verbosity=0, commit=False) - self.assertQuerysetEqual(Article.objects.all(), [ - '<Article: Time to reform copyright>', - '<Article: Poker has no place on ESPN>', - '<Article: Python program becomes self aware>' - ]) + @skipUnlessDBFeature('supports_forward_references') + def test_format_discovery(self): + # Load fixture 1 again, using format discovery + management.call_command('loaddata', 'fixture1', verbosity=0, commit=False) + self.assertQuerysetEqual(Article.objects.all(), [ + '<Article: Time to reform copyright>', + '<Article: Poker has no place on ESPN>', + '<Article: Python program becomes self aware>' + ]) - # Try to load fixture 2 using format discovery; this will fail - # because there are two fixture2's in the fixtures directory - new_io = StringIO.StringIO() - management.call_command('loaddata', 'fixture2', verbosity=0, stderr=new_io) - output = new_io.getvalue().strip().split('\n') - self.assertEqual(len(output), 1) - self.assertTrue(output[0].startswith("Multiple fixtures named 'fixture2'")) + # Try to load fixture 2 using format discovery; this will fail + # because there are two fixture2's in the fixtures directory + new_io = StringIO.StringIO() + management.call_command('loaddata', 'fixture2', verbosity=0, stderr=new_io) + output = new_io.getvalue().strip().split('\n') + self.assertEqual(len(output), 1) + self.assertTrue(output[0].startswith("Multiple fixtures named 'fixture2'")) - # object list is unaffected - self.assertQuerysetEqual(Article.objects.all(), [ - '<Article: Time to reform copyright>', - '<Article: Poker has no place on ESPN>', - '<Article: Python program becomes self aware>' - ]) + # object list is unaffected + self.assertQuerysetEqual(Article.objects.all(), [ + '<Article: Time to reform copyright>', + '<Article: Poker has no place on ESPN>', + '<Article: Python program becomes self aware>' + ]) - # Dump the current contents of the database as a JSON fixture - self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]') + # Dump the current contents of the database as a JSON fixture + self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]') - # Load fixture 4 (compressed), using format discovery - management.call_command('loaddata', 'fixture4', verbosity=0, commit=False) - self.assertQuerysetEqual(Article.objects.all(), [ - '<Article: Django pets kitten>', - '<Article: Time to reform copyright>', - '<Article: Poker has no place on ESPN>', - '<Article: Python program becomes self aware>' - ]) + # Load fixture 4 (compressed), using format discovery + management.call_command('loaddata', 'fixture4', verbosity=0, commit=False) + self.assertQuerysetEqual(Article.objects.all(), [ + '<Article: Django pets kitten>', + '<Article: Time to reform copyright>', + '<Article: Poker has no place on ESPN>', + '<Article: Python program becomes self aware>' + ]) diff --git a/tests/modeltests/lookup/models.py b/tests/modeltests/lookup/models.py index 72b547a376..bb555615ea 100644 --- a/tests/modeltests/lookup/models.py +++ b/tests/modeltests/lookup/models.py @@ -4,7 +4,7 @@ This demonstrates features of the database API. """ -from django.db import models, DEFAULT_DB_ALIAS +from django.db import models, DEFAULT_DB_ALIAS, connection from django.conf import settings class Article(models.Model): @@ -41,15 +41,16 @@ False # There should be some now! >>> Article.objects.exists() True -"""} -if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] in ( - 'django.db.backends.postgresql', - 'django.db.backends.postgresql_pysycopg2'): - __test__['API_TESTS'] += r""" -# text matching tests for PostgreSQL 8.3 +# Integer value can be queried using string >>> Article.objects.filter(id__iexact='1') [<Article: Article 1>] + +"""} + +if connection.features.supports_date_lookup_using_string: + __test__['API_TESTS'] += r""" +# A date lookup can be performed using a string search >>> Article.objects.filter(pub_date__startswith='2005') [<Article: Article 5>, <Article: Article 6>, <Article: Article 4>, <Article: Article 2>, <Article: Article 3>, <Article: Article 7>, <Article: Article 1>] """ @@ -409,7 +410,7 @@ FieldError: Join on field 'headline' not permitted. Did you misspell 'starts' fo """ -if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.mysql': +if connection.features.supports_regex_backreferencing: __test__['API_TESTS'] += r""" # grouping and backreferences >>> Article.objects.filter(headline__regex=r'b(.).*b\1') diff --git a/tests/modeltests/test_client/tests.py b/tests/modeltests/test_client/tests.py index 09f292e037..c669fdbadd 100644 --- a/tests/modeltests/test_client/tests.py +++ b/tests/modeltests/test_client/tests.py @@ -1,6 +1,6 @@ # Validate that you can override the default test suite -import unittest +from django.utils import unittest def suite(): """ diff --git a/tests/modeltests/transactions/tests.py b/tests/modeltests/transactions/tests.py index 9964f5d7ab..be95005195 100644 --- a/tests/modeltests/transactions/tests.py +++ b/tests/modeltests/transactions/tests.py @@ -1,155 +1,159 @@ -from django.test import TransactionTestCase from django.db import connection, transaction, IntegrityError, DEFAULT_DB_ALIAS from django.conf import settings +from django.test import TransactionTestCase, skipUnlessDBFeature from models import Reporter -PGSQL = 'psycopg2' in settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] -MYSQL = 'mysql' in settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] class TransactionTests(TransactionTestCase): + def create_a_reporter_then_fail(self, first, last): + a = Reporter(first_name=first, last_name=last) + a.save() + raise Exception("I meant to do that") - if not MYSQL: + def remove_a_reporter(self, first_name): + r = Reporter.objects.get(first_name="Alice") + r.delete() - def create_a_reporter_then_fail(self, first, last): - a = Reporter(first_name=first, last_name=last) - a.save() - raise Exception("I meant to do that") + def manually_managed(self): + r = Reporter(first_name="Dirk", last_name="Gently") + r.save() + transaction.commit() - def remove_a_reporter(self, first_name): - r = Reporter.objects.get(first_name="Alice") - r.delete() + def manually_managed_mistake(self): + r = Reporter(first_name="Edward", last_name="Woodward") + r.save() + # Oops, I forgot to commit/rollback! - def manually_managed(self): - r = Reporter(first_name="Dirk", last_name="Gently") - r.save() - transaction.commit() + @skipUnlessDBFeature('supports_transactions') + def test_autocommit(self): + """ + The default behavior is to autocommit after each save() action. + """ + self.assertRaises(Exception, + self.create_a_reporter_then_fail, + "Alice", "Smith" + ) - def manually_managed_mistake(self): - r = Reporter(first_name="Edward", last_name="Woodward") - r.save() - # Oops, I forgot to commit/rollback! + # The object created before the exception still exists + self.assertEqual(Reporter.objects.count(), 1) - def execute_bad_sql(self): - cursor = connection.cursor() - cursor.execute("INSERT INTO transactions_reporter (first_name, last_name) VALUES ('Douglas', 'Adams');") - transaction.set_dirty() + @skipUnlessDBFeature('supports_transactions') + def test_autocommit_decorator(self): + """ + The autocommit decorator works exactly the same as the default behavior. + """ + autocomitted_create_then_fail = transaction.autocommit( + self.create_a_reporter_then_fail + ) + self.assertRaises(Exception, + autocomitted_create_then_fail, + "Alice", "Smith" + ) + # Again, the object created before the exception still exists + self.assertEqual(Reporter.objects.count(), 1) - def test_autocommit(self): - """ - The default behavior is to autocommit after each save() action. - """ - self.assertRaises(Exception, - self.create_a_reporter_then_fail, - "Alice", "Smith" - ) + @skipUnlessDBFeature('supports_transactions') + def test_autocommit_decorator_with_using(self): + """ + The autocommit decorator also works with a using argument. + """ + autocomitted_create_then_fail = transaction.autocommit(using='default')( + self.create_a_reporter_then_fail + ) + self.assertRaises(Exception, + autocomitted_create_then_fail, + "Alice", "Smith" + ) + # Again, the object created before the exception still exists + self.assertEqual(Reporter.objects.count(), 1) - # The object created before the exception still exists - self.assertEqual(Reporter.objects.count(), 1) + @skipUnlessDBFeature('supports_transactions') + def test_commit_on_success(self): + """ + With the commit_on_success decorator, the transaction is only committed + if the function doesn't throw an exception. + """ + committed_on_success = transaction.commit_on_success( + self.create_a_reporter_then_fail) + self.assertRaises(Exception, committed_on_success, "Dirk", "Gently") + # This time the object never got saved + self.assertEqual(Reporter.objects.count(), 0) - def test_autocommit_decorator(self): - """ - The autocommit decorator works exactly the same as the default behavior. - """ - autocomitted_create_then_fail = transaction.autocommit( - self.create_a_reporter_then_fail - ) - self.assertRaises(Exception, - autocomitted_create_then_fail, - "Alice", "Smith" - ) - # Again, the object created before the exception still exists - self.assertEqual(Reporter.objects.count(), 1) + @skipUnlessDBFeature('supports_transactions') + def test_commit_on_success_with_using(self): + """ + The commit_on_success decorator also works with a using argument. + """ + using_committed_on_success = transaction.commit_on_success(using='default')( + self.create_a_reporter_then_fail + ) + self.assertRaises(Exception, + using_committed_on_success, + "Dirk", "Gently" + ) + # This time the object never got saved + self.assertEqual(Reporter.objects.count(), 0) - def test_autocommit_decorator_with_using(self): - """ - The autocommit decorator also works with a using argument. - """ - autocomitted_create_then_fail = transaction.autocommit(using='default')( - self.create_a_reporter_then_fail - ) - self.assertRaises(Exception, - autocomitted_create_then_fail, - "Alice", "Smith" - ) - # Again, the object created before the exception still exists - self.assertEqual(Reporter.objects.count(), 1) + @skipUnlessDBFeature('supports_transactions') + def test_commit_on_success_succeed(self): + """ + If there aren't any exceptions, the data will get saved. + """ + Reporter.objects.create(first_name="Alice", last_name="Smith") + remove_comitted_on_success = transaction.commit_on_success( + self.remove_a_reporter + ) + remove_comitted_on_success("Alice") + self.assertEqual(list(Reporter.objects.all()), []) - def test_commit_on_success(self): - """ - With the commit_on_success decorator, the transaction is only committed - if the function doesn't throw an exception. - """ - committed_on_success = transaction.commit_on_success( - self.create_a_reporter_then_fail) - self.assertRaises(Exception, committed_on_success, "Dirk", "Gently") - # This time the object never got saved - self.assertEqual(Reporter.objects.count(), 0) + @skipUnlessDBFeature('supports_transactions') + def test_manually_managed(self): + """ + You can manually manage transactions if you really want to, but you + have to remember to commit/rollback. + """ + manually_managed = transaction.commit_manually(self.manually_managed) + manually_managed() + self.assertEqual(Reporter.objects.count(), 1) - def test_commit_on_success_with_using(self): - """ - The commit_on_success decorator also works with a using argument. - """ - using_committed_on_success = transaction.commit_on_success(using='default')( - self.create_a_reporter_then_fail - ) - self.assertRaises(Exception, - using_committed_on_success, - "Dirk", "Gently" - ) - # This time the object never got saved - self.assertEqual(Reporter.objects.count(), 0) + @skipUnlessDBFeature('supports_transactions') + def test_manually_managed_mistake(self): + """ + If you forget, you'll get bad errors. + """ + manually_managed_mistake = transaction.commit_manually( + self.manually_managed_mistake + ) + self.assertRaises(transaction.TransactionManagementError, + manually_managed_mistake) - def test_commit_on_success_succeed(self): - """ - If there aren't any exceptions, the data will get saved. - """ - Reporter.objects.create(first_name="Alice", last_name="Smith") - remove_comitted_on_success = transaction.commit_on_success( - self.remove_a_reporter - ) - remove_comitted_on_success("Alice") - self.assertEqual(list(Reporter.objects.all()), []) + @skipUnlessDBFeature('supports_transactions') + def test_manually_managed_with_using(self): + """ + The commit_manually function also works with a using argument. + """ + using_manually_managed_mistake = transaction.commit_manually(using='default')( + self.manually_managed_mistake + ) + self.assertRaises(transaction.TransactionManagementError, + using_manually_managed_mistake + ) - def test_manually_managed(self): - """ - You can manually manage transactions if you really want to, but you - have to remember to commit/rollback. - """ - manually_managed = transaction.commit_manually(self.manually_managed) - manually_managed() - self.assertEqual(Reporter.objects.count(), 1) +class TransactionRollbackTests(TransactionTestCase): + def execute_bad_sql(self): + cursor = connection.cursor() + cursor.execute("INSERT INTO transactions_reporter (first_name, last_name) VALUES ('Douglas', 'Adams');") + transaction.set_dirty() - def test_manually_managed_mistake(self): - """ - If you forget, you'll get bad errors. - """ - manually_managed_mistake = transaction.commit_manually( - self.manually_managed_mistake - ) - self.assertRaises(transaction.TransactionManagementError, - manually_managed_mistake) - - def test_manually_managed_with_using(self): - """ - The commit_manually function also works with a using argument. - """ - using_manually_managed_mistake = transaction.commit_manually(using='default')( - self.manually_managed_mistake - ) - self.assertRaises(transaction.TransactionManagementError, - using_manually_managed_mistake - ) - - if PGSQL: - - def test_bad_sql(self): - """ - Regression for #11900: If a function wrapped by commit_on_success - writes a transaction that can't be committed, that transaction should - be rolled back. The bug is only visible using the psycopg2 backend, - though the fix is generally a good idea. - """ - execute_bad_sql = transaction.commit_on_success(self.execute_bad_sql) - self.assertRaises(IntegrityError, execute_bad_sql) - transaction.rollback() + @skipUnlessDBFeature('requires_rollback_on_dirty_transaction') + def test_bad_sql(self): + """ + Regression for #11900: If a function wrapped by commit_on_success + writes a transaction that can't be committed, that transaction should + be rolled back. The bug is only visible using the psycopg2 backend, + though the fix is generally a good idea. + """ + execute_bad_sql = transaction.commit_on_success(self.execute_bad_sql) + self.assertRaises(IntegrityError, execute_bad_sql) + transaction.rollback() diff --git a/tests/modeltests/validation/__init__.py b/tests/modeltests/validation/__init__.py index d0a7d19d49..ca18c1bd68 100644 --- a/tests/modeltests/validation/__init__.py +++ b/tests/modeltests/validation/__init__.py @@ -1,4 +1,4 @@ -import unittest +from django.utils import unittest from django.core.exceptions import ValidationError diff --git a/tests/modeltests/validation/test_unique.py b/tests/modeltests/validation/test_unique.py index fb77c4d28c..2b824ae3b2 100644 --- a/tests/modeltests/validation/test_unique.py +++ b/tests/modeltests/validation/test_unique.py @@ -1,7 +1,9 @@ -import unittest import datetime + from django.conf import settings from django.db import connection +from django.utils import unittest + from models import CustomPKModel, UniqueTogetherModel, UniqueFieldsModel, UniqueForDateModel, ModelToValidate diff --git a/tests/modeltests/validation/validators.py b/tests/modeltests/validation/validators.py index 3ad2c40f03..6a7d833555 100644 --- a/tests/modeltests/validation/validators.py +++ b/tests/modeltests/validation/validators.py @@ -1,4 +1,5 @@ -from unittest import TestCase +from django.utils.unittest import TestCase + from modeltests.validation import ValidationTestCase from models import * diff --git a/tests/modeltests/validators/tests.py b/tests/modeltests/validators/tests.py index 44ad176747..b4411a221a 100644 --- a/tests/modeltests/validators/tests.py +++ b/tests/modeltests/validators/tests.py @@ -1,10 +1,12 @@ # -*- coding: utf-8 -*- import re import types -from unittest import TestCase from datetime import datetime, timedelta + from django.core.exceptions import ValidationError from django.core.validators import * +from django.utils.unittest import TestCase + NOW = datetime.now() diff --git a/tests/regressiontests/admin_scripts/tests.py b/tests/regressiontests/admin_scripts/tests.py index 3dd8ad5d13..52f1bedc44 100644 --- a/tests/regressiontests/admin_scripts/tests.py +++ b/tests/regressiontests/admin_scripts/tests.py @@ -4,13 +4,13 @@ advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODU and default settings.py files. """ import os -import unittest import shutil import sys import re from django import conf, bin, get_version from django.conf import settings +from django.utils import unittest class AdminScriptTestCase(unittest.TestCase): def write_settings(self, filename, apps=None, is_dir=False, sdict=None): diff --git a/tests/regressiontests/admin_util/tests.py b/tests/regressiontests/admin_util/tests.py index 5ea0ac585e..6979a7a573 100644 --- a/tests/regressiontests/admin_util/tests.py +++ b/tests/regressiontests/admin_util/tests.py @@ -1,16 +1,15 @@ from datetime import datetime -import unittest from django.conf import settings -from django.db import models -from django.utils.formats import localize -from django.test import TestCase - from django.contrib import admin from django.contrib.admin.util import display_for_field, label_for_field, lookup_field +from django.contrib.admin.util import NestedObjects from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE from django.contrib.sites.models import Site -from django.contrib.admin.util import NestedObjects +from django.db import models +from django.test import TestCase +from django.utils import unittest +from django.utils.formats import localize from models import Article, Count diff --git a/tests/regressiontests/admin_views/tests.py b/tests/regressiontests/admin_views/tests.py index c530839f5d..c0e1e506d1 100644 --- a/tests/regressiontests/admin_views/tests.py +++ b/tests/regressiontests/admin_views/tests.py @@ -12,13 +12,14 @@ from django.contrib.admin.sites import LOGIN_FORM_KEY from django.contrib.admin.util import quote from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.forms.util import ErrorList +import django.template.context from django.test import TestCase from django.utils import formats from django.utils.cache import get_max_age from django.utils.encoding import iri_to_uri from django.utils.html import escape from django.utils.translation import get_date_formats, activate, deactivate -import django.template.context +from django.utils import unittest # local test models from models import Article, BarAccount, CustomArticle, EmptyModel, \ @@ -2210,51 +2211,52 @@ class UserAdminTest(TestCase): self.assertNotEquals(new_user.password, UNUSABLE_PASSWORD) try: - # If docutils isn't installed, skip the AdminDocs tests. import docutils +except ImportError: + docutils = None - class AdminDocsTest(TestCase): - fixtures = ['admin-views-users.xml'] +#@unittest.skipUnless(docutils, "no docutils installed.") +class AdminDocsTest(TestCase): + fixtures = ['admin-views-users.xml'] - def setUp(self): - self.client.login(username='super', password='secret') + def setUp(self): + self.client.login(username='super', password='secret') - def tearDown(self): - self.client.logout() + def tearDown(self): + self.client.logout() - def test_tags(self): - response = self.client.get('/test_admin/admin/doc/tags/') + def test_tags(self): + response = self.client.get('/test_admin/admin/doc/tags/') - # The builtin tag group exists - self.assertContains(response, "<h2>Built-in tags</h2>", count=2) + # The builtin tag group exists + self.assertContains(response, "<h2>Built-in tags</h2>", count=2) - # A builtin tag exists in both the index and detail - self.assertContains(response, '<h3 id="built_in-autoescape">autoescape</h3>') - self.assertContains(response, '<li><a href="#built_in-autoescape">autoescape</a></li>') + # A builtin tag exists in both the index and detail + self.assertContains(response, '<h3 id="built_in-autoescape">autoescape</h3>') + self.assertContains(response, '<li><a href="#built_in-autoescape">autoescape</a></li>') - # An app tag exists in both the index and detail - self.assertContains(response, '<h3 id="flatpages-get_flatpages">get_flatpages</h3>') - self.assertContains(response, '<li><a href="#flatpages-get_flatpages">get_flatpages</a></li>') + # An app tag exists in both the index and detail + self.assertContains(response, '<h3 id="flatpages-get_flatpages">get_flatpages</h3>') + self.assertContains(response, '<li><a href="#flatpages-get_flatpages">get_flatpages</a></li>') - # The admin list tag group exists - self.assertContains(response, "<h2>admin_list</h2>", count=2) + # The admin list tag group exists + self.assertContains(response, "<h2>admin_list</h2>", count=2) - # An admin list tag exists in both the index and detail - self.assertContains(response, '<h3 id="admin_list-admin_actions">admin_actions</h3>') - self.assertContains(response, '<li><a href="#admin_list-admin_actions">admin_actions</a></li>') + # An admin list tag exists in both the index and detail + self.assertContains(response, '<h3 id="admin_list-admin_actions">admin_actions</h3>') + self.assertContains(response, '<li><a href="#admin_list-admin_actions">admin_actions</a></li>') - def test_filters(self): - response = self.client.get('/test_admin/admin/doc/filters/') + def test_filters(self): + response = self.client.get('/test_admin/admin/doc/filters/') - # The builtin filter group exists - self.assertContains(response, "<h2>Built-in filters</h2>", count=2) + # The builtin filter group exists + self.assertContains(response, "<h2>Built-in filters</h2>", count=2) - # A builtin filter exists in both the index and detail - self.assertContains(response, '<h3 id="built_in-add">add</h3>') - self.assertContains(response, '<li><a href="#built_in-add">add</a></li>') + # A builtin filter exists in both the index and detail + self.assertContains(response, '<h3 id="built_in-add">add</h3>') + self.assertContains(response, '<li><a href="#built_in-add">add</a></li>') -except ImportError: - pass +AdminDocsTest = unittest.skipUnless(docutils, "no docutils installed.")(AdminDocsTest) class ValidXHTMLTests(TestCase): fixtures = ['admin-views-users.xml'] diff --git a/tests/regressiontests/admin_widgets/tests.py b/tests/regressiontests/admin_widgets/tests.py index c445644335..900cb4a462 100644 --- a/tests/regressiontests/admin_widgets/tests.py +++ b/tests/regressiontests/admin_widgets/tests.py @@ -3,9 +3,10 @@ from django import forms from django.contrib import admin from django.contrib.admin import widgets -from unittest import TestCase -from django.test import TestCase as DjangoTestCase from django.db.models import DateField +from django.test import TestCase as DjangoTestCase +from django.utils.unittest import TestCase + import models class AdminFormfieldForDBFieldTests(TestCase): diff --git a/tests/regressiontests/aggregation_regress/tests.py b/tests/regressiontests/aggregation_regress/tests.py index 58d0b2748f..c82fd996fd 100644 --- a/tests/regressiontests/aggregation_regress/tests.py +++ b/tests/regressiontests/aggregation_regress/tests.py @@ -3,32 +3,13 @@ from decimal import Decimal from django.core.exceptions import FieldError from django.conf import settings -from django.test import TestCase, Approximate +from django.test import TestCase, Approximate, skipUnlessDBFeature from django.db import DEFAULT_DB_ALIAS from django.db.models import Count, Max, Avg, Sum, StdDev, Variance, F from regressiontests.aggregation_regress.models import * -def run_stddev_tests(): - """Check to see if StdDev/Variance tests should be run. - - Stddev and Variance are not guaranteed to be available for SQLite, and - are not available for PostgreSQL before 8.2. - """ - if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.sqlite3': - return False - - class StdDevPop(object): - sql_function = 'STDDEV_POP' - - try: - connection.ops.check_aggregate_support(StdDevPop()) - except: - return False - return True - - class AggregationTests(TestCase): def assertObjectAttrs(self, obj, **kwargs): for attr, value in kwargs.iteritems(): @@ -75,27 +56,27 @@ class AggregationTests(TestCase): qs2 = books.filter(id__in=list(qs)) self.assertEqual(list(qs1), list(qs2)) - if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.oracle': - def test_annotate_with_extra(self): - """ - Regression test for #11916: Extra params + aggregation creates - incorrect SQL. - """ - #oracle doesn't support subqueries in group by clause - shortest_book_sql = """ - SELECT name - FROM aggregation_regress_book b - WHERE b.publisher_id = aggregation_regress_publisher.id - ORDER BY b.pages - LIMIT 1 - """ - # tests that this query does not raise a DatabaseError due to the full - # subselect being (erroneously) added to the GROUP BY parameters - qs = Publisher.objects.extra(select={ - 'name_of_shortest_book': shortest_book_sql, - }).annotate(total_books=Count('book')) - # force execution of the query - list(qs) + @skipUnlessDBFeature('supports_subqueries_in_group_by') + def test_annotate_with_extra(self): + """ + Regression test for #11916: Extra params + aggregation creates + incorrect SQL. + """ + #oracle doesn't support subqueries in group by clause + shortest_book_sql = """ + SELECT name + FROM aggregation_regress_book b + WHERE b.publisher_id = aggregation_regress_publisher.id + ORDER BY b.pages + LIMIT 1 + """ + # tests that this query does not raise a DatabaseError due to the full + # subselect being (erroneously) added to the GROUP BY parameters + qs = Publisher.objects.extra(select={ + 'name_of_shortest_book': shortest_book_sql, + }).annotate(total_books=Count('book')) + # force execution of the query + list(qs) def test_aggregate(self): # Ordering requests are ignored @@ -641,64 +622,64 @@ class AggregationTests(TestCase): lambda: Book.objects.annotate(mean_age=Avg('authors__age')).annotate(Avg('mean_age')) ) - if run_stddev_tests(): - def test_stddev(self): - self.assertEqual( - Book.objects.aggregate(StdDev('pages')), - {'pages__stddev': Approximate(311.46, 1)} - ) + @skipUnlessDBFeature('supports_stddev') + def test_stddev(self): + self.assertEqual( + Book.objects.aggregate(StdDev('pages')), + {'pages__stddev': Approximate(311.46, 1)} + ) - self.assertEqual( - Book.objects.aggregate(StdDev('rating')), - {'rating__stddev': Approximate(0.60, 1)} - ) + self.assertEqual( + Book.objects.aggregate(StdDev('rating')), + {'rating__stddev': Approximate(0.60, 1)} + ) - self.assertEqual( - Book.objects.aggregate(StdDev('price')), - {'price__stddev': Approximate(24.16, 2)} - ) + self.assertEqual( + Book.objects.aggregate(StdDev('price')), + {'price__stddev': Approximate(24.16, 2)} + ) - self.assertEqual( - Book.objects.aggregate(StdDev('pages', sample=True)), - {'pages__stddev': Approximate(341.19, 2)} - ) + self.assertEqual( + Book.objects.aggregate(StdDev('pages', sample=True)), + {'pages__stddev': Approximate(341.19, 2)} + ) - self.assertEqual( - Book.objects.aggregate(StdDev('rating', sample=True)), - {'rating__stddev': Approximate(0.66, 2)} - ) + self.assertEqual( + Book.objects.aggregate(StdDev('rating', sample=True)), + {'rating__stddev': Approximate(0.66, 2)} + ) - self.assertEqual( - Book.objects.aggregate(StdDev('price', sample=True)), - {'price__stddev': Approximate(26.46, 1)} - ) + self.assertEqual( + Book.objects.aggregate(StdDev('price', sample=True)), + {'price__stddev': Approximate(26.46, 1)} + ) - self.assertEqual( - Book.objects.aggregate(Variance('pages')), - {'pages__variance': Approximate(97010.80, 1)} - ) + self.assertEqual( + Book.objects.aggregate(Variance('pages')), + {'pages__variance': Approximate(97010.80, 1)} + ) - self.assertEqual( - Book.objects.aggregate(Variance('rating')), - {'rating__variance': Approximate(0.36, 1)} - ) + self.assertEqual( + Book.objects.aggregate(Variance('rating')), + {'rating__variance': Approximate(0.36, 1)} + ) - self.assertEqual( - Book.objects.aggregate(Variance('price')), - {'price__variance': Approximate(583.77, 1)} - ) + self.assertEqual( + Book.objects.aggregate(Variance('price')), + {'price__variance': Approximate(583.77, 1)} + ) - self.assertEqual( - Book.objects.aggregate(Variance('pages', sample=True)), - {'pages__variance': Approximate(116412.96, 1)} - ) + self.assertEqual( + Book.objects.aggregate(Variance('pages', sample=True)), + {'pages__variance': Approximate(116412.96, 1)} + ) - self.assertEqual( - Book.objects.aggregate(Variance('rating', sample=True)), - {'rating__variance': Approximate(0.44, 2)} - ) + self.assertEqual( + Book.objects.aggregate(Variance('rating', sample=True)), + {'rating__variance': Approximate(0.44, 2)} + ) - self.assertEqual( - Book.objects.aggregate(Variance('price', sample=True)), - {'price__variance': Approximate(700.53, 2)} - ) + self.assertEqual( + Book.objects.aggregate(Variance('price', sample=True)), + {'price__variance': Approximate(700.53, 2)} + ) diff --git a/tests/regressiontests/app_loading/tests.py b/tests/regressiontests/app_loading/tests.py index 111ed46925..77aeb9a5d1 100644 --- a/tests/regressiontests/app_loading/tests.py +++ b/tests/regressiontests/app_loading/tests.py @@ -2,10 +2,10 @@ import copy import os import sys import time -from unittest import TestCase from django.conf import Settings from django.db.models.loading import cache, load_app +from django.utils.unittest import TestCase __test__ = {"API_TESTS": """ Test the globbing of INSTALLED_APPS. diff --git a/tests/regressiontests/backends/models.py b/tests/regressiontests/backends/models.py index 82da8cdd91..3ad4a60c02 100644 --- a/tests/regressiontests/backends/models.py +++ b/tests/regressiontests/backends/models.py @@ -28,7 +28,7 @@ class SchoolClass(models.Model): # Unfortunately, the following model breaks MySQL hard. # Until #13711 is fixed, this test can't be run under MySQL. -if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.mysql': +if connection.features.supports_long_model_names: class VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ(models.Model): class Meta: # We need to use a short actual table name or diff --git a/tests/regressiontests/backends/tests.py b/tests/regressiontests/backends/tests.py index bf2086c0b7..c5d13285d3 100644 --- a/tests/regressiontests/backends/tests.py +++ b/tests/regressiontests/backends/tests.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- # Unit and doctests for specific database backends. import datetime -import unittest from django.conf import settings from django.core import management @@ -9,48 +8,46 @@ from django.core.management.color import no_style from django.db import backend, connection, connections, DEFAULT_DB_ALIAS from django.db.backends.signals import connection_created from django.db.backends.postgresql import version as pg_version -from django.test import TestCase +from django.test import TestCase, skipUnlessDBFeature +from django.utils import unittest from regressiontests.backends import models -class Callproc(unittest.TestCase): +class OracleChecks(unittest.TestCase): + @unittest.skipUnless(connection.vendor == 'oracle', + "No need to check Oracle cursor semantics") def test_dbms_session(self): # If the backend is Oracle, test that we can call a standard # stored procedure through our cursor wrapper. - if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle': - convert_unicode = backend.convert_unicode - cursor = connection.cursor() - cursor.callproc(convert_unicode('DBMS_SESSION.SET_IDENTIFIER'), - [convert_unicode('_django_testing!'),]) - return True - else: - return True + convert_unicode = backend.convert_unicode + cursor = connection.cursor() + cursor.callproc(convert_unicode('DBMS_SESSION.SET_IDENTIFIER'), + [convert_unicode('_django_testing!'),]) + @unittest.skipUnless(connection.vendor == 'oracle', + "No need to check Oracle cursor semantics") def test_cursor_var(self): # If the backend is Oracle, test that we can pass cursor variables # as query parameters. - if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle': - cursor = connection.cursor() - var = cursor.var(backend.Database.STRING) - cursor.execute("BEGIN %s := 'X'; END; ", [var]) - self.assertEqual(var.getvalue(), 'X') - - -class LongString(unittest.TestCase): + cursor = connection.cursor() + var = cursor.var(backend.Database.STRING) + cursor.execute("BEGIN %s := 'X'; END; ", [var]) + self.assertEqual(var.getvalue(), 'X') + @unittest.skipUnless(connection.vendor == 'oracle', + "No need to check Oracle cursor semantics") def test_long_string(self): # If the backend is Oracle, test that we can save a text longer # than 4000 chars and read it properly - if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle': - c = connection.cursor() - c.execute('CREATE TABLE ltext ("TEXT" NCLOB)') - long_str = ''.join([unicode(x) for x in xrange(4000)]) - c.execute('INSERT INTO ltext VALUES (%s)',[long_str]) - c.execute('SELECT text FROM ltext') - row = c.fetchone() - self.assertEquals(long_str, row[0].read()) - c.execute('DROP TABLE ltext') + c = connection.cursor() + c.execute('CREATE TABLE ltext ("TEXT" NCLOB)') + long_str = ''.join([unicode(x) for x in xrange(4000)]) + c.execute('INSERT INTO ltext VALUES (%s)',[long_str]) + c.execute('SELECT text FROM ltext') + row = c.fetchone() + self.assertEqual(long_str, row[0].read()) + c.execute('DROP TABLE ltext') class DateQuotingTest(TestCase): @@ -97,46 +94,48 @@ class ParameterHandlingTest(TestCase): # Unfortunately, the following tests would be a good test to run on all # backends, but it breaks MySQL hard. Until #13711 is fixed, it can't be run # everywhere (although it would be an effective test of #13711). -if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.mysql': - class LongNameTest(TestCase): - """Long primary keys and model names can result in a sequence name - that exceeds the database limits, which will result in truncation - on certain databases (e.g., Postgres). The backend needs to use - the correct sequence name in last_insert_id and other places, so - check it is. Refs #8901. - """ +class LongNameTest(TestCase): + """Long primary keys and model names can result in a sequence name + that exceeds the database limits, which will result in truncation + on certain databases (e.g., Postgres). The backend needs to use + the correct sequence name in last_insert_id and other places, so + check it is. Refs #8901. + """ - def test_sequence_name_length_limits_create(self): - """Test creation of model with long name and long pk name doesn't error. Ref #8901""" - models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() + @skipUnlessDBFeature('supports_long_model_names') + def test_sequence_name_length_limits_create(self): + """Test creation of model with long name and long pk name doesn't error. Ref #8901""" + models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() - def test_sequence_name_length_limits_m2m(self): - """Test an m2m save of a model with a long name and a long m2m field name doesn't error as on Django >=1.2 this now uses object saves. Ref #8901""" - obj = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() - rel_obj = models.Person.objects.create(first_name='Django', last_name='Reinhardt') - obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj) + @skipUnlessDBFeature('supports_long_model_names') + def test_sequence_name_length_limits_m2m(self): + """Test an m2m save of a model with a long name and a long m2m field name doesn't error as on Django >=1.2 this now uses object saves. Ref #8901""" + obj = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() + rel_obj = models.Person.objects.create(first_name='Django', last_name='Reinhardt') + obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj) - def test_sequence_name_length_limits_flush(self): - """Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901""" - # A full flush is expensive to the full test, so we dig into the - # internals to generate the likely offending SQL and run it manually + @skipUnlessDBFeature('supports_long_model_names') + def test_sequence_name_length_limits_flush(self): + """Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901""" + # A full flush is expensive to the full test, so we dig into the + # internals to generate the likely offending SQL and run it manually - # Some convenience aliases - VLM = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ - VLM_m2m = VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through - tables = [ - VLM._meta.db_table, - VLM_m2m._meta.db_table, - ] - sequences = [ - { - 'column': VLM._meta.pk.column, - 'table': VLM._meta.db_table - }, - ] - cursor = connection.cursor() - for statement in connection.ops.sql_flush(no_style(), tables, sequences): - cursor.execute(statement) + # Some convenience aliases + VLM = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ + VLM_m2m = VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through + tables = [ + VLM._meta.db_table, + VLM_m2m._meta.db_table, + ] + sequences = [ + { + 'column': VLM._meta.pk.column, + 'table': VLM._meta.db_table + }, + ] + cursor = connection.cursor() + for statement in connection.ops.sql_flush(no_style(), tables, sequences): + cursor.execute(statement) class SequenceResetTest(TestCase): def test_generic_relation(self): @@ -170,22 +169,22 @@ class PostgresVersionTest(TestCase): # Unfortunately with sqlite3 the in-memory test database cannot be # closed, and so it cannot be re-opened during testing, and so we # sadly disable this test for now. -if settings.DATABASES[DEFAULT_DB_ALIAS]["ENGINE"] != "django.db.backends.sqlite3": - class ConnectionCreatedSignalTest(TestCase): - def test_signal(self): - data = {} - def receiver(sender, connection, **kwargs): - data["connection"] = connection +class ConnectionCreatedSignalTest(TestCase): + @skipUnlessDBFeature('test_db_allows_multiple_connections') + def test_signal(self): + data = {} + def receiver(sender, connection, **kwargs): + data["connection"] = connection - connection_created.connect(receiver) - connection.close() - cursor = connection.cursor() - self.assertTrue(data["connection"] is connection) + connection_created.connect(receiver) + connection.close() + cursor = connection.cursor() + self.assertTrue(data["connection"] is connection) - connection_created.disconnect(receiver) - data.clear() - cursor = connection.cursor() - self.assertTrue(data == {}) + connection_created.disconnect(receiver) + data.clear() + cursor = connection.cursor() + self.assertTrue(data == {}) class BackendTestCase(TestCase): @@ -225,3 +224,4 @@ class BackendTestCase(TestCase): self.assertEqual(cursor.fetchone(), (u'Clark', u'Kent')) self.assertEqual(list(cursor.fetchmany(2)), [(u'Jane', u'Doe'), (u'John', u'Doe')]) self.assertEqual(list(cursor.fetchall()), [(u'Mary', u'Agnelline'), (u'Peter', u'Parker')]) + diff --git a/tests/regressiontests/bash_completion/tests.py b/tests/regressiontests/bash_completion/tests.py index 24c8b1d3f3..f9670346a1 100644 --- a/tests/regressiontests/bash_completion/tests.py +++ b/tests/regressiontests/bash_completion/tests.py @@ -2,12 +2,12 @@ A series of tests to establish that the command-line bash completion works. """ import os -import unittest import sys import StringIO from django.conf import settings from django.core.management import ManagementUtility +from django.utils import unittest class BashCompletionTests(unittest.TestCase): """ diff --git a/tests/regressiontests/bug639/tests.py b/tests/regressiontests/bug639/tests.py index 2cc3a8af0b..345ce456ea 100644 --- a/tests/regressiontests/bug639/tests.py +++ b/tests/regressiontests/bug639/tests.py @@ -6,9 +6,10 @@ ModelForm's save() method causes Model.save() to be called more than once. import os import shutil -import unittest from django.core.files.uploadedfile import SimpleUploadedFile +from django.utils import unittest + from regressiontests.bug639.models import Photo, PhotoForm, temp_storage_dir class Bug639Test(unittest.TestCase): diff --git a/tests/regressiontests/bug8245/tests.py b/tests/regressiontests/bug8245/tests.py index e45dd05673..1f957252c1 100644 --- a/tests/regressiontests/bug8245/tests.py +++ b/tests/regressiontests/bug8245/tests.py @@ -1,6 +1,5 @@ -from unittest import TestCase - from django.contrib import admin +from django.utils.unittest import TestCase class Bug8245Test(TestCase): diff --git a/tests/regressiontests/builtin_server/tests.py b/tests/regressiontests/builtin_server/tests.py index ad3abc9e9f..9563be4c4e 100644 --- a/tests/regressiontests/builtin_server/tests.py +++ b/tests/regressiontests/builtin_server/tests.py @@ -1,6 +1,7 @@ -from unittest import TestCase from StringIO import StringIO + from django.core.servers.basehttp import ServerHandler +from django.utils.unittest import TestCase # # Tests for #9659: wsgi.file_wrapper in the builtin server. diff --git a/tests/regressiontests/cache/tests.py b/tests/regressiontests/cache/tests.py index 1e0a4046bb..a91b842ebd 100644 --- a/tests/regressiontests/cache/tests.py +++ b/tests/regressiontests/cache/tests.py @@ -7,7 +7,6 @@ import os import shutil import tempfile import time -import unittest import warnings from django.conf import settings @@ -17,6 +16,7 @@ from django.core.cache.backends.base import InvalidCacheBackendError, CacheKeyWa from django.http import HttpResponse, HttpRequest from django.middleware.cache import FetchFromCacheMiddleware, UpdateCacheMiddleware from django.utils import translation +from django.utils import unittest from django.utils.cache import patch_vary_headers, get_cache_key, learn_cache_key from django.utils.hashcompat import md5_constructor from regressiontests.cache.models import Poll, expensive_calculation @@ -393,6 +393,7 @@ class BaseCacheTests(object): # runner doesn't add any global warning filters (it currently # does not). warnings.resetwarnings() + warnings.simplefilter("ignore", PendingDeprecationWarning) class DBCacheTests(unittest.TestCase, BaseCacheTests): def setUp(self): diff --git a/tests/regressiontests/datatypes/tests.py b/tests/regressiontests/datatypes/tests.py index f7a0447ac1..1d44552a37 100644 --- a/tests/regressiontests/datatypes/tests.py +++ b/tests/regressiontests/datatypes/tests.py @@ -1,10 +1,11 @@ import datetime + +from django.conf import settings from django.db import DEFAULT_DB_ALIAS -from django.test import TestCase +from django.test import TestCase, skipIfDBFeature from django.utils import tzinfo from models import Donut, RumBaba -from django.conf import settings class DataTypesTestCase(TestCase): @@ -73,14 +74,14 @@ class DataTypesTestCase(TestCase): newd = Donut.objects.get(id=d.id) self.assert_(isinstance(newd.review, unicode)) - def test_tz_awareness_mysql(self): + @skipIfDBFeature('supports_timezones') + def test_error_on_timezone(self): """Regression test for #8354: the MySQL backend should raise an error if given a timezone-aware datetime object.""" - if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.mysql': - dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=tzinfo.FixedOffset(0)) - d = Donut(name='Bear claw', consumed_at=dt) - self.assertRaises(ValueError, d.save) - # ValueError: MySQL backend does not support timezone-aware datetimes. + dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=tzinfo.FixedOffset(0)) + d = Donut(name='Bear claw', consumed_at=dt) + self.assertRaises(ValueError, d.save) + # ValueError: MySQL backend does not support timezone-aware datetimes. def test_datefield_auto_now_add(self): """Regression test for #10970, auto_now_add for DateField should store diff --git a/tests/regressiontests/decorators/tests.py b/tests/regressiontests/decorators/tests.py index ea2e10e965..1f0551eb79 100644 --- a/tests/regressiontests/decorators/tests.py +++ b/tests/regressiontests/decorators/tests.py @@ -1,18 +1,19 @@ -from unittest import TestCase from sys import version_info try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.4 fallback. +from django.contrib.auth.decorators import login_required, permission_required, user_passes_test +from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse, HttpRequest +from django.utils.decorators import method_decorator from django.utils.functional import allow_lazy, lazy, memoize +from django.utils.unittest import TestCase from django.views.decorators.http import require_http_methods, require_GET, require_POST from django.views.decorators.vary import vary_on_headers, vary_on_cookie from django.views.decorators.cache import cache_page, never_cache, cache_control -from django.utils.decorators import method_decorator -from django.contrib.auth.decorators import login_required, permission_required, user_passes_test -from django.contrib.admin.views.decorators import staff_member_required + def fully_decorated(request): """Expected __doc__""" @@ -70,25 +71,25 @@ class DecoratorsTest(TestCase): def test1(user): user.decorators_applied.append('test1') return True - + def test2(user): user.decorators_applied.append('test2') return True - + def callback(request): return request.user.decorators_applied callback = user_passes_test(test1)(callback) callback = user_passes_test(test2)(callback) - + class DummyUser(object): pass class DummyRequest(object): pass - + request = DummyRequest() request.user = DummyUser() request.user.decorators_applied = [] response = callback(request) - + self.assertEqual(response, ['test2', 'test1']) def test_cache_page_new_style(self): diff --git a/tests/regressiontests/delete_regress/tests.py b/tests/regressiontests/delete_regress/tests.py index 26cd3c5ce9..754031b7af 100644 --- a/tests/regressiontests/delete_regress/tests.py +++ b/tests/regressiontests/delete_regress/tests.py @@ -2,64 +2,65 @@ import datetime from django.conf import settings from django.db import backend, connection, transaction, DEFAULT_DB_ALIAS -from django.test import TestCase, TransactionTestCase +from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from models import Book, Award, AwardNote, Person, Child, Toy, PlayedWith, PlayedWithNote + # Can't run this test under SQLite, because you can't # get two connections to an in-memory database. -if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.sqlite3': - class DeleteLockingTest(TransactionTestCase): - def setUp(self): - # Create a second connection to the default database - conn_settings = settings.DATABASES[DEFAULT_DB_ALIAS] - self.conn2 = backend.DatabaseWrapper({ - 'HOST': conn_settings['HOST'], - 'NAME': conn_settings['NAME'], - 'OPTIONS': conn_settings['OPTIONS'], - 'PASSWORD': conn_settings['PASSWORD'], - 'PORT': conn_settings['PORT'], - 'USER': conn_settings['USER'], - 'TIME_ZONE': settings.TIME_ZONE, - }) +class DeleteLockingTest(TransactionTestCase): + def setUp(self): + # Create a second connection to the default database + conn_settings = settings.DATABASES[DEFAULT_DB_ALIAS] + self.conn2 = backend.DatabaseWrapper({ + 'HOST': conn_settings['HOST'], + 'NAME': conn_settings['NAME'], + 'OPTIONS': conn_settings['OPTIONS'], + 'PASSWORD': conn_settings['PASSWORD'], + 'PORT': conn_settings['PORT'], + 'USER': conn_settings['USER'], + 'TIME_ZONE': settings.TIME_ZONE, + }) - # Put both DB connections into managed transaction mode - transaction.enter_transaction_management() - transaction.managed(True) - self.conn2._enter_transaction_management(True) + # Put both DB connections into managed transaction mode + transaction.enter_transaction_management() + transaction.managed(True) + self.conn2._enter_transaction_management(True) - def tearDown(self): - # Close down the second connection. - transaction.leave_transaction_management() - self.conn2.close() + def tearDown(self): + # Close down the second connection. + transaction.leave_transaction_management() + self.conn2.close() - def test_concurrent_delete(self): - "Deletes on concurrent transactions don't collide and lock the database. Regression for #9479" + @skipUnlessDBFeature('test_db_allows_multiple_connections') + def test_concurrent_delete(self): + "Deletes on concurrent transactions don't collide and lock the database. Regression for #9479" - # Create some dummy data - b1 = Book(id=1, pagecount=100) - b2 = Book(id=2, pagecount=200) - b3 = Book(id=3, pagecount=300) - b1.save() - b2.save() - b3.save() + # Create some dummy data + b1 = Book(id=1, pagecount=100) + b2 = Book(id=2, pagecount=200) + b3 = Book(id=3, pagecount=300) + b1.save() + b2.save() + b3.save() - transaction.commit() + transaction.commit() - self.assertEquals(3, Book.objects.count()) + self.assertEqual(3, Book.objects.count()) - # Delete something using connection 2. - cursor2 = self.conn2.cursor() - cursor2.execute('DELETE from delete_regress_book WHERE id=1') - self.conn2._commit(); + # Delete something using connection 2. + cursor2 = self.conn2.cursor() + cursor2.execute('DELETE from delete_regress_book WHERE id=1') + self.conn2._commit(); - # Now perform a queryset delete that covers the object - # deleted in connection 2. This causes an infinite loop - # under MySQL InnoDB unless we keep track of already - # deleted objects. - Book.objects.filter(pagecount__lt=250).delete() - transaction.commit() - self.assertEquals(1, Book.objects.count()) + # Now perform a queryset delete that covers the object + # deleted in connection 2. This causes an infinite loop + # under MySQL InnoDB unless we keep track of already + # deleted objects. + Book.objects.filter(pagecount__lt=250).delete() + transaction.commit() + self.assertEqual(1, Book.objects.count()) class DeleteCascadeTests(TestCase): def test_generic_relation_cascade(self): diff --git a/tests/regressiontests/dispatch/tests/test_dispatcher.py b/tests/regressiontests/dispatch/tests/test_dispatcher.py index ad3a05f2cd..9ec800fc1b 100644 --- a/tests/regressiontests/dispatch/tests/test_dispatcher.py +++ b/tests/regressiontests/dispatch/tests/test_dispatcher.py @@ -1,7 +1,8 @@ -from django.dispatch import Signal -import unittest -import sys import gc +import sys + +from django.dispatch import Signal +from django.utils import unittest import django.utils.copycompat as copy if sys.platform.startswith('java'): @@ -20,7 +21,7 @@ def receiver_1_arg(val, **kwargs): class Callable(object): def __call__(self, val, **kwargs): return val - + def a(self, val, **kwargs): return val @@ -35,7 +36,7 @@ class DispatcherTests(unittest.TestCase): # force cleanup just in case signal.receivers = [] - + def testExact(self): a_signal.connect(receiver_1_arg, sender=self) expected = [(receiver_1_arg,"test")] @@ -51,7 +52,7 @@ class DispatcherTests(unittest.TestCase): self.assertEqual(result, expected) a_signal.disconnect(receiver_1_arg) self._testIsClean(a_signal) - + def testGarbageCollected(self): a = Callable() a_signal.connect(a.a, sender=self) @@ -61,7 +62,7 @@ class DispatcherTests(unittest.TestCase): result = a_signal.send(sender=self, val="test") self.assertEqual(result, expected) self._testIsClean(a_signal) - + def testMultipleRegistration(self): a = Callable() a_signal.connect(a) @@ -90,7 +91,7 @@ class DispatcherTests(unittest.TestCase): self.assertEqual(len(a_signal.receivers), 1) a_signal.disconnect(dispatch_uid = "uid") self._testIsClean(a_signal) - + def testRobust(self): """Test the sendRobust function""" def fails(val, **kwargs): diff --git a/tests/regressiontests/dispatch/tests/test_saferef.py b/tests/regressiontests/dispatch/tests/test_saferef.py index c0ec879a4b..1b773ebfef 100644 --- a/tests/regressiontests/dispatch/tests/test_saferef.py +++ b/tests/regressiontests/dispatch/tests/test_saferef.py @@ -1,6 +1,6 @@ from django.dispatch.saferef import * -import unittest +from django.utils import unittest class Test1(object): def x(self): diff --git a/tests/regressiontests/expressions_regress/tests.py b/tests/regressiontests/expressions_regress/tests.py index a66272828d..67632f48bb 100644 --- a/tests/regressiontests/expressions_regress/tests.py +++ b/tests/regressiontests/expressions_regress/tests.py @@ -1,14 +1,14 @@ """ Spanning tests for all the operations that F() expressions can perform. """ -from django.test import TestCase, Approximate - from django.conf import settings from django.db import models, DEFAULT_DB_ALIAS from django.db.models import F +from django.test import TestCase, Approximate, skipUnlessDBFeature from regressiontests.expressions_regress.models import Number + class ExpressionsRegressTests(TestCase): def setUp(self): @@ -130,13 +130,13 @@ class ExpressionOperatorTests(TestCase): self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 40) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) - if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.oracle': - def test_lefthand_bitwise_or(self): - # LH Bitwise or on integers - Number.objects.filter(pk=self.n.pk).update(integer=F('integer') | 48) + @skipUnlessDBFeature('supports_bitwise_or') + def test_lefthand_bitwise_or(self): + # LH Bitwise or on integers + Number.objects.filter(pk=self.n.pk).update(integer=F('integer') | 48) - self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 58) - self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) + self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 58) + self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) def test_right_hand_addition(self): # Right hand operators @@ -185,11 +185,11 @@ class ExpressionOperatorTests(TestCase): self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 10) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) - if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.oracle': - def test_right_hand_bitwise_or(self): - # RH Bitwise or on integers - Number.objects.filter(pk=self.n.pk).update(integer=15 | F('integer')) + @skipUnlessDBFeature('supports_bitwise_or') + def test_right_hand_bitwise_or(self): + # RH Bitwise or on integers + Number.objects.filter(pk=self.n.pk).update(integer=15 | F('integer')) - self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 47) - self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) + self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 47) + self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) diff --git a/tests/regressiontests/file_storage/tests.py b/tests/regressiontests/file_storage/tests.py index 88d4f77810..70e3f13ff3 100644 --- a/tests/regressiontests/file_storage/tests.py +++ b/tests/regressiontests/file_storage/tests.py @@ -4,7 +4,6 @@ import shutil import sys import tempfile import time -import unittest from cStringIO import StringIO from datetime import datetime, timedelta from django.conf import settings @@ -14,7 +13,8 @@ from django.core.files.images import get_image_dimensions from django.core.files.storage import FileSystemStorage, get_storage_class from django.core.files.uploadedfile import UploadedFile from django.core.exceptions import ImproperlyConfigured -from unittest import TestCase +from django.utils import unittest + try: import threading except ImportError: @@ -294,7 +294,7 @@ class SlowFile(ContentFile): time.sleep(1) return super(ContentFile, self).chunks() -class FileSaveRaceConditionTest(TestCase): +class FileSaveRaceConditionTest(unittest.TestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) @@ -315,7 +315,7 @@ class FileSaveRaceConditionTest(TestCase): self.storage.delete('conflict') self.storage.delete('conflict_1') -class FileStoragePermissions(TestCase): +class FileStoragePermissions(unittest.TestCase): def setUp(self): self.old_perms = settings.FILE_UPLOAD_PERMISSIONS settings.FILE_UPLOAD_PERMISSIONS = 0666 @@ -332,7 +332,7 @@ class FileStoragePermissions(TestCase): self.assertEqual(actual_mode, 0666) -class FileStoragePathParsing(TestCase): +class FileStoragePathParsing(unittest.TestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) @@ -370,64 +370,67 @@ class FileStoragePathParsing(TestCase): else: self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1'))) -if Image is not None: - class DimensionClosingBug(TestCase): +class DimensionClosingBug(unittest.TestCase): + """ + Test that get_image_dimensions() properly closes files (#8817) + """ + @unittest.skipUnless(Image, "PIL not installed") + def test_not_closing_of_files(self): """ - Test that get_image_dimensions() properly closes files (#8817) + Open files passed into get_image_dimensions() should stay opened. """ - def test_not_closing_of_files(self): - """ - Open files passed into get_image_dimensions() should stay opened. - """ - empty_io = StringIO() - try: - get_image_dimensions(empty_io) - finally: - self.assert_(not empty_io.closed) + empty_io = StringIO() + try: + get_image_dimensions(empty_io) + finally: + self.assert_(not empty_io.closed) - def test_closing_of_filenames(self): - """ - get_image_dimensions() called with a filename should closed the file. - """ - # We need to inject a modified open() builtin into the images module - # that checks if the file was closed properly if the function is - # called with a filename instead of an file object. - # get_image_dimensions will call our catching_open instead of the - # regular builtin one. + @unittest.skipUnless(Image, "PIL not installed") + def test_closing_of_filenames(self): + """ + get_image_dimensions() called with a filename should closed the file. + """ + # We need to inject a modified open() builtin into the images module + # that checks if the file was closed properly if the function is + # called with a filename instead of an file object. + # get_image_dimensions will call our catching_open instead of the + # regular builtin one. - class FileWrapper(object): - _closed = [] - def __init__(self, f): - self.f = f - def __getattr__(self, name): - return getattr(self.f, name) - def close(self): - self._closed.append(True) - self.f.close() + class FileWrapper(object): + _closed = [] + def __init__(self, f): + self.f = f + def __getattr__(self, name): + return getattr(self.f, name) + def close(self): + self._closed.append(True) + self.f.close() - def catching_open(*args): - return FileWrapper(open(*args)) + def catching_open(*args): + return FileWrapper(open(*args)) - from django.core.files import images - images.open = catching_open - try: - get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png")) - finally: - del images.open - self.assert_(FileWrapper._closed) + from django.core.files import images + images.open = catching_open + try: + get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png")) + finally: + del images.open + self.assert_(FileWrapper._closed) - class InconsistentGetImageDimensionsBug(TestCase): +class InconsistentGetImageDimensionsBug(unittest.TestCase): + """ + Test that get_image_dimensions() works properly after various calls + using a file handler (#11158) + """ + @unittest.skipUnless(Image, "PIL not installed") + def test_multiple_calls(self): """ - Test that get_image_dimensions() works properly after various calls using a file handler (#11158) + Multiple calls of get_image_dimensions() should return the same size. """ - def test_multiple_calls(self): - """ - Multiple calls of get_image_dimensions() should return the same size. - """ - from django.core.files.images import ImageFile - img_path = os.path.join(os.path.dirname(__file__), "test.png") - image = ImageFile(open(img_path, 'rb')) - image_pil = Image.open(img_path) - size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image) - self.assertEqual(image_pil.size, size_1) - self.assertEqual(size_1, size_2) + from django.core.files.images import ImageFile + img_path = os.path.join(os.path.dirname(__file__), "test.png") + image = ImageFile(open(img_path, 'rb')) + image_pil = Image.open(img_path) + size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image) + self.assertEqual(image_pil.size, size_1) + self.assertEqual(size_1, size_2) diff --git a/tests/regressiontests/file_uploads/tests.py b/tests/regressiontests/file_uploads/tests.py index 1395cb23ea..ac1ec1656e 100644 --- a/tests/regressiontests/file_uploads/tests.py +++ b/tests/regressiontests/file_uploads/tests.py @@ -2,15 +2,15 @@ import os import errno import shutil -import unittest from StringIO import StringIO from django.core.files import temp as tempfile from django.core.files.uploadedfile import SimpleUploadedFile +from django.http.multipartparser import MultiPartParser from django.test import TestCase, client from django.utils import simplejson +from django.utils import unittest from django.utils.hashcompat import sha_constructor -from django.http.multipartparser import MultiPartParser from models import FileModel, temp_storage, UPLOAD_TO import uploadhandler @@ -223,7 +223,7 @@ class FileUploadTests(TestCase): ret = super(POSTAccessingHandler, self).handle_uncaught_exception(request, resolver, exc_info) p = request.POST return ret - + post_data = { 'name': 'Ringo', 'file_field': open(__file__), @@ -244,7 +244,7 @@ class FileUploadTests(TestCase): response = self.client.post('/file_uploads/upload_errors/', post_data) except reference_error.__class__, err: self.failIf( - str(err) == str(reference_error), + str(err) == str(reference_error), "Caught a repeated exception that'll cause an infinite loop in file uploads." ) except Exception, err: diff --git a/tests/regressiontests/fixtures_regress/models.py b/tests/regressiontests/fixtures_regress/models.py index 9e09a1688b..7c732ce6d4 100644 --- a/tests/regressiontests/fixtures_regress/models.py +++ b/tests/regressiontests/fixtures_regress/models.py @@ -1,4 +1,4 @@ -from django.db import models, DEFAULT_DB_ALIAS +from django.db import models, DEFAULT_DB_ALIAS, connection from django.contrib.auth.models import User from django.conf import settings @@ -31,7 +31,7 @@ class Stuff(models.Model): # Oracle doesn't distinguish between None and the empty string. # This hack makes the test case pass using Oracle. name = self.name - if (settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle' + if (connection.features.interprets_empty_strings_as_nulls and name == u''): name = None return unicode(name) + u' is owned by ' + unicode(self.owner) diff --git a/tests/regressiontests/forms/fields.py b/tests/regressiontests/forms/fields.py index cf0c3f659c..b3212eada2 100644 --- a/tests/regressiontests/forms/fields.py +++ b/tests/regressiontests/forms/fields.py @@ -30,11 +30,10 @@ import re import os from decimal import Decimal -from unittest import TestCase - from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import * from django.forms.widgets import RadioFieldRenderer +from django.utils.unittest import TestCase def fix_os_paths(x): diff --git a/tests/regressiontests/forms/input_formats.py b/tests/regressiontests/forms/input_formats.py index 498c6de9fb..e362620ddb 100644 --- a/tests/regressiontests/forms/input_formats.py +++ b/tests/regressiontests/forms/input_formats.py @@ -1,9 +1,9 @@ from datetime import time, date, datetime -from unittest import TestCase from django import forms from django.conf import settings from django.utils.translation import activate, deactivate +from django.utils.unittest import TestCase class LocalizedTimeTests(TestCase): diff --git a/tests/regressiontests/forms/validators.py b/tests/regressiontests/forms/validators.py index ed8e8fbd9a..cadf660ab8 100644 --- a/tests/regressiontests/forms/validators.py +++ b/tests/regressiontests/forms/validators.py @@ -1,8 +1,7 @@ -from unittest import TestCase - from django import forms from django.core import validators from django.core.exceptions import ValidationError +from django.utils.unittest import TestCase class TestFieldWithValidators(TestCase): diff --git a/tests/regressiontests/forms/widgets.py b/tests/regressiontests/forms/widgets.py index 10483a7675..2c21d197b2 100644 --- a/tests/regressiontests/forms/widgets.py +++ b/tests/regressiontests/forms/widgets.py @@ -1265,10 +1265,9 @@ u'<input type="hidden" name="date_0" value="17.09.2007" /><input type="hidden" n """ - -from django.utils import copycompat as copy -from unittest import TestCase from django import forms +from django.utils import copycompat as copy +from django.utils.unittest import TestCase from django.core.files.uploadedfile import SimpleUploadedFile diff --git a/tests/regressiontests/httpwrappers/tests.py b/tests/regressiontests/httpwrappers/tests.py index d3991aad86..6d452524fe 100644 --- a/tests/regressiontests/httpwrappers/tests.py +++ b/tests/regressiontests/httpwrappers/tests.py @@ -1,7 +1,8 @@ import copy import pickle -import unittest + from django.http import QueryDict, HttpResponse, CompatCookie, BadHeaderError +from django.utils import unittest class QueryDictTests(unittest.TestCase): def test_missing_key(self): @@ -17,7 +18,7 @@ class QueryDictTests(unittest.TestCase): self.assertRaises(AttributeError, q.pop, 'foo') self.assertRaises(AttributeError, q.popitem) self.assertRaises(AttributeError, q.clear) - + def test_immutable_get_with_default(self): q = QueryDict('') self.assertEqual(q.get('foo', 'default'), 'default') @@ -34,7 +35,7 @@ class QueryDictTests(unittest.TestCase): self.assertEqual(q.values(), []) self.assertEqual(len(q), 0) self.assertEqual(q.urlencode(), '') - + def test_single_key_value(self): """Test QueryDict with one key/value pair""" @@ -47,7 +48,7 @@ class QueryDictTests(unittest.TestCase): self.assertEqual(q.get('bar', 'default'), 'default') self.assertEqual(q.getlist('foo'), ['bar']) self.assertEqual(q.getlist('bar'), []) - + self.assertRaises(AttributeError, q.setlist, 'foo', ['bar']) self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar']) @@ -67,16 +68,16 @@ class QueryDictTests(unittest.TestCase): self.assertRaises(AttributeError, q.popitem) self.assertRaises(AttributeError, q.clear) self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar') - + self.assertEqual(q.urlencode(), 'foo=bar') - + def test_mutable_copy(self): """A copy of a QueryDict is mutable.""" q = QueryDict('').copy() self.assertRaises(KeyError, q.__getitem__, "foo") q['name'] = 'john' self.assertEqual(q['name'], 'john') - + def test_mutable_delete(self): q = QueryDict('').copy() q['name'] = 'john' @@ -126,20 +127,20 @@ class QueryDictTests(unittest.TestCase): """Test QueryDict with two key/value pairs with same keys.""" q = QueryDict('vote=yes&vote=no') - + self.assertEqual(q['vote'], u'no') self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar') - + self.assertEqual(q.get('vote', 'default'), u'no') self.assertEqual(q.get('foo', 'default'), 'default') self.assertEqual(q.getlist('vote'), [u'yes', u'no']) self.assertEqual(q.getlist('foo'), []) - + self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz']) self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz']) self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar']) - self.assertEqual(q.has_key('vote'), True) + self.assertEqual(q.has_key('vote'), True) self.assertEqual('vote' in q, True) self.assertEqual(q.has_key('foo'), False) self.assertEqual('foo' in q, False) @@ -148,23 +149,23 @@ class QueryDictTests(unittest.TestCase): self.assertEqual(q.keys(), [u'vote']) self.assertEqual(q.values(), [u'no']) self.assertEqual(len(q), 1) - + self.assertRaises(AttributeError, q.update, {'foo': 'bar'}) self.assertRaises(AttributeError, q.pop, 'foo') self.assertRaises(AttributeError, q.popitem) self.assertRaises(AttributeError, q.clear) self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar') self.assertRaises(AttributeError, q.__delitem__, 'vote') - + def test_invalid_input_encoding(self): """ QueryDicts must be able to handle invalid input encoding (in this case, bad UTF-8 encoding). """ q = QueryDict('foo=bar&foo=\xff') - self.assertEqual(q['foo'], u'\ufffd') + self.assertEqual(q['foo'], u'\ufffd') self.assertEqual(q.getlist('foo'), [u'bar', u'\ufffd']) - + def test_pickle(self): q = QueryDict('') q1 = pickle.loads(pickle.dumps(q, 2)) @@ -172,7 +173,7 @@ class QueryDictTests(unittest.TestCase): q = QueryDict('a=b&c=d') q1 = pickle.loads(pickle.dumps(q, 2)) self.assertEqual(q == q1, True) - q = QueryDict('a=b&c=d&a=1') + q = QueryDict('a=b&c=d&a=1') q1 = pickle.loads(pickle.dumps(q, 2)) self.assertEqual(q == q1 , True) @@ -181,21 +182,21 @@ class QueryDictTests(unittest.TestCase): x = QueryDict("a=1&a=2", mutable=True) y = QueryDict("a=3&a=4") x.update(y) - self.assertEqual(x.getlist('a'), [u'1', u'2', u'3', u'4']) + self.assertEqual(x.getlist('a'), [u'1', u'2', u'3', u'4']) def test_non_default_encoding(self): """#13572 - QueryDict with a non-default encoding""" - q = QueryDict('sbb=one', encoding='rot_13') + q = QueryDict('sbb=one', encoding='rot_13') self.assertEqual(q.encoding , 'rot_13' ) self.assertEqual(q.items() , [(u'foo', u'bar')] ) self.assertEqual(q.urlencode() , 'sbb=one' ) - q = q.copy() + q = q.copy() self.assertEqual(q.encoding , 'rot_13' ) self.assertEqual(q.items() , [(u'foo', u'bar')] ) self.assertEqual(q.urlencode() , 'sbb=one' ) self.assertEqual(copy.copy(q).encoding , 'rot_13' ) self.assertEqual(copy.deepcopy(q).encoding , 'rot_13') - + class HttpResponseTests(unittest.TestCase): def test_unicode_headers(self): r = HttpResponse() @@ -203,10 +204,10 @@ class HttpResponseTests(unittest.TestCase): # If we insert a unicode value it will be converted to an ascii r['value'] = u'test value' self.failUnless(isinstance(r['value'], str)) - + # An error is raised ~hen a unicode object with non-ascii is assigned. self.assertRaises(UnicodeEncodeError, r.__setitem__, 'value', u't\xebst value') - + # An error is raised when a unicode object with non-ASCII format is # passed as initial mimetype or content_type. self.assertRaises(UnicodeEncodeError, HttpResponse, @@ -216,12 +217,12 @@ class HttpResponseTests(unittest.TestCase): self.assertRaises(UnicodeEncodeError, HttpResponse, content_type=u't\xebst value') - # The response also converts unicode keys to strings.) + # The response also converts unicode keys to strings.) r[u'test'] = 'testing key' l = list(r.items()) l.sort() self.assertEqual(l[1], ('test', 'testing key')) - + # It will also raise errors for keys with non-ascii data. self.assertRaises(UnicodeEncodeError, r.__setitem__, u't\xebst key', 'value') diff --git a/tests/regressiontests/humanize/tests.py b/tests/regressiontests/humanize/tests.py index 8b454719a1..e1962ab442 100644 --- a/tests/regressiontests/humanize/tests.py +++ b/tests/regressiontests/humanize/tests.py @@ -1,6 +1,7 @@ -import unittest from datetime import timedelta, date + from django.template import Template, Context, add_to_builtins +from django.utils import unittest from django.utils.dateformat import DateFormat from django.utils.translation import ugettext as _ from django.utils.html import escape diff --git a/tests/regressiontests/introspection/tests.py b/tests/regressiontests/introspection/tests.py index 2a81aa8736..3a6f786417 100644 --- a/tests/regressiontests/introspection/tests.py +++ b/tests/regressiontests/introspection/tests.py @@ -1,6 +1,6 @@ from django.conf import settings from django.db import connection, DEFAULT_DB_ALIAS -from django.test import TestCase +from django.test import TestCase, skipUnlessDBFeature from django.utils import functional from models import Reporter, Article @@ -77,13 +77,13 @@ class IntrospectionTests(TestCase): ) # Regression test for #9991 - 'real' types in postgres - if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'].startswith('django.db.backends.postgresql'): - def test_postgresql_real_type(self): - cursor = connection.cursor() - cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);") - desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table') - cursor.execute('DROP TABLE django_ixn_real_test_table;') - self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField') + @skipUnlessDBFeature('has_real_datatype') + def test_postgresql_real_type(self): + cursor = connection.cursor() + cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);") + desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table') + cursor.execute('DROP TABLE django_ixn_real_test_table;') + self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField') def test_get_relations(self): cursor = connection.cursor() diff --git a/tests/regressiontests/localflavor/tests.py b/tests/regressiontests/localflavor/tests.py index 69682360d3..85e91a0f8d 100644 --- a/tests/regressiontests/localflavor/tests.py +++ b/tests/regressiontests/localflavor/tests.py @@ -1,5 +1,5 @@ -import unittest from django.test import TestCase +from django.utils import unittest # just import your tests here from us.tests import * diff --git a/tests/regressiontests/max_lengths/tests.py b/tests/regressiontests/max_lengths/tests.py index 0fb2f30e20..bfb7da10b7 100644 --- a/tests/regressiontests/max_lengths/tests.py +++ b/tests/regressiontests/max_lengths/tests.py @@ -1,12 +1,12 @@ -from unittest import TestCase from django.db import DatabaseError +from django.utils import unittest from regressiontests.max_lengths.models import PersonWithDefaultMaxLengths, PersonWithCustomMaxLengths -class MaxLengthArgumentsTests(TestCase): - +class MaxLengthArgumentsTests(unittest.TestCase): + def verify_max_length(self, model,field,length): self.assertEquals(model._meta.get_field(field).max_length,length) - + def test_default_max_lengths(self): self.verify_max_length(PersonWithDefaultMaxLengths, 'email', 75) self.verify_max_length(PersonWithDefaultMaxLengths, 'vcard', 100) @@ -19,7 +19,7 @@ class MaxLengthArgumentsTests(TestCase): self.verify_max_length(PersonWithCustomMaxLengths, 'homepage', 250) self.verify_max_length(PersonWithCustomMaxLengths, 'avatar', 250) -class MaxLengthORMTests(TestCase): +class MaxLengthORMTests(unittest.TestCase): def test_custom_max_lengths(self): args = { diff --git a/tests/regressiontests/model_fields/tests.py b/tests/regressiontests/model_fields/tests.py index 58c32b5c0a..a0b45931df 100644 --- a/tests/regressiontests/model_fields/tests.py +++ b/tests/regressiontests/model_fields/tests.py @@ -1,12 +1,12 @@ import datetime -import unittest from decimal import Decimal -import django.test +from django import test from django import forms -from django.db import models from django.core.exceptions import ValidationError +from django.db import models from django.db.models.fields.files import FieldFile +from django.utils import unittest from models import Foo, Bar, Whiz, BigD, BigS, Image, BigInt, Post, NullBooleanModel, BooleanModel, Document @@ -22,7 +22,7 @@ if Image: TwoImageFieldTests -class BasicFieldTests(django.test.TestCase): +class BasicFieldTests(test.TestCase): def test_show_hidden_initial(self): """ Regression test for #12913. Make sure fields with choices respect @@ -48,7 +48,7 @@ class BasicFieldTests(django.test.TestCase): except ValidationError, e: self.fail("NullBooleanField failed validation with value of None: %s" % e.messages) -class DecimalFieldTests(django.test.TestCase): +class DecimalFieldTests(test.TestCase): def test_to_python(self): f = models.DecimalField(max_digits=4, decimal_places=2) self.assertEqual(f.to_python(3), Decimal("3")) @@ -95,7 +95,7 @@ class DecimalFieldTests(django.test.TestCase): # This should not crash. That counts as a win for our purposes. Foo.objects.filter(d__gte=100000000000) -class ForeignKeyTests(django.test.TestCase): +class ForeignKeyTests(test.TestCase): def test_callable_default(self): """Test the use of a lazy callable for ForeignKey.default""" a = Foo.objects.create(id=1, a='abc', d=Decimal("12.34")) @@ -194,7 +194,7 @@ class BooleanFieldTests(unittest.TestCase): select={'string_length': 'LENGTH(string)'})[0] self.assertFalse(isinstance(b5.pk, bool)) -class ChoicesTests(django.test.TestCase): +class ChoicesTests(test.TestCase): def test_choices_and_field_display(self): """ Check that get_choices and get_flatchoices interact with @@ -206,7 +206,7 @@ class ChoicesTests(django.test.TestCase): self.assertEqual(Whiz(c=None).get_c_display(), None) # Blank value self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value -class SlugFieldTests(django.test.TestCase): +class SlugFieldTests(test.TestCase): def test_slugfield_max_length(self): """ Make sure SlugField honors max_length (#9706) @@ -216,7 +216,7 @@ class SlugFieldTests(django.test.TestCase): self.assertEqual(bs.s, 'slug'*50) -class ValidationTest(django.test.TestCase): +class ValidationTest(test.TestCase): def test_charfield_raises_error_on_empty_string(self): f = models.CharField() self.assertRaises(ValidationError, f.clean, "", None) @@ -271,7 +271,7 @@ class ValidationTest(django.test.TestCase): self.assertRaises(ValidationError, f.clean, None, None) -class BigIntegerFieldTests(django.test.TestCase): +class BigIntegerFieldTests(test.TestCase): def test_limits(self): # Ensure that values that are right at the limits can be saved # and then retrieved without corruption. @@ -299,7 +299,7 @@ class BigIntegerFieldTests(django.test.TestCase): b = BigInt.objects.get(value = '10') self.assertEqual(b.value, 10) -class TypeCoercionTests(django.test.TestCase): +class TypeCoercionTests(test.TestCase): """ Test that database lookups can accept the wrong types and convert them with no error: especially on Postgres 8.3+ which does not do diff --git a/tests/regressiontests/model_regress/models.py b/tests/regressiontests/model_regress/models.py index 420f2c262c..6d1573aea3 100644 --- a/tests/regressiontests/model_regress/models.py +++ b/tests/regressiontests/model_regress/models.py @@ -2,7 +2,7 @@ import datetime from django.conf import settings -from django.db import models, DEFAULT_DB_ALIAS +from django.db import models, DEFAULT_DB_ALIAS, connection from django.utils import tzinfo CHOICES = ( @@ -149,9 +149,7 @@ datetime.datetime(2000, 1, 1, 6, 1, 1) """} -if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] not in ( - "django.db.backends.mysql", - "django.db.backends.oracle"): +if connection.features.supports_timezones: __test__["timezone-tests"] = """ # Saving an updating with timezone-aware datetime Python objects. Regression # test for #10443. diff --git a/tests/regressiontests/pagination_regress/tests.py b/tests/regressiontests/pagination_regress/tests.py index 08436df355..28fe3163eb 100644 --- a/tests/regressiontests/pagination_regress/tests.py +++ b/tests/regressiontests/pagination_regress/tests.py @@ -1,6 +1,5 @@ -from unittest import TestCase - from django.core.paginator import Paginator, EmptyPage +from django.utils.unittest import TestCase class PaginatorTests(TestCase): """ diff --git a/tests/regressiontests/queries/models.py b/tests/regressiontests/queries/models.py index f22cfb3af3..88022163f8 100644 --- a/tests/regressiontests/queries/models.py +++ b/tests/regressiontests/queries/models.py @@ -8,7 +8,7 @@ import sys import threading from django.conf import settings -from django.db import models, DEFAULT_DB_ALIAS +from django.db import models, DEFAULT_DB_ALIAS, connection from django.db.models import Count from django.db.models.query import Q, ITER_CHUNK_SIZE, EmptyQuerySet @@ -1307,13 +1307,13 @@ FieldError: Infinite loop caused by ordering. # In Oracle, we expect a null CharField to return u'' instead of None. -if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == "django.db.backends.oracle": +if connection.features.interprets_empty_strings_as_nulls: __test__["API_TESTS"] = __test__["API_TESTS"].replace("<NONE_OR_EMPTY_UNICODE>", "u''") else: __test__["API_TESTS"] = __test__["API_TESTS"].replace("<NONE_OR_EMPTY_UNICODE>", "None") -if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == "django.db.backends.mysql": +if connection.features.requires_explicit_null_ordering_when_grouping: __test__["API_TESTS"] += """ When grouping without specifying ordering, we add an explicit "ORDER BY NULL" portion in MySQL to prevent unnecessary sorting. @@ -1342,7 +1342,7 @@ Using an empty generator expression as the rvalue for an "__in" lookup is legal # Sqlite 3 does not support passing in more than 1000 parameters except by # changing a parameter at compilation time. -if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != "django.db.backends.sqlite3": +if connection.features.supports_1000_query_paramters: __test__["API_TESTS"] += """ Bug #14244: Test that the "in" lookup works with lists of 1000 items or more. >>> Number.objects.all().delete() diff --git a/tests/regressiontests/queries/tests.py b/tests/regressiontests/queries/tests.py index ab5369246d..7d393bc2aa 100644 --- a/tests/regressiontests/queries/tests.py +++ b/tests/regressiontests/queries/tests.py @@ -1,8 +1,7 @@ -import unittest - from django.db import DatabaseError, connections, DEFAULT_DB_ALIAS from django.db.models import Count from django.test import TestCase +from django.utils import unittest from models import Tag, Annotation, DumbCategory, Note, ExtraInfo, Number diff --git a/tests/regressiontests/serializers_regress/tests.py b/tests/regressiontests/serializers_regress/tests.py index be920c6920..4180143e21 100644 --- a/tests/regressiontests/serializers_regress/tests.py +++ b/tests/regressiontests/serializers_regress/tests.py @@ -17,7 +17,7 @@ except ImportError: from django.conf import settings from django.core import serializers, management -from django.db import transaction, DEFAULT_DB_ALIAS +from django.db import transaction, DEFAULT_DB_ALIAS, connection from django.test import TestCase from django.utils.functional import curry @@ -335,7 +335,7 @@ The end."""), # Because Oracle treats the empty string as NULL, Oracle is expected to fail # when field.empty_strings_allowed is True and the value is None; skip these # tests. -if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle': +if connection.features.interprets_empty_strings_as_nulls: test_data = [data for data in test_data if not (data[0] == data_obj and data[2]._meta.get_field('data').empty_strings_allowed and @@ -344,7 +344,7 @@ if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle' # Regression test for #8651 -- a FK to an object iwth PK of 0 # This won't work on MySQL since it won't let you create an object # with a primary key of 0, -if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] != 'django.db.backends.mysql': +if connection.features.allows_primary_key_0: test_data.extend([ (data_obj, 0, Anchor, "Anchor 0"), (fk_obj, 465, FKData, 0), diff --git a/tests/regressiontests/settings_tests/tests.py b/tests/regressiontests/settings_tests/tests.py index fa217b1d79..1b129d8c6f 100644 --- a/tests/regressiontests/settings_tests/tests.py +++ b/tests/regressiontests/settings_tests/tests.py @@ -1,5 +1,5 @@ -import unittest from django.conf import settings +from django.utils import unittest class SettingsTests(unittest.TestCase): diff --git a/tests/regressiontests/templates/loaders.py b/tests/regressiontests/templates/loaders.py index 40beb2997a..c59f838b4b 100644 --- a/tests/regressiontests/templates/loaders.py +++ b/tests/regressiontests/templates/loaders.py @@ -9,7 +9,6 @@ from django.conf import settings if __name__ == '__main__': settings.configure() -import unittest import sys import pkg_resources import imp @@ -21,6 +20,8 @@ from django.template import TemplateDoesNotExist, Context from django.template.loaders.eggs import load_template_source as lts_egg from django.template.loaders.eggs import Loader as EggLoader from django.template import loader +from django.utils import unittest + # Mock classes and objects for pkg_resources functions. class MockProvider(pkg_resources.NullProvider): @@ -73,6 +74,7 @@ class DeprecatedEggLoaderTest(unittest.TestCase): def tearDown(self): settings.INSTALLED_APPS = self._old_installed_apps warnings.resetwarnings() + warnings.simplefilter("ignore", PendingDeprecationWarning) def test_existing(self): "A template can be loaded from an egg" @@ -80,8 +82,6 @@ class DeprecatedEggLoaderTest(unittest.TestCase): contents, template_name = lts_egg("y.html") self.assertEqual(contents, "y") self.assertEqual(template_name, "egg:egg_1:templates/y.html") - warnings.resetwarnings() - warnings.simplefilter("ignore", PendingDeprecationWarning) class EggLoaderTest(unittest.TestCase): diff --git a/tests/regressiontests/templates/nodelist.py b/tests/regressiontests/templates/nodelist.py index 89fac97c66..48775397ae 100644 --- a/tests/regressiontests/templates/nodelist.py +++ b/tests/regressiontests/templates/nodelist.py @@ -1,6 +1,6 @@ -from unittest import TestCase from django.template.loader import get_template_from_string from django.template import VariableNode +from django.utils.unittest import TestCase class NodelistTest(TestCase): diff --git a/tests/regressiontests/templates/smartif.py b/tests/regressiontests/templates/smartif.py index 5e5d7704e7..fac453bf57 100644 --- a/tests/regressiontests/templates/smartif.py +++ b/tests/regressiontests/templates/smartif.py @@ -1,5 +1,5 @@ -import unittest from django.template.smartif import IfParser, Literal +from django.utils import unittest class SmartIfTests(unittest.TestCase): diff --git a/tests/regressiontests/templates/tests.py b/tests/regressiontests/templates/tests.py index 9e2d175677..39fb30ac98 100644 --- a/tests/regressiontests/templates/tests.py +++ b/tests/regressiontests/templates/tests.py @@ -11,12 +11,12 @@ import time import os import sys import traceback -import unittest from django import template from django.core import urlresolvers from django.template import loader from django.template.loaders import app_directories, filesystem, cached +from django.utils import unittest from django.utils.translation import activate, deactivate, ugettext as _ from django.utils.safestring import mark_safe from django.utils.tzinfo import LocalTimezone @@ -506,16 +506,16 @@ class Templates(unittest.TestCase): 'basic-syntax28': ("{{ a.b }}", {'a': SilentGetItemClass()}, ('', 'INVALID')), 'basic-syntax29': ("{{ a.b }}", {'a': SilentAttrClass()}, ('', 'INVALID')), - # Something that starts like a number but has an extra lookup works as a lookup. - 'basic-syntax30': ("{{ 1.2.3 }}", {"1": {"2": {"3": "d"}}}, "d"), - 'basic-syntax31': ("{{ 1.2.3 }}", {"1": {"2": ("a", "b", "c", "d")}}, "d"), - 'basic-syntax32': ("{{ 1.2.3 }}", {"1": (("x", "x", "x", "x"), ("y", "y", "y", "y"), ("a", "b", "c", "d"))}, "d"), - 'basic-syntax33': ("{{ 1.2.3 }}", {"1": ("xxxx", "yyyy", "abcd")}, "d"), - 'basic-syntax34': ("{{ 1.2.3 }}", {"1": ({"x": "x"}, {"y": "y"}, {"z": "z", "3": "d"})}, "d"), - - # Numbers are numbers even if their digits are in the context. - 'basic-syntax35': ("{{ 1 }}", {"1": "abc"}, "1"), - 'basic-syntax36': ("{{ 1.2 }}", {"1": "abc"}, "1.2"), + # Something that starts like a number but has an extra lookup works as a lookup. + 'basic-syntax30': ("{{ 1.2.3 }}", {"1": {"2": {"3": "d"}}}, "d"), + 'basic-syntax31': ("{{ 1.2.3 }}", {"1": {"2": ("a", "b", "c", "d")}}, "d"), + 'basic-syntax32': ("{{ 1.2.3 }}", {"1": (("x", "x", "x", "x"), ("y", "y", "y", "y"), ("a", "b", "c", "d"))}, "d"), + 'basic-syntax33': ("{{ 1.2.3 }}", {"1": ("xxxx", "yyyy", "abcd")}, "d"), + 'basic-syntax34': ("{{ 1.2.3 }}", {"1": ({"x": "x"}, {"y": "y"}, {"z": "z", "3": "d"})}, "d"), + + # Numbers are numbers even if their digits are in the context. + 'basic-syntax35': ("{{ 1 }}", {"1": "abc"}, "1"), + 'basic-syntax36': ("{{ 1.2 }}", {"1": "abc"}, "1.2"), # List-index syntax allows a template to access a certain item of a subscriptable object. 'list-index01': ("{{ var.1 }}", {"var": ["first item", "second item"]}, "second item"), @@ -603,7 +603,7 @@ class Templates(unittest.TestCase): #filters should accept empty string constants 'filter-syntax20': ('{{ ""|default_if_none:"was none" }}', {}, ""), - + ### COMMENT SYNTAX ######################################################## 'comment-syntax01': ("{# this is hidden #}hello", {}, "hello"), 'comment-syntax02': ("{# this is hidden #}hello{# foo #}", {}, "hello"), @@ -1300,8 +1300,8 @@ class Templates(unittest.TestCase): # Regression test for #11270. 'cache17': ('{% load cache %}{% cache 10 long_cache_key poem %}Some Content{% endcache %}', {'poem': 'Oh freddled gruntbuggly/Thy micturations are to me/As plurdled gabbleblotchits/On a lurgid bee/That mordiously hath bitled out/Its earted jurtles/Into a rancid festering/Or else I shall rend thee in the gobberwarts with my blurglecruncheon/See if I dont.'}, 'Some Content'), - - + + ### AUTOESCAPE TAG ############################################## 'autoescape-tag01': ("{% autoescape off %}hello{% endautoescape %}", {}, "hello"), 'autoescape-tag02': ("{% autoescape off %}{{ first }}{% endautoescape %}", {"first": "<b>hello</b>"}, "<b>hello</b>"), @@ -1330,23 +1330,23 @@ class Templates(unittest.TestCase): # implementation details (fortunately, the (no)autoescape block # tags can be used in those cases) 'autoescape-filtertag01': ("{{ first }}{% filter safe %}{{ first }} x<y{% endfilter %}", {"first": "<a>"}, template.TemplateSyntaxError), - + # ifqeual compares unescaped vales. - 'autoescape-ifequal01': ('{% ifequal var "this & that" %}yes{% endifequal %}', { "var": "this & that" }, "yes" ), - - # Arguments to filters are 'safe' and manipulate their input unescaped. - 'autoescape-filters01': ('{{ var|cut:"&" }}', { "var": "this & that" }, "this that" ), - 'autoescape-filters02': ('{{ var|join:" & \" }}', { "var": ("Tom", "Dick", "Harry") }, "Tom & Dick & Harry" ), - - # Literal strings are safe. - 'autoescape-literals01': ('{{ "this & that" }}',{}, "this & that" ), - - # Iterating over strings outputs safe characters. - 'autoescape-stringiterations01': ('{% for l in var %}{{ l }},{% endfor %}', {'var': 'K&R'}, "K,&,R," ), - - # Escape requirement survives lookup. - 'autoescape-lookup01': ('{{ var.key }}', { "var": {"key": "this & that" }}, "this & that" ), - + 'autoescape-ifequal01': ('{% ifequal var "this & that" %}yes{% endifequal %}', { "var": "this & that" }, "yes" ), + + # Arguments to filters are 'safe' and manipulate their input unescaped. + 'autoescape-filters01': ('{{ var|cut:"&" }}', { "var": "this & that" }, "this that" ), + 'autoescape-filters02': ('{{ var|join:" & \" }}', { "var": ("Tom", "Dick", "Harry") }, "Tom & Dick & Harry" ), + + # Literal strings are safe. + 'autoescape-literals01': ('{{ "this & that" }}',{}, "this & that" ), + + # Iterating over strings outputs safe characters. + 'autoescape-stringiterations01': ('{% for l in var %}{{ l }},{% endfor %}', {'var': 'K&R'}, "K,&,R," ), + + # Escape requirement survives lookup. + 'autoescape-lookup01': ('{{ var.key }}', { "var": {"key": "this & that" }}, "this & that" ), + } diff --git a/tests/regressiontests/test_client_regress/models.py b/tests/regressiontests/test_client_regress/models.py index 20ed3af82f..851d204a54 100644 --- a/tests/regressiontests/test_client_regress/models.py +++ b/tests/regressiontests/test_client_regress/models.py @@ -35,83 +35,83 @@ class AssertContainsTests(TestCase): try: self.assertContains(response, 'text', status_code=999) except AssertionError, e: - self.assertEquals(str(e), "Couldn't retrieve content: Response code was 200 (expected 999)") + self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertContains(response, 'text', status_code=999, msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Couldn't retrieve content: Response code was 200 (expected 999)") + self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertNotContains(response, 'text', status_code=999) except AssertionError, e: - self.assertEquals(str(e), "Couldn't retrieve content: Response code was 200 (expected 999)") + self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertNotContains(response, 'text', status_code=999, msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Couldn't retrieve content: Response code was 200 (expected 999)") + self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertNotContains(response, 'once') except AssertionError, e: - self.assertEquals(str(e), "Response should not contain 'once'") + self.assertIn("Response should not contain 'once'", str(e)) try: self.assertNotContains(response, 'once', msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Response should not contain 'once'") + self.assertIn("abc: Response should not contain 'once'", str(e)) try: self.assertContains(response, 'never', 1) except AssertionError, e: - self.assertEquals(str(e), "Found 0 instances of 'never' in response (expected 1)") + self.assertIn("Found 0 instances of 'never' in response (expected 1)", str(e)) try: self.assertContains(response, 'never', 1, msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Found 0 instances of 'never' in response (expected 1)") + self.assertIn("abc: Found 0 instances of 'never' in response (expected 1)", str(e)) try: self.assertContains(response, 'once', 0) except AssertionError, e: - self.assertEquals(str(e), "Found 1 instances of 'once' in response (expected 0)") + self.assertIn("Found 1 instances of 'once' in response (expected 0)", str(e)) try: self.assertContains(response, 'once', 0, msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Found 1 instances of 'once' in response (expected 0)") + self.assertIn("abc: Found 1 instances of 'once' in response (expected 0)", str(e)) try: self.assertContains(response, 'once', 2) except AssertionError, e: - self.assertEquals(str(e), "Found 1 instances of 'once' in response (expected 2)") + self.assertIn("Found 1 instances of 'once' in response (expected 2)", str(e)) try: self.assertContains(response, 'once', 2, msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Found 1 instances of 'once' in response (expected 2)") + self.assertIn("abc: Found 1 instances of 'once' in response (expected 2)", str(e)) try: self.assertContains(response, 'twice', 1) except AssertionError, e: - self.assertEquals(str(e), "Found 2 instances of 'twice' in response (expected 1)") + self.assertIn("Found 2 instances of 'twice' in response (expected 1)", str(e)) try: self.assertContains(response, 'twice', 1, msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Found 2 instances of 'twice' in response (expected 1)") + self.assertIn("abc: Found 2 instances of 'twice' in response (expected 1)", str(e)) try: self.assertContains(response, 'thrice') except AssertionError, e: - self.assertEquals(str(e), "Couldn't find 'thrice' in response") + self.assertIn("Couldn't find 'thrice' in response", str(e)) try: self.assertContains(response, 'thrice', msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Couldn't find 'thrice' in response") + self.assertIn("abc: Couldn't find 'thrice' in response", str(e)) try: self.assertContains(response, 'thrice', 3) except AssertionError, e: - self.assertEquals(str(e), "Found 0 instances of 'thrice' in response (expected 3)") + self.assertIn("Found 0 instances of 'thrice' in response (expected 3)", str(e)) try: self.assertContains(response, 'thrice', 3, msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Found 0 instances of 'thrice' in response (expected 3)") + self.assertIn("abc: Found 0 instances of 'thrice' in response (expected 3)", str(e)) def test_unicode_contains(self): "Unicode characters can be found in template context" @@ -141,12 +141,12 @@ class AssertTemplateUsedTests(TestCase): try: self.assertTemplateUsed(response, 'GET Template') except AssertionError, e: - self.assertEquals(str(e), "No templates used to render the response") + self.assertIn("No templates used to render the response", str(e)) try: self.assertTemplateUsed(response, 'GET Template', msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: No templates used to render the response") + self.assertIn("abc: No templates used to render the response", str(e)) def test_single_context(self): "Template assertions work when there is a single context" @@ -155,22 +155,22 @@ class AssertTemplateUsedTests(TestCase): try: self.assertTemplateNotUsed(response, 'Empty GET Template') except AssertionError, e: - self.assertEquals(str(e), "Template 'Empty GET Template' was used unexpectedly in rendering the response") + self.assertIn("Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateNotUsed(response, 'Empty GET Template', msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Template 'Empty GET Template' was used unexpectedly in rendering the response") + self.assertIn("abc: Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateUsed(response, 'Empty POST Template') except AssertionError, e: - self.assertEquals(str(e), "Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template") + self.assertIn("Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e)) try: self.assertTemplateUsed(response, 'Empty POST Template', msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template") + self.assertIn("abc: Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e)) def test_multiple_context(self): "Template assertions work when there are multiple contexts" @@ -186,17 +186,17 @@ class AssertTemplateUsedTests(TestCase): try: self.assertTemplateNotUsed(response, "form_view.html") except AssertionError, e: - self.assertEquals(str(e), "Template 'form_view.html' was used unexpectedly in rendering the response") + self.assertIn("Template 'form_view.html' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateNotUsed(response, 'base.html') except AssertionError, e: - self.assertEquals(str(e), "Template 'base.html' was used unexpectedly in rendering the response") + self.assertIn("Template 'base.html' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateUsed(response, "Valid POST Template") except AssertionError, e: - self.assertEquals(str(e), "Template 'Valid POST Template' was not a template used to render the response. Actual template(s) used: form_view.html, base.html") + self.assertIn("Template 'Valid POST Template' was not a template used to render the response. Actual template(s) used: form_view.html, base.html", str(e)) class AssertRedirectsTests(TestCase): def test_redirect_page(self): @@ -206,12 +206,12 @@ class AssertRedirectsTests(TestCase): try: self.assertRedirects(response, '/test_client/get_view/') except AssertionError, e: - self.assertEquals(str(e), "Response didn't redirect as expected: Response code was 301 (expected 302)") + self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) try: self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Response didn't redirect as expected: Response code was 301 (expected 302)") + self.assertIn("abc: Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) def test_lost_query(self): "An assertion is raised if the redirect location doesn't preserve GET parameters" @@ -219,12 +219,12 @@ class AssertRedirectsTests(TestCase): try: self.assertRedirects(response, '/test_client/get_view/') except AssertionError, e: - self.assertEquals(str(e), "Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'") + self.assertIn("Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e)) try: self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'") + self.assertIn("abc: Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e)) def test_incorrect_target(self): "An assertion is raised if the response redirects to another target" @@ -233,7 +233,7 @@ class AssertRedirectsTests(TestCase): # Should redirect to get_view self.assertRedirects(response, '/test_client/some_view/') except AssertionError, e: - self.assertEquals(str(e), "Response didn't redirect as expected: Response code was 301 (expected 302)") + self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) def test_target_page(self): "An assertion is raised if the response redirect target cannot be retrieved as expected" @@ -242,13 +242,13 @@ class AssertRedirectsTests(TestCase): # The redirect target responds with a 301 code, not 200 self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/') except AssertionError, e: - self.assertEquals(str(e), "Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)") + self.assertIn("Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e)) try: # The redirect target responds with a 301 code, not 200 self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)") + self.assertIn("abc: Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e)) def test_redirect_chain(self): "You can follow a redirect chain of multiple redirects" @@ -339,12 +339,12 @@ class AssertRedirectsTests(TestCase): try: self.assertRedirects(response, '/test_client/get_view/') except AssertionError, e: - self.assertEquals(str(e), "Response didn't redirect as expected: Response code was 200 (expected 302)") + self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) try: self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Response didn't redirect as expected: Response code was 200 (expected 302)") + self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) def test_redirect_on_non_redirect_page(self): "An assertion is raised if the original page couldn't be retrieved as expected" @@ -353,12 +353,12 @@ class AssertRedirectsTests(TestCase): try: self.assertRedirects(response, '/test_client/get_view/') except AssertionError, e: - self.assertEquals(str(e), "Response didn't redirect as expected: Response code was 200 (expected 302)") + self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) try: self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') except AssertionError, e: - self.assertEquals(str(e), "abc: Response didn't redirect as expected: Response code was 200 (expected 302)") + self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) class AssertFormErrorTests(TestCase): @@ -378,11 +378,11 @@ class AssertFormErrorTests(TestCase): try: self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.') except AssertionError, e: - self.assertEqual(str(e), "The form 'wrong_form' was not used to render the response") + self.assertIn("The form 'wrong_form' was not used to render the response", str(e)) try: self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.', msg_prefix='abc') except AssertionError, e: - self.assertEqual(str(e), "abc: The form 'wrong_form' was not used to render the response") + self.assertIn("abc: The form 'wrong_form' was not used to render the response", str(e)) def test_unknown_field(self): "An assertion is raised if the field name is unknown" @@ -400,11 +400,11 @@ class AssertFormErrorTests(TestCase): try: self.assertFormError(response, 'form', 'some_field', 'Some error.') except AssertionError, e: - self.assertEqual(str(e), "The form 'form' in context 0 does not contain the field 'some_field'") + self.assertIn("The form 'form' in context 0 does not contain the field 'some_field'", str(e)) try: self.assertFormError(response, 'form', 'some_field', 'Some error.', msg_prefix='abc') except AssertionError, e: - self.assertEqual(str(e), "abc: The form 'form' in context 0 does not contain the field 'some_field'") + self.assertIn("abc: The form 'form' in context 0 does not contain the field 'some_field'", str(e)) def test_noerror_field(self): "An assertion is raised if the field doesn't have any errors" @@ -422,11 +422,11 @@ class AssertFormErrorTests(TestCase): try: self.assertFormError(response, 'form', 'value', 'Some error.') except AssertionError, e: - self.assertEqual(str(e), "The field 'value' on form 'form' in context 0 contains no errors") + self.assertIn("The field 'value' on form 'form' in context 0 contains no errors", str(e)) try: self.assertFormError(response, 'form', 'value', 'Some error.', msg_prefix='abc') except AssertionError, e: - self.assertEqual(str(e), "abc: The field 'value' on form 'form' in context 0 contains no errors") + self.assertIn("abc: The field 'value' on form 'form' in context 0 contains no errors", str(e)) def test_unknown_error(self): "An assertion is raised if the field doesn't contain the provided error" @@ -444,11 +444,11 @@ class AssertFormErrorTests(TestCase): try: self.assertFormError(response, 'form', 'email', 'Some error.') except AssertionError, e: - self.assertEqual(str(e), "The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])") + self.assertIn("The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])", str(e)) try: self.assertFormError(response, 'form', 'email', 'Some error.', msg_prefix='abc') except AssertionError, e: - self.assertEqual(str(e), "abc: The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])") + self.assertIn("abc: The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])", str(e)) def test_unknown_nonfield_error(self): """ @@ -469,11 +469,11 @@ class AssertFormErrorTests(TestCase): try: self.assertFormError(response, 'form', None, 'Some error.') except AssertionError, e: - self.assertEqual(str(e), "The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )") + self.assertIn("The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e)) try: self.assertFormError(response, 'form', None, 'Some error.', msg_prefix='abc') except AssertionError, e: - self.assertEqual(str(e), "abc: The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )") + self.assertIn("abc: The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e)) class LoginTests(TestCase): fixtures = ['testdata'] diff --git a/tests/regressiontests/test_runner/tests.py b/tests/regressiontests/test_runner/tests.py index d8db7baf94..2cc09d6cf3 100644 --- a/tests/regressiontests/test_runner/tests.py +++ b/tests/regressiontests/test_runner/tests.py @@ -2,9 +2,9 @@ Tests for django test runner """ import StringIO -import unittest -import django + from django.test import simple +from django.utils import unittest class DjangoTestRunnerTests(unittest.TestCase): diff --git a/tests/regressiontests/urlpatterns_reverse/tests.py b/tests/regressiontests/urlpatterns_reverse/tests.py index 477b0b7b3f..140a6bbd4a 100644 --- a/tests/regressiontests/urlpatterns_reverse/tests.py +++ b/tests/regressiontests/urlpatterns_reverse/tests.py @@ -1,8 +1,6 @@ """ Unit tests for reverse URL lookups. """ -import unittest - from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse, resolve, NoReverseMatch,\ @@ -11,6 +9,7 @@ from django.core.urlresolvers import reverse, resolve, NoReverseMatch,\ from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect from django.shortcuts import redirect from django.test import TestCase +from django.utils import unittest import urlconf_outer import urlconf_inner diff --git a/tests/regressiontests/utils/dateformat.py b/tests/regressiontests/utils/dateformat.py index b312c8d2aa..e785eec724 100644 --- a/tests/regressiontests/utils/dateformat.py +++ b/tests/regressiontests/utils/dateformat.py @@ -1,12 +1,12 @@ from datetime import datetime, date import os import time -import unittest from django.utils.dateformat import format -from django.utils import dateformat, translation +from django.utils import dateformat, translation, unittest from django.utils.tzinfo import FixedOffset, LocalTimezone + class DateFormatTests(unittest.TestCase): def setUp(self): self.old_TZ = os.environ.get('TZ') diff --git a/tests/regressiontests/utils/feedgenerator.py b/tests/regressiontests/utils/feedgenerator.py index 9085d41c06..c62bd2b03a 100644 --- a/tests/regressiontests/utils/feedgenerator.py +++ b/tests/regressiontests/utils/feedgenerator.py @@ -1,7 +1,6 @@ import datetime -import unittest -from django.utils import feedgenerator, tzinfo +from django.utils import feedgenerator, tzinfo, unittest class FeedgeneratorTest(unittest.TestCase): """ diff --git a/tests/regressiontests/utils/functional.py b/tests/regressiontests/utils/functional.py index 206a5838b5..763d6964c1 100644 --- a/tests/regressiontests/utils/functional.py +++ b/tests/regressiontests/utils/functional.py @@ -1,5 +1,4 @@ -import unittest - +from django.utils import unittest from django.utils.functional import lazy diff --git a/tests/regressiontests/utils/module_loading.py b/tests/regressiontests/utils/module_loading.py index 4422f8f5d8..a9e2c7907b 100644 --- a/tests/regressiontests/utils/module_loading.py +++ b/tests/regressiontests/utils/module_loading.py @@ -1,11 +1,12 @@ import os import sys -import unittest from zipimport import zipimporter +from django.utils import unittest from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule + class DefaultLoader(unittest.TestCase): def test_loader(self): "Normal module existence can be tested" diff --git a/tests/regressiontests/utils/termcolors.py b/tests/regressiontests/utils/termcolors.py index ccae32cd16..7efac0dc9f 100644 --- a/tests/regressiontests/utils/termcolors.py +++ b/tests/regressiontests/utils/termcolors.py @@ -1,5 +1,4 @@ -import unittest - +from django.utils import unittest from django.utils.termcolors import parse_color_setting, PALETTES, DEFAULT_PALETTE, LIGHT_PALETTE, DARK_PALETTE, NOCOLOR_PALETTE class TermColorTests(unittest.TestCase): diff --git a/tests/runtests.py b/tests/runtests.py index 64adc80041..a5f7479128 100755 --- a/tests/runtests.py +++ b/tests/runtests.py @@ -1,9 +1,8 @@ #!/usr/bin/env python - import os, subprocess, sys, traceback -import unittest import django.contrib as contrib +from django.utils import unittest CONTRIB_DIR_NAME = 'django.contrib' MODEL_TESTS_DIR_NAME = 'modeltests' @@ -256,7 +255,7 @@ def paired_tests(paired_test, options, test_labels): print '***** Trying paired execution' - # Make sure the bisection point isn't in the test list + # Make sure the constant member of the pair isn't in the test list # Also remove tests that need to be run in specific combinations for label in [paired_test, 'model_inheritance_same_model_name']: try: |
