summaryrefslogtreecommitdiff
path: root/django/test
diff options
context:
space:
mode:
Diffstat (limited to 'django/test')
-rw-r--r--django/test/client.py11
-rw-r--r--django/test/testcases.py11
-rw-r--r--django/test/utils.py49
3 files changed, 46 insertions, 25 deletions
diff --git a/django/test/client.py b/django/test/client.py
index 7e62715205..9ec3615973 100644
--- a/django/test/client.py
+++ b/django/test/client.py
@@ -253,3 +253,14 @@ class Client:
else:
return False
+ def logout(self):
+ """Removes the authenticated user's cookies.
+
+ Causes the authenticated user to be logged out.
+ """
+ try:
+ Session.objects.get(session_key=self.cookies['sessionid'].value).delete()
+ except KeyError:
+ pass
+
+ self.cookies = SimpleCookie()
diff --git a/django/test/testcases.py b/django/test/testcases.py
index 5373d822df..21c429271c 100644
--- a/django/test/testcases.py
+++ b/django/test/testcases.py
@@ -1,7 +1,8 @@
import re, unittest
from urlparse import urlparse
from django.db import transaction
-from django.core import management, mail
+from django.core import mail
+from django.core.management import call_command
from django.db.models import get_apps
from django.test import _doctest as doctest
from django.test.client import Client
@@ -42,9 +43,11 @@ class TestCase(unittest.TestCase):
* Clearing the mail test outbox.
"""
- management.flush(verbosity=0, interactive=False)
+ call_command('flush', verbosity=0, interactive=False)
if hasattr(self, 'fixtures'):
- management.load_data(self.fixtures, verbosity=0)
+ # We have to use this slightly awkward syntax due to the fact
+ # that we're using *args and **kwargs together.
+ call_command('loaddata', *self.fixtures, **{'verbosity': 0})
mail.outbox = []
def __call__(self, result=None):
@@ -88,7 +91,7 @@ class TestCase(unittest.TestCase):
self.assertEqual(real_count, count,
"Found %d instances of '%s' in response (expected %d)" % (real_count, text, count))
else:
- self.assertTrue(real_count != 0, "Couldn't find '%s' in response" % text)
+ self.failUnless(real_count != 0, "Couldn't find '%s' in response" % text)
def assertFormError(self, response, form, field, errors):
"Assert that a form used to render the response has a specific field error"
diff --git a/django/test/utils.py b/django/test/utils.py
index e9525b4dd4..bc53ef4bfb 100644
--- a/django/test/utils.py
+++ b/django/test/utils.py
@@ -1,8 +1,8 @@
import sys, time
from django.conf import settings
from django.db import connection, backend, get_creation_module
-from django.core import management, mail
-from django.core import management, mail
+from django.core import mail
+from django.core.management import call_command
from django.dispatch import dispatcher
from django.test import signals
from django.template import Template
@@ -18,12 +18,12 @@ def instrumented_test_render(self, context):
"""
dispatcher.send(signal=signals.template_rendered, sender=self, template=self, context=context)
return self.nodelist.render(context)
-
+
class TestSMTPConnection(object):
"""A substitute SMTP connection for use during test sessions.
The test connection stores email messages in a dummy outbox,
rather than sending them out on the wire.
-
+
"""
def __init__(*args, **kwargs):
pass
@@ -36,37 +36,38 @@ class TestSMTPConnection(object):
def send_messages(self, messages):
"Redirect messages to the dummy outbox"
mail.outbox.extend(messages)
+ return len(messages)
def setup_test_environment():
"""Perform any global pre-test setup. This involves:
-
+
- Installing the instrumented test renderer
- Diverting the email sending functions to a test buffer
-
+
"""
Template.original_render = Template.render
Template.render = instrumented_test_render
-
+
mail.original_SMTPConnection = mail.SMTPConnection
mail.SMTPConnection = TestSMTPConnection
mail.outbox = []
-
+
def teardown_test_environment():
"""Perform any global post-test teardown. This involves:
- Restoring the original test renderer
- Restoring the email sending functions
-
+
"""
Template.render = Template.original_render
del Template.original_render
-
+
mail.SMTPConnection = mail.original_SMTPConnection
del mail.original_SMTPConnection
-
+
del mail.outbox
-
+
def _set_autocommit(connection):
"Make sure a connection is in autocommit mode."
if hasattr(connection.connection, "autocommit"):
@@ -89,12 +90,16 @@ def get_postgresql_create_suffix():
return ''
def create_test_db(verbosity=1, autoclobber=False):
+ """
+ Creates a test database, prompting the user for confirmation if the
+ database already exists. Returns the name of the test database created.
+ """
# If the database backend wants to create the test DB itself, let it
creation_module = get_creation_module()
if hasattr(creation_module, "create_test_db"):
creation_module.create_test_db(settings, connection, backend, verbosity, autoclobber)
return
-
+
if verbosity >= 1:
print "Creating test database..."
# If we're using SQLite, it's more convenient to test against an
@@ -112,22 +117,22 @@ def create_test_db(verbosity=1, autoclobber=False):
TEST_DATABASE_NAME = settings.TEST_DATABASE_NAME
else:
TEST_DATABASE_NAME = TEST_DATABASE_PREFIX + settings.DATABASE_NAME
-
+
# Create the test database and connect to it. We need to autocommit
- # if the database supports it because PostgreSQL doesn't allow
+ # if the database supports it because PostgreSQL doesn't allow
# CREATE/DROP DATABASE statements within transactions.
cursor = connection.cursor()
_set_autocommit(connection)
try:
cursor.execute("CREATE DATABASE %s %s" % (backend.quote_name(TEST_DATABASE_NAME), suffix))
- except Exception, e:
+ except Exception, e:
sys.stderr.write("Got an error creating the test database: %s\n" % e)
if not autoclobber:
confirm = raw_input("Type 'yes' if you would like to try deleting the test database '%s', or 'no' to cancel: " % TEST_DATABASE_NAME)
if autoclobber or confirm == 'yes':
try:
if verbosity >= 1:
- print "Destroying old test database..."
+ print "Destroying old test database..."
cursor.execute("DROP DATABASE %s" % backend.quote_name(TEST_DATABASE_NAME))
if verbosity >= 1:
print "Creating test database..."
@@ -138,27 +143,29 @@ def create_test_db(verbosity=1, autoclobber=False):
else:
print "Tests cancelled."
sys.exit(1)
-
+
connection.close()
settings.DATABASE_NAME = TEST_DATABASE_NAME
- management.syncdb(verbosity, interactive=False)
+ call_command('syncdb', verbosity=verbosity, interactive=False)
if settings.CACHE_BACKEND.startswith('db://'):
cache_name = settings.CACHE_BACKEND[len('db://'):]
- management.createcachetable(cache_name)
+ call_command('createcachetable', cache_name)
# Get a cursor (even though we don't need one yet). This has
# the side effect of initializing the test database.
cursor = connection.cursor()
+ return TEST_DATABASE_NAME
+
def destroy_test_db(old_database_name, verbosity=1):
# If the database wants to drop the test DB itself, let it
creation_module = get_creation_module()
if hasattr(creation_module, "destroy_test_db"):
creation_module.destroy_test_db(settings, connection, backend, old_database_name, verbosity)
return
-
+
# Unless we're using SQLite, remove the test database to clean up after
# ourselves. Connect to the previous database (not the test database)
# to do so, because it's not allowed to delete a database while being