Cleaned up some imports.

Fixed long lines.
Changed some docstrings to use "action words".


git-svn-id: http://code.djangoproject.com/svn/django/trunk@6044 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Gary Wilson Jr 2007-09-04 00:50:06 +00:00
parent 1da7b5cde7
commit 53372fcb07
2 changed files with 86 additions and 61 deletions

View File

@ -1,10 +1,11 @@
import re, unittest import re
import unittest
from urlparse import urlsplit from urlparse import urlsplit
from django.http import QueryDict from django.http import QueryDict
from django.db import transaction from django.db import transaction
from django.core import mail from django.core import mail
from django.core.management import call_command from django.core.management import call_command
from django.db.models import get_apps
from django.test import _doctest as doctest from django.test import _doctest as doctest
from django.test.client import Client from django.test.client import Client
@ -33,28 +34,27 @@ class OutputChecker(doctest.OutputChecker):
if not ok: if not ok:
return normalize_long_ints(want) == normalize_long_ints(got) return normalize_long_ints(want) == normalize_long_ints(got)
return ok return ok
class DocTestRunner(doctest.DocTestRunner): class DocTestRunner(doctest.DocTestRunner):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
doctest.DocTestRunner.__init__(self, *args, **kwargs) doctest.DocTestRunner.__init__(self, *args, **kwargs)
self.optionflags = doctest.ELLIPSIS self.optionflags = doctest.ELLIPSIS
def report_unexpected_exception(self, out, test, example, exc_info): def report_unexpected_exception(self, out, test, example, exc_info):
doctest.DocTestRunner.report_unexpected_exception(self,out,test,example,exc_info) doctest.DocTestRunner.report_unexpected_exception(self, out, test,
example, exc_info)
# Rollback, in case of database errors. Otherwise they'd have # Rollback, in case of database errors. Otherwise they'd have
# side effects on other tests. # side effects on other tests.
from django.db import transaction
transaction.rollback_unless_managed() transaction.rollback_unless_managed()
class TestCase(unittest.TestCase): class TestCase(unittest.TestCase):
def _pre_setup(self): def _pre_setup(self):
"""Perform any pre-test setup. This includes: """Performs any pre-test setup. This includes:
* If the Test Case class has a 'fixtures' member, clearing the * If the Test Case class has a 'fixtures' member, clearing the
database and installing the named fixtures at the start of each test. database and installing the named fixtures at the start of each
test.
* Clearing the mail test outbox. * Clearing the mail test outbox.
""" """
call_command('flush', verbosity=0, interactive=False) call_command('flush', verbosity=0, interactive=False)
if hasattr(self, 'fixtures'): if hasattr(self, 'fixtures'):
@ -73,96 +73,120 @@ class TestCase(unittest.TestCase):
self._pre_setup() self._pre_setup()
super(TestCase, self).__call__(result) super(TestCase, self).__call__(result)
def assertRedirects(self, response, expected_url, status_code=302, target_status_code=200): def assertRedirects(self, response, expected_url, status_code=302,
"""Assert that a response redirected to a specific URL, and that the target_status_code=200):
"""Asserts that a response redirected to a specific URL, and that the
redirect URL can be loaded. redirect URL can be loaded.
Note that assertRedirects won't work for external links since it uses Note that assertRedirects won't work for external links since it uses
TestClient to do a request. TestClient to do a request.
""" """
self.assertEqual(response.status_code, status_code, self.assertEqual(response.status_code, status_code,
"Response didn't redirect as expected: Response code was %d (expected %d)" % ("Response didn't redirect as expected: Response code was %d"
(response.status_code, status_code)) " (expected %d)" % (response.status_code, status_code)))
scheme, netloc, path, query, fragment = urlsplit(response['Location']) scheme, netloc, path, query, fragment = urlsplit(response['Location'])
url = path url = path
if query: if query:
url += '?' + query url += '?' + query
if fragment: if fragment:
url += '#' + fragment url += '#' + fragment
self.assertEqual(url, expected_url, self.assertEqual(url, expected_url,
"Response redirected to '%s', expected '%s'" % (url, expected_url)) "Response redirected to '%s', expected '%s'" % (url, expected_url))
# Get the redirection page, using the same client that was used # Get the redirection page, using the same client that was used
# to obtain the original response. # to obtain the original response.
redirect_response = response.client.get(path, QueryDict(query)) redirect_response = response.client.get(path, QueryDict(query))
self.assertEqual(redirect_response.status_code, target_status_code, self.assertEqual(redirect_response.status_code, target_status_code,
"Couldn't retrieve redirection page '%s': response code was %d (expected %d)" % ("Couldn't retrieve redirection page '%s': response code was %d"
(path, redirect_response.status_code, target_status_code)) " (expected %d)") %
(path, redirect_response.status_code, target_status_code))
def assertContains(self, response, text, count=None, status_code=200): def assertContains(self, response, text, count=None, status_code=200):
"""Assert that a response indicates that a page was retreived successfully, """
(i.e., the HTTP status code was as expected), and that ``text`` occurs ``count`` Asserts that a response indicates that a page was retreived
times in the content of the response. If ``count`` is None, the count doesn't successfully, (i.e., the HTTP status code was as expected), and that
matter - the assertion is true if the text occurs at least once in the response. ``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text occurs at least once in the response.
""" """
self.assertEqual(response.status_code, status_code, self.assertEqual(response.status_code, status_code,
"Couldn't retrieve page: Response code was %d (expected %d)'" % "Couldn't retrieve page: Response code was %d (expected %d)'" %
(response.status_code, status_code)) (response.status_code, status_code))
real_count = response.content.count(text) real_count = response.content.count(text)
if count is not None: if count is not None:
self.assertEqual(real_count, count, self.assertEqual(real_count, count,
"Found %d instances of '%s' in response (expected %d)" % (real_count, text, count)) "Found %d instances of '%s' in response (expected %d)" %
(real_count, text, count))
else: else:
self.failUnless(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): def assertFormError(self, response, form, field, errors):
"Assert that a form used to render the response has a specific field error" """
Asserts that a form used to render the response has a specific field
error.
"""
# Put context(s) into a list to simplify processing. # Put context(s) into a list to simplify processing.
contexts = to_list(response.context) contexts = to_list(response.context)
if not contexts: if not contexts:
self.fail('Response did not use any contexts to render the' self.fail('Response did not use any contexts to render the'
' response') ' response')
# Put error(s) into a list to simplify processing. # Put error(s) into a list to simplify processing.
errors = to_list(errors) errors = to_list(errors)
# Search all contexts for the error. # Search all contexts for the error.
found_form = False found_form = False
for i,context in enumerate(contexts): for i,context in enumerate(contexts):
if form in context: if form not in context:
found_form = True continue
for err in errors: found_form = True
if field: for err in errors:
if field in context[form].errors: if field:
self.failUnless(err in context[form].errors[field], if field in context[form].errors:
"The field '%s' on form '%s' in context %d does not contain the error '%s' (actual errors: %s)" % field_errors = context[form].errors[field]
(field, form, i, err, list(context[form].errors[field]))) self.failUnless(err in field_errors,
elif field in context[form].fields: "The field '%s' on form '%s' in"
self.fail("The field '%s' on form '%s' in context %d contains no errors" % " context %d does not contain the"
(field, form, i)) " error '%s' (actual errors: %s)" %
else: (field, form, i, err,
self.fail("The form '%s' in context %d does not contain the field '%s'" % (form, i, field)) list(field_errors)))
elif field in context[form].fields:
self.fail("The field '%s' on form '%s' in context %d"
" contains no errors" % (field, form, i))
else: else:
self.failUnless(err in context[form].non_field_errors(), self.fail("The form '%s' in context %d does not"
"The form '%s' in context %d does not contain the non-field error '%s' (actual errors: %s)" % " contain the field '%s'" %
(form, i, err, list(context[form].non_field_errors()))) (form, i, field))
else:
non_field_errors = context[form].non_field_errors()
self.failUnless(err in non_field_errors,
"The form '%s' in context %d does not contain the"
" non-field error '%s' (actual errors: %s)" %
(form, i, err, non_field_errors))
if not found_form: if not found_form:
self.fail("The form '%s' was not used to render the response" % form) self.fail("The form '%s' was not used to render the response" %
form)
def assertTemplateUsed(self, response, template_name): def assertTemplateUsed(self, response, template_name):
"Assert that the template with the provided name was used in rendering the response" """
Asserts that the template with the provided name was used in rendering
the response.
"""
template_names = [t.name for t in to_list(response.template)] template_names = [t.name for t in to_list(response.template)]
if not template_names: if not template_names:
self.fail('No templates used to render the response') self.fail('No templates used to render the response')
self.failUnless(template_name in template_names, self.failUnless(template_name in template_names,
(u"Template '%s' was not a template used to render the response." (u"Template '%s' was not a template used to render the response."
" Actual template(s) used: %s") % (template_name, u" Actual template(s) used: %s") % (template_name,
u', '.join(template_names))) u', '.join(template_names)))
def assertTemplateNotUsed(self, response, template_name): def assertTemplateNotUsed(self, response, template_name):
"Assert that the template with the provided name was NOT used in rendering the response" """
Asserts that the template with the provided name was NOT used in
rendering the response.
"""
template_names = [t.name for t in to_list(response.template)] template_names = [t.name for t in to_list(response.template)]
self.failIf(template_name in template_names, self.failIf(template_name in template_names,
(u"Template '%s' was used unexpectedly in rendering the" (u"Template '%s' was used unexpectedly in rendering the"
" response") % template_name) u" response") % template_name)

View File

@ -1,10 +1,11 @@
from xml.dom.minidom import parseString from xml.dom.minidom import parseString
from django.core.mail import EmailMessage, SMTPConnection from django.core.mail import EmailMessage, SMTPConnection
from django.template import Context, Template from django.template import Context, Template
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.newforms.forms import Form from django.newforms.forms import Form
from django.newforms import fields from django.newforms import fields, ValidationError
from django.shortcuts import render_to_response from django.shortcuts import render_to_response
def get_view(request): def get_view(request):