Removed all usages of deprecated TestCase methods (self.fail*). This removed most of the Warnings emitted (with -Wall) during the test suite.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@14803 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Alex Gaynor 2010-12-04 07:28:12 +00:00
parent 6770c36262
commit 5bc0ec4ec4
30 changed files with 386 additions and 379 deletions

View File

@ -1,14 +1,13 @@
import os import os
from django import forms from django import forms, http
from django import http
from django.conf import settings from django.conf import settings
from django.contrib.formtools import preview, wizard, utils from django.contrib.formtools import preview, wizard, utils
from django.test import TestCase from django.test import TestCase
from django.utils import unittest from django.utils import unittest
success_string = "Done was called!"
success_string = "Done was called!"
class TestFormPreview(preview.FormPreview): class TestFormPreview(preview.FormPreview):
def get_context(self, request, form): def get_context(self, request, form):
@ -100,7 +99,7 @@ class PreviewTests(TestCase):
# show we previously saw first stage of the form. # show we previously saw first stage of the form.
self.test_data.update({'stage':2}) self.test_data.update({'stage':2})
response = self.client.post('/test1/', self.test_data) response = self.client.post('/test1/', self.test_data)
self.failIfEqual(response.content, success_string) self.assertNotEqual(response.content, success_string)
hash = self.preview.security_hash(None, TestForm(self.test_data)) hash = self.preview.security_hash(None, TestForm(self.test_data))
self.test_data.update({'hash': hash}) self.test_data.update({'hash': hash})
response = self.client.post('/test1/', self.test_data) response = self.client.post('/test1/', self.test_data)
@ -134,7 +133,7 @@ class PreviewTests(TestCase):
# show we previously saw first stage of the form. # show we previously saw first stage of the form.
self.test_data.update({'stage':2}) self.test_data.update({'stage':2})
response = self.client.post('/test1/', self.test_data) response = self.client.post('/test1/', self.test_data)
self.failIfEqual(response.content, success_string) self.assertNotEqual(response.content, success_string)
hash = utils.security_hash(None, TestForm(self.test_data)) hash = utils.security_hash(None, TestForm(self.test_data))
self.test_data.update({'hash': hash}) self.test_data.update({'hash': hash})
response = self.client.post('/test1/', self.test_data) response = self.client.post('/test1/', self.test_data)
@ -151,11 +150,11 @@ class PreviewTests(TestCase):
self.test_data.update({'stage':2}) self.test_data.update({'stage':2})
response = self.client.post('/test2/', self.test_data) response = self.client.post('/test2/', self.test_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.failIfEqual(response.content, success_string) self.assertNotEqual(response.content, success_string)
hash = utils.security_hash(None, TestForm(self.test_data)) hash = utils.security_hash(None, TestForm(self.test_data))
self.test_data.update({'hash': hash}) self.test_data.update({'hash': hash})
response = self.client.post('/test2/', self.test_data) response = self.client.post('/test2/', self.test_data)
self.failIfEqual(response.content, success_string) self.assertNotEqual(response.content, success_string)
class SecurityHashTests(unittest.TestCase): class SecurityHashTests(unittest.TestCase):
@ -392,4 +391,3 @@ class WizardTests(TestCase):
"wizard_step": "1"} "wizard_step": "1"}
wizard(DummyRequest(POST=data)) wizard(DummyRequest(POST=data))
self.assertTrue(reached[0]) self.assertTrue(reached[0])

View File

@ -355,7 +355,7 @@ class TransactionTestCase(ut2.TestCase):
if hasattr(response, 'redirect_chain'): if hasattr(response, 'redirect_chain'):
# The request was a followed redirect # The request was a followed redirect
self.failUnless(len(response.redirect_chain) > 0, self.assertTrue(len(response.redirect_chain) > 0,
msg_prefix + "Response didn't redirect as expected: Response" msg_prefix + "Response didn't redirect as expected: Response"
" code was %d (expected %d)" % " code was %d (expected %d)" %
(response.status_code, status_code)) (response.status_code, status_code))
@ -469,7 +469,7 @@ class TransactionTestCase(ut2.TestCase):
if field: if field:
if field in context[form].errors: if field in context[form].errors:
field_errors = context[form].errors[field] field_errors = context[form].errors[field]
self.failUnless(err in field_errors, self.assertTrue(err in field_errors,
msg_prefix + "The field '%s' on form '%s' in" msg_prefix + "The field '%s' on form '%s' in"
" context %d does not contain the error '%s'" " context %d does not contain the error '%s'"
" (actual errors: %s)" % " (actual errors: %s)" %
@ -484,7 +484,7 @@ class TransactionTestCase(ut2.TestCase):
(form, i, field)) (form, i, field))
else: else:
non_field_errors = context[form].non_field_errors() non_field_errors = context[form].non_field_errors()
self.failUnless(err in non_field_errors, self.assertTrue(err in non_field_errors,
msg_prefix + "The form '%s' in context %d does not" msg_prefix + "The form '%s' in context %d does not"
" contain the non-field error '%s'" " contain the non-field error '%s'"
" (actual errors: %s)" % " (actual errors: %s)" %
@ -504,7 +504,7 @@ class TransactionTestCase(ut2.TestCase):
template_names = [t.name for t in response.templates] template_names = [t.name for t in response.templates]
if not template_names: if not template_names:
self.fail(msg_prefix + "No templates used to render the response") self.fail(msg_prefix + "No templates used to render the response")
self.failUnless(template_name in template_names, self.assertTrue(template_name in template_names,
msg_prefix + "Template '%s' was not a template used to render" msg_prefix + "Template '%s' was not a template used to render"
" the response. Actual template(s) used: %s" % " the response. Actual template(s) used: %s" %
(template_name, u', '.join(template_names))) (template_name, u', '.join(template_names)))
@ -518,7 +518,7 @@ class TransactionTestCase(ut2.TestCase):
msg_prefix += ": " msg_prefix += ": "
template_names = [t.name for t in response.templates] template_names = [t.name for t in response.templates]
self.failIf(template_name in template_names, self.assertFalse(template_name in template_names,
msg_prefix + "Template '%s' was used unexpectedly in rendering" msg_prefix + "Template '%s' was used unexpectedly in rendering"
" the response" % template_name) " the response" % template_name)

View File

@ -2,13 +2,13 @@ import datetime
import re import re
from datetime import date from datetime import date
from decimal import Decimal from decimal import Decimal
from django import forms from django import forms
from django.db import models from django.db import models
from django.forms.models import _get_foreign_key from django.forms.models import (_get_foreign_key, inlineformset_factory,
from django.forms.models import inlineformset_factory modelformset_factory, modelformset_factory)
from django.forms.models import modelformset_factory
from django.forms.models import modelformset_factory
from django.test import TestCase from django.test import TestCase
from modeltests.model_formsets.models import ( from modeltests.model_formsets.models import (
Author, BetterAuthor, Book, BookWithCustomPK, Editor, Author, BetterAuthor, Book, BookWithCustomPK, Editor,
BookWithOptionalAltEditor, AlternateBook, AuthorMeeting, CustomPrimaryKey, BookWithOptionalAltEditor, AlternateBook, AuthorMeeting, CustomPrimaryKey,
@ -30,7 +30,7 @@ class DeletionTests(TestCase):
} }
formset = PoetFormSet(data, queryset=Poet.objects.all()) formset = PoetFormSet(data, queryset=Poet.objects.all())
formset.save() formset.save()
self.failUnless(formset.is_valid()) self.assertTrue(formset.is_valid())
self.assertEqual(Poet.objects.count(), 0) self.assertEqual(Poet.objects.count(), 0)
def test_add_form_deletion_when_invalid(self): def test_add_form_deletion_when_invalid(self):

View File

@ -171,6 +171,6 @@ class SignalTests(TestCase):
signals.post_save.connect(sender=Person, receiver=b) signals.post_save.connect(sender=Person, receiver=b)
p = Person.objects.create(first_name='John', last_name='Smith') p = Person.objects.create(first_name='John', last_name='Smith')
self.failUnless(a._run) self.assertTrue(a._run)
self.failUnless(b._run) self.assertTrue(b._run)
self.assertEqual(signals.post_save.receivers, []) self.assertEqual(signals.post_save.receivers, [])

View File

@ -73,7 +73,7 @@ class ClientTest(TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['data'], '37') self.assertEqual(response.context['data'], '37')
self.assertEqual(response.templates[0].name, 'POST Template') self.assertEqual(response.templates[0].name, 'POST Template')
self.failUnless('Data received' in response.content) self.assertTrue('Data received' in response.content)
def test_response_headers(self): def test_response_headers(self):
"Check the value of HTTP headers returned in a response" "Check the value of HTTP headers returned in a response"
@ -278,7 +278,7 @@ class ClientTest(TestCase):
# Log in # Log in
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.failUnless(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Request a page that requires a login # Request a page that requires a login
response = self.client.get('/test_client/login_protected_view/') response = self.client.get('/test_client/login_protected_view/')
@ -294,7 +294,7 @@ class ClientTest(TestCase):
# Log in # Log in
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.failUnless(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Request a page that requires a login # Request a page that requires a login
response = self.client.get('/test_client/login_protected_method_view/') response = self.client.get('/test_client/login_protected_method_view/')
@ -310,7 +310,7 @@ class ClientTest(TestCase):
# Log in # Log in
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.failUnless(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Request a page that requires a login # Request a page that requires a login
response = self.client.get('/test_client/login_protected_view_custom_redirect/') response = self.client.get('/test_client/login_protected_view_custom_redirect/')
@ -321,13 +321,13 @@ class ClientTest(TestCase):
"Request a page that is protected with @login, but use bad credentials" "Request a page that is protected with @login, but use bad credentials"
login = self.client.login(username='otheruser', password='nopassword') login = self.client.login(username='otheruser', password='nopassword')
self.failIf(login) self.assertFalse(login)
def test_view_with_inactive_login(self): def test_view_with_inactive_login(self):
"Request a page that is protected with @login, but use an inactive login" "Request a page that is protected with @login, but use an inactive login"
login = self.client.login(username='inactive', password='password') login = self.client.login(username='inactive', password='password')
self.failIf(login) self.assertFalse(login)
def test_logout(self): def test_logout(self):
"Request a logout after logging in" "Request a logout after logging in"
@ -355,7 +355,7 @@ class ClientTest(TestCase):
# Log in # Log in
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.failUnless(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Log in with wrong permissions. Should result in 302. # Log in with wrong permissions. Should result in 302.
response = self.client.get('/test_client/permission_protected_view/') response = self.client.get('/test_client/permission_protected_view/')
@ -372,7 +372,7 @@ class ClientTest(TestCase):
# Log in # Log in
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.failUnless(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Log in with wrong permissions. Should result in 302. # Log in with wrong permissions. Should result in 302.
response = self.client.get('/test_client/permission_protected_method_view/') response = self.client.get('/test_client/permission_protected_method_view/')

View File

@ -2,6 +2,7 @@ from django.test import TestCase
from models import A, B, C, D, DataPoint, RelatedPoint from models import A, B, C, D, DataPoint, RelatedPoint
class SimpleTest(TestCase): class SimpleTest(TestCase):
def setUp(self): def setUp(self):
self.a1 = A.objects.create() self.a1 = A.objects.create()
@ -15,18 +16,18 @@ class SimpleTest(TestCase):
Test that update changes the right number of rows for a nonempty queryset Test that update changes the right number of rows for a nonempty queryset
""" """
num_updated = self.a1.b_set.update(y=100) num_updated = self.a1.b_set.update(y=100)
self.failUnlessEqual(num_updated, 20) self.assertEqual(num_updated, 20)
cnt = B.objects.filter(y=100).count() cnt = B.objects.filter(y=100).count()
self.failUnlessEqual(cnt, 20) self.assertEqual(cnt, 20)
def test_empty_update(self): def test_empty_update(self):
""" """
Test that update changes the right number of rows for an empty queryset Test that update changes the right number of rows for an empty queryset
""" """
num_updated = self.a2.b_set.update(y=100) num_updated = self.a2.b_set.update(y=100)
self.failUnlessEqual(num_updated, 0) self.assertEqual(num_updated, 0)
cnt = B.objects.filter(y=100).count() cnt = B.objects.filter(y=100).count()
self.failUnlessEqual(cnt, 0) self.assertEqual(cnt, 0)
def test_nonempty_update_with_inheritance(self): def test_nonempty_update_with_inheritance(self):
""" """
@ -34,9 +35,9 @@ class SimpleTest(TestCase):
when the update affects only a base table when the update affects only a base table
""" """
num_updated = self.a1.d_set.update(y=100) num_updated = self.a1.d_set.update(y=100)
self.failUnlessEqual(num_updated, 20) self.assertEqual(num_updated, 20)
cnt = D.objects.filter(y=100).count() cnt = D.objects.filter(y=100).count()
self.failUnlessEqual(cnt, 20) self.assertEqual(cnt, 20)
def test_empty_update_with_inheritance(self): def test_empty_update_with_inheritance(self):
""" """
@ -44,9 +45,9 @@ class SimpleTest(TestCase):
when the update affects only a base table when the update affects only a base table
""" """
num_updated = self.a2.d_set.update(y=100) num_updated = self.a2.d_set.update(y=100)
self.failUnlessEqual(num_updated, 0) self.assertEqual(num_updated, 0)
cnt = D.objects.filter(y=100).count() cnt = D.objects.filter(y=100).count()
self.failUnlessEqual(cnt, 0) self.assertEqual(cnt, 0)
class AdvancedTests(TestCase): class AdvancedTests(TestCase):

View File

@ -33,7 +33,7 @@ class ChangeListTests(TransactionTestCase):
context = Context({'cl': cl}) context = Context({'cl': cl})
table_output = template.render(context) table_output = template.render(context)
row_html = '<tbody><tr class="row1"><td><input type="checkbox" class="action-select" value="1" name="_selected_action" /></td><th><a href="1/">name</a></th><td>Parent object</td></tr></tbody>' row_html = '<tbody><tr class="row1"><td><input type="checkbox" class="action-select" value="1" name="_selected_action" /></td><th><a href="1/">name</a></th><td>Parent object</td></tr></tbody>'
self.failIf(table_output.find(row_html) == -1, self.assertFalse(table_output.find(row_html) == -1,
'Failed to find expected row element: %s' % table_output) 'Failed to find expected row element: %s' % table_output)
def test_result_list_editable_html(self): def test_result_list_editable_html(self):
@ -64,11 +64,11 @@ class ChangeListTests(TransactionTestCase):
table_output = template.render(context) table_output = template.render(context)
# make sure that hidden fields are in the correct place # make sure that hidden fields are in the correct place
hiddenfields_div = '<div class="hiddenfields"><input type="hidden" name="form-0-id" value="1" id="id_form-0-id" /></div>' hiddenfields_div = '<div class="hiddenfields"><input type="hidden" name="form-0-id" value="1" id="id_form-0-id" /></div>'
self.failIf(table_output.find(hiddenfields_div) == -1, self.assertFalse(table_output.find(hiddenfields_div) == -1,
'Failed to find hidden fields in: %s' % table_output) 'Failed to find hidden fields in: %s' % table_output)
# make sure that list editable fields are rendered in divs correctly # make sure that list editable fields are rendered in divs correctly
editable_name_field = '<input name="form-0-name" value="name" class="vTextField" maxlength="30" type="text" id="id_form-0-name" />' editable_name_field = '<input name="form-0-name" value="name" class="vTextField" maxlength="30" type="text" id="id_form-0-name" />'
self.failIf('<td>%s</td>' % editable_name_field == -1, self.assertFalse('<td>%s</td>' % editable_name_field == -1,
'Failed to find "name" list_editable field in: %s' % table_output) 'Failed to find "name" list_editable field in: %s' % table_output)
class ChildAdmin(admin.ModelAdmin): class ChildAdmin(admin.ModelAdmin):

View File

@ -1,12 +1,10 @@
from django.test import TestCase
from django.contrib.admin.helpers import InlineAdminForm from django.contrib.admin.helpers import InlineAdminForm
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
# local test models # local test models
from models import Holder, Inner, InnerInline from models import (Holder, Inner, InnerInline, Holder2, Inner2, Holder3,
from models import Holder2, Inner2, Holder3, Inner3 Inner3, Person, OutfitItem, Fashionista, Teacher, Parent, Child)
from models import Person, OutfitItem, Fashionista
from models import Teacher, Parent, Child
class TestInline(TestCase): class TestInline(TestCase):
@ -19,7 +17,7 @@ class TestInline(TestCase):
self.change_url = '/test_admin/admin/admin_inlines/holder/%i/' % holder.id self.change_url = '/test_admin/admin/admin_inlines/holder/%i/' % holder.id
result = self.client.login(username='super', password='secret') result = self.client.login(username='super', password='secret')
self.failUnlessEqual(result, True) self.assertEqual(result, True)
def tearDown(self): def tearDown(self):
self.client.logout() self.client.logout()
@ -75,7 +73,7 @@ class TestInlineMedia(TestCase):
def setUp(self): def setUp(self):
result = self.client.login(username='super', password='secret') result = self.client.login(username='super', password='secret')
self.failUnlessEqual(result, True) self.assertEqual(result, True)
def tearDown(self): def tearDown(self):
self.client.logout() self.client.logout()

View File

@ -12,6 +12,7 @@ from django import conf, bin, get_version
from django.conf import settings from django.conf import settings
from django.utils import unittest from django.utils import unittest
class AdminScriptTestCase(unittest.TestCase): class AdminScriptTestCase(unittest.TestCase):
def write_settings(self, filename, apps=None, is_dir=False, sdict=None): def write_settings(self, filename, apps=None, is_dir=False, sdict=None):
test_dir = os.path.dirname(os.path.dirname(__file__)) test_dir = os.path.dirname(os.path.dirname(__file__))
@ -156,7 +157,7 @@ class AdminScriptTestCase(unittest.TestCase):
self.assertEquals(len(stream), 0, "Stream should be empty: actually contains '%s'" % stream) self.assertEquals(len(stream), 0, "Stream should be empty: actually contains '%s'" % stream)
def assertOutput(self, stream, msg): def assertOutput(self, stream, msg):
"Utility assertion: assert that the given message exists in the output" "Utility assertion: assert that the given message exists in the output"
self.failUnless(msg in stream, "'%s' does not match actual output text '%s'" % (msg, stream)) self.assertTrue(msg in stream, "'%s' does not match actual output text '%s'" % (msg, stream))
########################################################################## ##########################################################################
# DJANGO ADMIN TESTS # DJANGO ADMIN TESTS

File diff suppressed because it is too large Load Diff

View File

@ -143,7 +143,7 @@ class AdminForeignKeyWidgetChangeList(DjangoTestCase):
def test_changelist_foreignkey(self): def test_changelist_foreignkey(self):
response = self.client.get('%s/admin_widgets/car/' % self.admin_root) response = self.client.get('%s/admin_widgets/car/' % self.admin_root)
self.failUnless('%s/auth/user/add/' % self.admin_root in response.content) self.assertTrue('%s/auth/user/add/' % self.admin_root in response.content)
class AdminForeignKeyRawIdWidget(DjangoTestCase): class AdminForeignKeyRawIdWidget(DjangoTestCase):

View File

@ -47,28 +47,28 @@ class EggLoadingTest(TestCase):
egg_name = '%s/modelapp.egg' % self.egg_dir egg_name = '%s/modelapp.egg' % self.egg_dir
sys.path.append(egg_name) sys.path.append(egg_name)
models = load_app('app_with_models') models = load_app('app_with_models')
self.failIf(models is None) self.assertFalse(models is None)
def test_egg2(self): def test_egg2(self):
"""Loading an app from an egg that has no models returns no models (and no error)""" """Loading an app from an egg that has no models returns no models (and no error)"""
egg_name = '%s/nomodelapp.egg' % self.egg_dir egg_name = '%s/nomodelapp.egg' % self.egg_dir
sys.path.append(egg_name) sys.path.append(egg_name)
models = load_app('app_no_models') models = load_app('app_no_models')
self.failUnless(models is None) self.assertTrue(models is None)
def test_egg3(self): def test_egg3(self):
"""Models module can be loaded from an app located under an egg's top-level package""" """Models module can be loaded from an app located under an egg's top-level package"""
egg_name = '%s/omelet.egg' % self.egg_dir egg_name = '%s/omelet.egg' % self.egg_dir
sys.path.append(egg_name) sys.path.append(egg_name)
models = load_app('omelet.app_with_models') models = load_app('omelet.app_with_models')
self.failIf(models is None) self.assertFalse(models is None)
def test_egg4(self): def test_egg4(self):
"""Loading an app with no models from under the top-level egg package generates no error""" """Loading an app with no models from under the top-level egg package generates no error"""
egg_name = '%s/omelet.egg' % self.egg_dir egg_name = '%s/omelet.egg' % self.egg_dir
sys.path.append(egg_name) sys.path.append(egg_name)
models = load_app('omelet.app_no_models') models = load_app('omelet.app_no_models')
self.failUnless(models is None) self.assertTrue(models is None)
def test_egg5(self): def test_egg5(self):
"""Loading an app from an egg that has an import error in its models module raises that error""" """Loading an app from an egg that has an import error in its models module raises that error"""
@ -80,4 +80,4 @@ class EggLoadingTest(TestCase):
except ImportError, e: except ImportError, e:
# Make sure the message is indicating the actual # Make sure the message is indicating the actual
# problem in the broken app. # problem in the broken app.
self.failUnless("modelz" in e.args[0]) self.assertTrue("modelz" in e.args[0])

View File

@ -12,7 +12,7 @@ class Bug8245Test(TestCase):
try: try:
admin.autodiscover() admin.autodiscover()
except Exception, e: except Exception, e:
self.failUnlessEqual(str(e), "Bad admin module") self.assertEqual(str(e), "Bad admin module")
else: else:
self.fail( self.fail(
'autodiscover should have raised a "Bad admin module" error.') 'autodiscover should have raised a "Bad admin module" error.')
@ -22,7 +22,7 @@ class Bug8245Test(TestCase):
try: try:
admin.autodiscover() admin.autodiscover()
except Exception, e: except Exception, e:
self.failUnlessEqual(str(e), "Bad admin module") self.assertEqual(str(e), "Bad admin module")
else: else:
self.fail( self.fail(
'autodiscover should have raised a "Bad admin module" error.') 'autodiscover should have raised a "Bad admin module" error.')

View File

@ -48,5 +48,5 @@ class WSGIFileWrapperTests(TestCase):
err = StringIO() err = StringIO()
handler = FileWrapperHandler(None, StringIO(), err, env) handler = FileWrapperHandler(None, StringIO(), err, env)
handler.run(wsgi_app) handler.run(wsgi_app)
self.failIf(handler._used_sendfile) self.assertFalse(handler._used_sendfile)
self.assertEqual(handler.stdout.getvalue().splitlines()[-1],'Hello World!') self.assertEqual(handler.stdout.getvalue().splitlines()[-1],'Hello World!')

View File

@ -1,19 +1,21 @@
import time import time
from django.conf import settings from django.conf import settings
from django.contrib.comments.models import Comment
from django.contrib.comments.forms import CommentForm from django.contrib.comments.forms import CommentForm
from django.contrib.comments.models import Comment
from django.utils.hashcompat import sha_constructor from django.utils.hashcompat import sha_constructor
from regressiontests.comment_tests.models import Article from regressiontests.comment_tests.models import Article
from regressiontests.comment_tests.tests import CommentTestCase from regressiontests.comment_tests.tests import CommentTestCase
class CommentFormTests(CommentTestCase):
class CommentFormTests(CommentTestCase):
def testInit(self): def testInit(self):
f = CommentForm(Article.objects.get(pk=1)) f = CommentForm(Article.objects.get(pk=1))
self.assertEqual(f.initial['content_type'], str(Article._meta)) self.assertEqual(f.initial['content_type'], str(Article._meta))
self.assertEqual(f.initial['object_pk'], "1") self.assertEqual(f.initial['object_pk'], "1")
self.failIfEqual(f.initial['security_hash'], None) self.assertNotEqual(f.initial['security_hash'], None)
self.failIfEqual(f.initial['timestamp'], None) self.assertNotEqual(f.initial['timestamp'], None)
def testValidPost(self): def testValidPost(self):
a = Article.objects.get(pk=1) a = Article.objects.get(pk=1)
@ -26,7 +28,7 @@ class CommentFormTests(CommentTestCase):
d = self.getValidData(a) d = self.getValidData(a)
d.update(kwargs) d.update(kwargs)
f = CommentForm(Article.objects.get(pk=1), data=d) f = CommentForm(Article.objects.get(pk=1), data=d)
self.failIf(f.is_valid()) self.assertFalse(f.is_valid())
return f return f
def testHoneypotTampering(self): def testHoneypotTampering(self):
@ -88,12 +90,12 @@ class CommentFormTests(CommentTestCase):
# Try with COMMENTS_ALLOW_PROFANITIES off # Try with COMMENTS_ALLOW_PROFANITIES off
settings.COMMENTS_ALLOW_PROFANITIES = False settings.COMMENTS_ALLOW_PROFANITIES = False
f = CommentForm(a, data=dict(d, comment="What a rooster!")) f = CommentForm(a, data=dict(d, comment="What a rooster!"))
self.failIf(f.is_valid()) self.assertFalse(f.is_valid())
# Now with COMMENTS_ALLOW_PROFANITIES on # Now with COMMENTS_ALLOW_PROFANITIES on
settings.COMMENTS_ALLOW_PROFANITIES = True settings.COMMENTS_ALLOW_PROFANITIES = True
f = CommentForm(a, data=dict(d, comment="What a rooster!")) f = CommentForm(a, data=dict(d, comment="What a rooster!"))
self.failUnless(f.is_valid()) self.assertTrue(f.is_valid())
# Restore settings # Restore settings
settings.PROFANITIES_LIST, settings.COMMENTS_ALLOW_PROFANITIES = saved settings.PROFANITIES_LIST, settings.COMMENTS_ALLOW_PROFANITIES = saved

View File

@ -199,7 +199,7 @@ class CommentViewTests(CommentTestCase):
signals.comment_will_be_posted.connect(receive) signals.comment_will_be_posted.connect(receive)
self.testCreateValidComment() self.testCreateValidComment()
c = Comment.objects.all()[0] c = Comment.objects.all()[0]
self.failIf(c.is_public) self.assertFalse(c.is_public)
def testCommentNext(self): def testCommentNext(self):
"""Test the different "next" actions the comment view can take""" """Test the different "next" actions the comment view can take"""
@ -208,14 +208,14 @@ class CommentViewTests(CommentTestCase):
response = self.client.post("/post/", data) response = self.client.post("/post/", data)
location = response["Location"] location = response["Location"]
match = post_redirect_re.match(location) match = post_redirect_re.match(location)
self.failUnless(match != None, "Unexpected redirect location: %s" % location) self.assertTrue(match != None, "Unexpected redirect location: %s" % location)
data["next"] = "/somewhere/else/" data["next"] = "/somewhere/else/"
data["comment"] = "This is another comment" data["comment"] = "This is another comment"
response = self.client.post("/post/", data) response = self.client.post("/post/", data)
location = response["Location"] location = response["Location"]
match = re.search(r"^http://testserver/somewhere/else/\?c=\d+$", location) match = re.search(r"^http://testserver/somewhere/else/\?c=\d+$", location)
self.failUnless(match != None, "Unexpected redirect location: %s" % location) self.assertTrue(match != None, "Unexpected redirect location: %s" % location)
def testCommentDoneView(self): def testCommentDoneView(self):
a = Article.objects.get(pk=1) a = Article.objects.get(pk=1)
@ -223,7 +223,7 @@ class CommentViewTests(CommentTestCase):
response = self.client.post("/post/", data) response = self.client.post("/post/", data)
location = response["Location"] location = response["Location"]
match = post_redirect_re.match(location) match = post_redirect_re.match(location)
self.failUnless(match != None, "Unexpected redirect location: %s" % location) self.assertTrue(match != None, "Unexpected redirect location: %s" % location)
pk = int(match.group('pk')) pk = int(match.group('pk'))
response = self.client.get(location) response = self.client.get(location)
self.assertTemplateUsed(response, "comments/posted.html") self.assertTemplateUsed(response, "comments/posted.html")
@ -240,7 +240,7 @@ class CommentViewTests(CommentTestCase):
response = self.client.post("/post/", data) response = self.client.post("/post/", data)
location = response["Location"] location = response["Location"]
match = re.search(r"^http://testserver/somewhere/else/\?foo=bar&c=\d+$", location) match = re.search(r"^http://testserver/somewhere/else/\?foo=bar&c=\d+$", location)
self.failUnless(match != None, "Unexpected redirect location: %s" % location) self.assertTrue(match != None, "Unexpected redirect location: %s" % location)
def testCommentPostRedirectWithInvalidIntegerPK(self): def testCommentPostRedirectWithInvalidIntegerPK(self):
""" """

View File

@ -1,12 +1,13 @@
from django.contrib.comments.models import Comment from django.contrib.comments.models import Comment
from regressiontests.comment_tests.models import Author, Article from regressiontests.comment_tests.models import Author, Article
from regressiontests.comment_tests.tests import CommentTestCase from regressiontests.comment_tests.tests import CommentTestCase
class CommentModelTests(CommentTestCase):
class CommentModelTests(CommentTestCase):
def testSave(self): def testSave(self):
for c in self.createSomeComments(): for c in self.createSomeComments():
self.failIfEqual(c.submit_date, None) self.assertNotEqual(c.submit_date, None)
def testUserProperties(self): def testUserProperties(self):
c1, c2, c3, c4 = self.createSomeComments() c1, c2, c3, c4 = self.createSomeComments()

View File

@ -1,8 +1,10 @@
from django.contrib.comments.models import Comment, CommentFlag
from django.contrib.auth.models import User, Permission from django.contrib.auth.models import User, Permission
from django.contrib.contenttypes.models import ContentType
from regressiontests.comment_tests.tests import CommentTestCase
from django.contrib.comments import signals from django.contrib.comments import signals
from django.contrib.comments.models import Comment, CommentFlag
from django.contrib.contenttypes.models import ContentType
from regressiontests.comment_tests.tests import CommentTestCase
class FlagViewTests(CommentTestCase): class FlagViewTests(CommentTestCase):
@ -93,7 +95,7 @@ class DeleteViewTests(CommentTestCase):
response = self.client.post("/delete/%d/" % pk) response = self.client.post("/delete/%d/" % pk)
self.assertEqual(response["Location"], "http://testserver/deleted/?c=%d" % pk) self.assertEqual(response["Location"], "http://testserver/deleted/?c=%d" % pk)
c = Comment.objects.get(pk=pk) c = Comment.objects.get(pk=pk)
self.failUnless(c.is_removed) self.assertTrue(c.is_removed)
self.assertEqual(c.flags.filter(flag=CommentFlag.MODERATOR_DELETION, user__username="normaluser").count(), 1) self.assertEqual(c.flags.filter(flag=CommentFlag.MODERATOR_DELETION, user__username="normaluser").count(), 1)
def testDeleteSignals(self): def testDeleteSignals(self):
@ -138,7 +140,7 @@ class ApproveViewTests(CommentTestCase):
response = self.client.post("/approve/%d/" % c1.pk) response = self.client.post("/approve/%d/" % c1.pk)
self.assertEqual(response["Location"], "http://testserver/approved/?c=%d" % c1.pk) self.assertEqual(response["Location"], "http://testserver/approved/?c=%d" % c1.pk)
c = Comment.objects.get(pk=c1.pk) c = Comment.objects.get(pk=c1.pk)
self.failUnless(c.is_public) self.assertTrue(c.is_public)
self.assertEqual(c.flags.filter(flag=CommentFlag.MODERATOR_APPROVAL, user__username="normaluser").count(), 1) self.assertEqual(c.flags.filter(flag=CommentFlag.MODERATOR_APPROVAL, user__username="normaluser").count(), 1)
def testApproveSignals(self): def testApproveSignals(self):

View File

@ -16,12 +16,11 @@ except ImportError:
import dummy_threading as threading import dummy_threading as threading
from django.conf import settings from django.conf import settings
from django.core.exceptions import SuspiciousOperation from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
from django.core.files.base import ContentFile, File from django.core.files.base import ContentFile, File
from django.core.files.images import get_image_dimensions from django.core.files.images import get_image_dimensions
from django.core.files.storage import FileSystemStorage, get_storage_class from django.core.files.storage import FileSystemStorage, get_storage_class
from django.core.files.uploadedfile import UploadedFile from django.core.files.uploadedfile import UploadedFile
from django.core.exceptions import ImproperlyConfigured
from django.utils import unittest from django.utils import unittest
# Try to import PIL in either of the two ways it can end up installed. # Try to import PIL in either of the two ways it can end up installed.
@ -103,7 +102,7 @@ class FileStorageTests(unittest.TestCase):
""" """
Standard file access options are available, and work as expected. Standard file access options are available, and work as expected.
""" """
self.failIf(self.storage.exists('storage_test')) self.assertFalse(self.storage.exists('storage_test'))
f = self.storage.open('storage_test', 'w') f = self.storage.open('storage_test', 'w')
f.write('storage contents') f.write('storage contents')
f.close() f.close()
@ -114,14 +113,14 @@ class FileStorageTests(unittest.TestCase):
f.close() f.close()
self.storage.delete('storage_test') self.storage.delete('storage_test')
self.failIf(self.storage.exists('storage_test')) self.assertFalse(self.storage.exists('storage_test'))
def test_file_accessed_time(self): def test_file_accessed_time(self):
""" """
File storage returns a Datetime object for the last accessed time of File storage returns a Datetime object for the last accessed time of
a file. a file.
""" """
self.failIf(self.storage.exists('test.file')) self.assertFalse(self.storage.exists('test.file'))
f = ContentFile('custom contents') f = ContentFile('custom contents')
f_name = self.storage.save('test.file', f) f_name = self.storage.save('test.file', f)
@ -137,7 +136,7 @@ class FileStorageTests(unittest.TestCase):
File storage returns a Datetime object for the creation time of File storage returns a Datetime object for the creation time of
a file. a file.
""" """
self.failIf(self.storage.exists('test.file')) self.assertFalse(self.storage.exists('test.file'))
f = ContentFile('custom contents') f = ContentFile('custom contents')
f_name = self.storage.save('test.file', f) f_name = self.storage.save('test.file', f)
@ -154,7 +153,7 @@ class FileStorageTests(unittest.TestCase):
File storage returns a Datetime object for the last modified time of File storage returns a Datetime object for the last modified time of
a file. a file.
""" """
self.failIf(self.storage.exists('test.file')) self.assertFalse(self.storage.exists('test.file'))
f = ContentFile('custom contents') f = ContentFile('custom contents')
f_name = self.storage.save('test.file', f) f_name = self.storage.save('test.file', f)
@ -171,7 +170,7 @@ class FileStorageTests(unittest.TestCase):
File storage extracts the filename from the content object if no File storage extracts the filename from the content object if no
name is given explicitly. name is given explicitly.
""" """
self.failIf(self.storage.exists('test.file')) self.assertFalse(self.storage.exists('test.file'))
f = ContentFile('custom contents') f = ContentFile('custom contents')
f.name = 'test.file' f.name = 'test.file'
@ -188,7 +187,7 @@ class FileStorageTests(unittest.TestCase):
""" """
File storage returns the full path of a file File storage returns the full path of a file
""" """
self.failIf(self.storage.exists('test.file')) self.assertFalse(self.storage.exists('test.file'))
f = ContentFile('custom contents') f = ContentFile('custom contents')
f_name = self.storage.save('test.file', f) f_name = self.storage.save('test.file', f)
@ -213,7 +212,7 @@ class FileStorageTests(unittest.TestCase):
File storage can get a mixin to extend the functionality of the File storage can get a mixin to extend the functionality of the
returned file. returned file.
""" """
self.failIf(self.storage.exists('test.file')) self.assertFalse(self.storage.exists('test.file'))
class TestFileMixin(object): class TestFileMixin(object):
mixed_in = True mixed_in = True
@ -232,9 +231,9 @@ class FileStorageTests(unittest.TestCase):
""" """
File storage returns a tuple containing directories and files. File storage returns a tuple containing directories and files.
""" """
self.failIf(self.storage.exists('storage_test_1')) self.assertFalse(self.storage.exists('storage_test_1'))
self.failIf(self.storage.exists('storage_test_2')) self.assertFalse(self.storage.exists('storage_test_2'))
self.failIf(self.storage.exists('storage_dir_1')) self.assertFalse(self.storage.exists('storage_dir_1'))
f = self.storage.save('storage_test_1', ContentFile('custom content')) f = self.storage.save('storage_test_1', ContentFile('custom content'))
f = self.storage.save('storage_test_2', ContentFile('custom content')) f = self.storage.save('storage_test_2', ContentFile('custom content'))
@ -357,7 +356,7 @@ class FileStoragePathParsing(unittest.TestCase):
self.storage.save('dotted.path/test', ContentFile("1")) self.storage.save('dotted.path/test', ContentFile("1"))
self.storage.save('dotted.path/test', ContentFile("2")) self.storage.save('dotted.path/test', ContentFile("2"))
self.failIf(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path'))) self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test'))) self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test')))
self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_1'))) self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_1')))

View File

@ -1,6 +1,6 @@
#! -*- coding: utf-8 -*- #! -*- coding: utf-8 -*-
import os
import errno import errno
import os
import shutil import shutil
from StringIO import StringIO from StringIO import StringIO
@ -15,6 +15,7 @@ from django.utils.hashcompat import sha_constructor
from models import FileModel, temp_storage, UPLOAD_TO from models import FileModel, temp_storage, UPLOAD_TO
import uploadhandler import uploadhandler
UNICODE_FILENAME = u'test-0123456789_中文_Orléans.jpg' UNICODE_FILENAME = u'test-0123456789_中文_Orléans.jpg'
class FileUploadTests(TestCase): class FileUploadTests(TestCase):

View File

@ -1,13 +1,14 @@
# coding: utf-8 # coding: utf-8
from django.test import TestCase
from django.conf import settings from django.conf import settings
from django.contrib.contenttypes.generic import generic_inlineformset_factory from django.contrib.contenttypes.generic import generic_inlineformset_factory
from django.test import TestCase
# local test models # local test models
from models import Episode, EpisodeExtra, EpisodeMaxNum, EpisodeExclude, \ from models import Episode, EpisodeExtra, EpisodeMaxNum, EpisodeExclude, \
Media, EpisodePermanent, MediaPermanentInline, Category Media, EpisodePermanent, MediaPermanentInline, Category
class GenericAdminViewTest(TestCase): class GenericAdminViewTest(TestCase):
fixtures = ['users.xml'] fixtures = ['users.xml']
@ -41,14 +42,14 @@ class GenericAdminViewTest(TestCase):
A smoke test to ensure GET on the add_view works. A smoke test to ensure GET on the add_view works.
""" """
response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episode/add/') response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episode/add/')
self.failUnlessEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def testBasicEditGet(self): def testBasicEditGet(self):
""" """
A smoke test to ensure GET on the change_view works. A smoke test to ensure GET on the change_view works.
""" """
response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episode/%d/' % self.episode_pk) response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episode/%d/' % self.episode_pk)
self.failUnlessEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def testBasicAddPost(self): def testBasicAddPost(self):
""" """
@ -62,7 +63,7 @@ class GenericAdminViewTest(TestCase):
"generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": u"0", "generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": u"0",
} }
response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/episode/add/', post_data) response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/episode/add/', post_data)
self.failUnlessEqual(response.status_code, 302) # redirect somewhere self.assertEqual(response.status_code, 302) # redirect somewhere
def testBasicEditPost(self): def testBasicEditPost(self):
""" """
@ -83,7 +84,7 @@ class GenericAdminViewTest(TestCase):
} }
url = '/generic_inline_admin/admin/generic_inline_admin/episode/%d/' % self.episode_pk url = '/generic_inline_admin/admin/generic_inline_admin/episode/%d/' % self.episode_pk
response = self.client.post(url, post_data) response = self.client.post(url, post_data)
self.failUnlessEqual(response.status_code, 302) # redirect somewhere self.assertEqual(response.status_code, 302) # redirect somewhere
def testGenericInlineFormset(self): def testGenericInlineFormset(self):
EpisodeMediaFormSet = generic_inlineformset_factory(Media, can_delete=False, extra=3) EpisodeMediaFormSet = generic_inlineformset_factory(Media, can_delete=False, extra=3)
@ -118,7 +119,7 @@ class GenericAdminViewTest(TestCase):
# Regression test for #12340. # Regression test for #12340.
e = Episode.objects.get(name='This Week in Django') e = Episode.objects.get(name='This Week in Django')
formset = inline_formset(instance=e) formset = inline_formset(instance=e)
self.failUnless(formset.get_queryset().ordered) self.assertTrue(formset.get_queryset().ordered)
class GenericInlineAdminParametersTest(TestCase): class GenericInlineAdminParametersTest(TestCase):
fixtures = ['users.xml'] fixtures = ['users.xml']
@ -178,7 +179,7 @@ class GenericInlineAdminParametersTest(TestCase):
e = self._create_object(EpisodeExclude) e = self._create_object(EpisodeExclude)
response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episodeexclude/%s/' % e.pk) response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episodeexclude/%s/' % e.pk)
formset = response.context['inline_admin_formsets'][0].formset formset = response.context['inline_admin_formsets'][0].formset
self.failIf('url' in formset.forms[0], 'The formset has excluded "url" field.') self.assertFalse('url' in formset.forms[0], 'The formset has excluded "url" field.')
class GenericInlineAdminWithUniqueTogetherTest(TestCase): class GenericInlineAdminWithUniqueTogetherTest(TestCase):
fixtures = ['users.xml'] fixtures = ['users.xml']
@ -202,9 +203,9 @@ class GenericInlineAdminWithUniqueTogetherTest(TestCase):
"generic_inline_admin-phonenumber-content_type-object_id-0-category": "%s" % category_id, "generic_inline_admin-phonenumber-content_type-object_id-0-category": "%s" % category_id,
} }
response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/contact/add/') response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/contact/add/')
self.failUnlessEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/contact/add/', post_data) response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/contact/add/', post_data)
self.failUnlessEqual(response.status_code, 302) # redirect somewhere self.assertEqual(response.status_code, 302) # redirect somewhere
class NoInlineDeletionTest(TestCase): class NoInlineDeletionTest(TestCase):
def test_no_deletion(self): def test_no_deletion(self):

View File

@ -52,10 +52,10 @@ class QueryDictTests(unittest.TestCase):
self.assertRaises(AttributeError, q.setlist, 'foo', ['bar']) self.assertRaises(AttributeError, q.setlist, 'foo', ['bar'])
self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar']) self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar'])
self.failUnless(q.has_key('foo')) self.assertTrue(q.has_key('foo'))
self.failUnless('foo' in q) self.assertTrue('foo' in q)
self.failIf(q.has_key('bar')) self.assertFalse(q.has_key('bar'))
self.failIf('bar' in q) self.assertFalse('bar' in q)
self.assertEqual(q.items(), [(u'foo', u'bar')]) self.assertEqual(q.items(), [(u'foo', u'bar')])
self.assertEqual(q.lists(), [(u'foo', [u'bar'])]) self.assertEqual(q.lists(), [(u'foo', [u'bar'])])
@ -92,7 +92,7 @@ class QueryDictTests(unittest.TestCase):
q = QueryDict('').copy() q = QueryDict('').copy()
q['name'] = 'john' q['name'] = 'john'
del q['name'] del q['name']
self.failIf('name' in q) self.assertFalse('name' in q)
def test_basic_mutable_operations(self): def test_basic_mutable_operations(self):
q = QueryDict('').copy() q = QueryDict('').copy()
@ -109,8 +109,8 @@ class QueryDictTests(unittest.TestCase):
q.appendlist('foo', 'another') q.appendlist('foo', 'another')
self.assertEqual(q.getlist('foo'), ['bar', 'baz', 'another']) self.assertEqual(q.getlist('foo'), ['bar', 'baz', 'another'])
self.assertEqual(q['foo'], 'another') self.assertEqual(q['foo'], 'another')
self.failUnless(q.has_key('foo')) self.assertTrue(q.has_key('foo'))
self.failUnless('foo' in q) self.assertTrue('foo' in q)
self.assertEqual(q.items(), [(u'foo', u'another'), (u'name', u'john')]) self.assertEqual(q.items(), [(u'foo', u'another'), (u'name', u'john')])
self.assertEqual(q.lists(), [(u'foo', [u'bar', u'baz', u'another']), (u'name', [u'john'])]) self.assertEqual(q.lists(), [(u'foo', [u'bar', u'baz', u'another']), (u'name', [u'john'])])
@ -213,7 +213,7 @@ class HttpResponseTests(unittest.TestCase):
# If we insert a unicode value it will be converted to an ascii # If we insert a unicode value it will be converted to an ascii
r['value'] = u'test value' r['value'] = u'test value'
self.failUnless(isinstance(r['value'], str)) self.assertTrue(isinstance(r['value'], str))
# An error is raised ~hen a unicode object with non-ascii is assigned. # An error is raised ~hen a unicode object with non-ascii is assigned.
self.assertRaises(UnicodeEncodeError, r.__setitem__, 'value', u't\xebst value') self.assertRaises(UnicodeEncodeError, r.__setitem__, 'value', u't\xebst value')

View File

@ -32,4 +32,4 @@ class PoFileTests(MessageCompilationTests):
# underlying compile_messages function instead # underlying compile_messages function instead
out = StringIO() out = StringIO()
self.assertRaises(CommandError, compile_messages, out, locale=LOCALE) self.assertRaises(CommandError, compile_messages, out, locale=LOCALE)
self.failIf(os.path.exists(self.MO_FILE)) self.assertFalse(os.path.exists(self.MO_FILE))

View File

@ -1,5 +1,6 @@
from django.test import TestCase
from django.forms.models import inlineformset_factory from django.forms.models import inlineformset_factory
from django.test import TestCase
from regressiontests.inline_formsets.models import Poet, Poem, School, Parent, Child from regressiontests.inline_formsets.models import Poet, Poem, School, Parent, Child
@ -20,7 +21,7 @@ class DeletionTests(TestCase):
} }
formset = PoemFormSet(data, instance=poet) formset = PoemFormSet(data, instance=poet)
formset.save() formset.save()
self.failUnless(formset.is_valid()) self.assertTrue(formset.is_valid())
self.assertEqual(Poem.objects.count(), 0) self.assertEqual(Poem.objects.count(), 0)
def test_add_form_deletion_when_invalid(self): def test_add_form_deletion_when_invalid(self):

View File

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from django.test import TestCase from django.conf import settings
from django.http import HttpRequest from django.http import HttpRequest
from django.middleware.common import CommonMiddleware from django.middleware.common import CommonMiddleware
from django.conf import settings from django.test import TestCase
class CommonMiddlewareTest(TestCase): class CommonMiddlewareTest(TestCase):
def setUp(self): def setUp(self):
@ -74,7 +75,7 @@ class CommonMiddlewareTest(TestCase):
try: try:
CommonMiddleware().process_request(request) CommonMiddleware().process_request(request)
except RuntimeError, e: except RuntimeError, e:
self.failUnless('end in a slash' in str(e)) self.assertTrue('end in a slash' in str(e))
settings.DEBUG = False settings.DEBUG = False
def test_append_slash_disabled(self): def test_append_slash_disabled(self):
@ -165,7 +166,7 @@ class CommonMiddlewareTest(TestCase):
request = self._get_request('customurlconf/slash') request = self._get_request('customurlconf/slash')
request.urlconf = 'regressiontests.middleware.extra_urls' request.urlconf = 'regressiontests.middleware.extra_urls'
r = CommonMiddleware().process_request(request) r = CommonMiddleware().process_request(request)
self.failIf(r is None, self.assertFalse(r is None,
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf") "CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
self.assertEquals(r.status_code, 301) self.assertEquals(r.status_code, 301)
self.assertEquals(r['Location'], 'http://testserver/middleware/customurlconf/slash/') self.assertEquals(r['Location'], 'http://testserver/middleware/customurlconf/slash/')
@ -188,7 +189,7 @@ class CommonMiddlewareTest(TestCase):
try: try:
CommonMiddleware().process_request(request) CommonMiddleware().process_request(request)
except RuntimeError, e: except RuntimeError, e:
self.failUnless('end in a slash' in str(e)) self.assertTrue('end in a slash' in str(e))
settings.DEBUG = False settings.DEBUG = False
def test_append_slash_disabled_custom_urlconf(self): def test_append_slash_disabled_custom_urlconf(self):
@ -209,7 +210,7 @@ class CommonMiddlewareTest(TestCase):
request = self._get_request('customurlconf/needsquoting#') request = self._get_request('customurlconf/needsquoting#')
request.urlconf = 'regressiontests.middleware.extra_urls' request.urlconf = 'regressiontests.middleware.extra_urls'
r = CommonMiddleware().process_request(request) r = CommonMiddleware().process_request(request)
self.failIf(r is None, self.assertFalse(r is None,
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf") "CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
self.assertEquals(r.status_code, 301) self.assertEquals(r.status_code, 301)
self.assertEquals( self.assertEquals(

View File

@ -1,11 +1,12 @@
import unittest
from datetime import date from datetime import date
from django import forms from django import forms
from django.forms.models import modelform_factory, ModelChoiceField, fields_for_model, construct_instance
from django.test import TestCase
from django.core.exceptions import FieldError, ValidationError from django.core.exceptions import FieldError, ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms.models import (modelform_factory, ModelChoiceField,
fields_for_model, construct_instance)
from django.utils import unittest
from django.test import TestCase
from models import Person, RealPerson, Triple, FilePathModel, Article, \ from models import Person, RealPerson, Triple, FilePathModel, Article, \
Publication, CustomFF, Author, Author1, Homepage, Document, Edition Publication, CustomFF, Author, Author1, Homepage, Document, Edition
@ -38,10 +39,10 @@ class UniqueTogetherTests(TestCase):
Triple.objects.create(left=1, middle=2, right=3) Triple.objects.create(left=1, middle=2, right=3)
form = TripleForm({'left': '1', 'middle': '2', 'right': '3'}) form = TripleForm({'left': '1', 'middle': '2', 'right': '3'})
self.failIf(form.is_valid()) self.assertFalse(form.is_valid())
form = TripleForm({'left': '1', 'middle': '3', 'right': '1'}) form = TripleForm({'left': '1', 'middle': '3', 'right': '1'})
self.failUnless(form.is_valid()) self.assertTrue(form.is_valid())
class TripleFormWithCleanOverride(forms.ModelForm): class TripleFormWithCleanOverride(forms.ModelForm):
class Meta: class Meta:
@ -59,7 +60,7 @@ class OverrideCleanTests(TestCase):
optional. optional.
""" """
form = TripleFormWithCleanOverride({'left': 1, 'middle': 2, 'right': 1}) form = TripleFormWithCleanOverride({'left': 1, 'middle': 2, 'right': 1})
self.failUnless(form.is_valid()) self.assertTrue(form.is_valid())
# form.instance.left will be None if the instance was not constructed # form.instance.left will be None if the instance was not constructed
# by form.full_clean(). # by form.full_clean().
self.assertEquals(form.instance.left, 1) self.assertEquals(form.instance.left, 1)

View File

@ -1,23 +1,22 @@
import tempfile
import shutil
import os import os
import sys
import posixpath import posixpath
import shutil
import sys
import tempfile
from StringIO import StringIO from StringIO import StringIO
from django.test import TestCase
from django.conf import settings from django.conf import settings
from django.contrib.staticfiles import finders, storage from django.contrib.staticfiles import finders, storage
from django.core.files.storage import default_storage
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage import default_storage
from django.core.management import call_command from django.core.management import call_command
from django.db.models.loading import load_app from django.db.models.loading import load_app
from django.template import Template, Context from django.template import Template, Context
from django.test import TestCase
TEST_ROOT = os.path.dirname(__file__) TEST_ROOT = os.path.dirname(__file__)
class StaticFilesTestCase(TestCase): class StaticFilesTestCase(TestCase):
""" """
Test case with a couple utility assertions. Test case with a couple utility assertions.
@ -73,7 +72,7 @@ class StaticFilesTestCase(TestCase):
settings.INSTALLED_APPS = self.old_installed_apps settings.INSTALLED_APPS = self.old_installed_apps
def assertFileContains(self, filepath, text): def assertFileContains(self, filepath, text):
self.failUnless(text in self._get_file(filepath), self.assertTrue(text in self._get_file(filepath),
"'%s' not in '%s'" % (text, filepath)) "'%s' not in '%s'" % (text, filepath))
def assertFileNotFound(self, filepath): def assertFileNotFound(self, filepath):
@ -178,8 +177,8 @@ class TestFindStatic(BuildStaticTestCase, TestDefaults):
finally: finally:
sys.stdout = _stdout sys.stdout = _stdout
self.assertEquals(len(lines), 3) # three because there is also the "Found <file> here" line self.assertEquals(len(lines), 3) # three because there is also the "Found <file> here" line
self.failUnless('project' in lines[1]) self.assertTrue('project' in lines[1])
self.failUnless('apps' in lines[2]) self.assertTrue('apps' in lines[2])
class TestBuildStatic(BuildStaticTestCase, TestDefaults): class TestBuildStatic(BuildStaticTestCase, TestDefaults):
@ -252,7 +251,7 @@ if sys.platform != 'win32':
With ``--link``, symbolic links are created. With ``--link``, symbolic links are created.
""" """
self.failUnless(os.path.islink(os.path.join(settings.STATIC_ROOT, 'test.txt'))) self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, 'test.txt')))
class TestServeStatic(StaticFilesTestCase): class TestServeStatic(StaticFilesTestCase):

View File

@ -3,15 +3,16 @@
Regression tests for the Test Client, especially the customized assertions. Regression tests for the Test Client, especially the customized assertions.
""" """
import os import os
from django.conf import settings
from django.test import Client, TestCase from django.conf import settings
from django.test.utils import ContextList
from django.core.urlresolvers import reverse
from django.core.exceptions import SuspiciousOperation from django.core.exceptions import SuspiciousOperation
from django.template import TemplateDoesNotExist, TemplateSyntaxError, Context, Template from django.core.urlresolvers import reverse
from django.template import loader from django.template import (TemplateDoesNotExist, TemplateSyntaxError,
Context, Template, loader)
from django.test import Client, TestCase
from django.test.client import encode_file from django.test.client import encode_file
from django.test.utils import ContextList
class AssertContainsTests(TestCase): class AssertContainsTests(TestCase):
def setUp(self): def setUp(self):
@ -484,7 +485,7 @@ class LoginTests(TestCase):
# Create a second client, and log in. # Create a second client, and log in.
c = Client() c = Client()
login = c.login(username='testclient', password='password') login = c.login(username='testclient', password='password')
self.failUnless(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Get a redirection page with the second client. # Get a redirection page with the second client.
response = c.get("/test_client_regress/login_protected_redirect_view/") response = c.get("/test_client_regress/login_protected_redirect_view/")
@ -508,7 +509,7 @@ class SessionEngineTests(TestCase):
def test_login(self): def test_login(self):
"A session engine that modifies the session key can be used to log in" "A session engine that modifies the session key can be used to log in"
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.failUnless(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Try to access a login protected page. # Try to access a login protected page.
response = self.client.get("/test_client/login_protected_view/") response = self.client.get("/test_client/login_protected_view/")
@ -547,7 +548,7 @@ class ExceptionTests(TestCase):
"#5836 - A stale user exception isn't re-raised by the test client." "#5836 - A stale user exception isn't re-raised by the test client."
login = self.client.login(username='testclient',password='password') login = self.client.login(username='testclient',password='password')
self.failUnless(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
try: try:
response = self.client.get("/test_client_regress/staff_only/") response = self.client.get("/test_client_regress/staff_only/")
self.fail("General users should not be able to visit this page") self.fail("General users should not be able to visit this page")
@ -558,7 +559,7 @@ class ExceptionTests(TestCase):
# This next operation should be successful; if it isn't we have a problem. # This next operation should be successful; if it isn't we have a problem.
login = self.client.login(username='staff', password='password') login = self.client.login(username='staff', password='password')
self.failUnless(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
try: try:
self.client.get("/test_client_regress/staff_only/") self.client.get("/test_client_regress/staff_only/")
except SuspiciousOperation: except SuspiciousOperation:
@ -670,7 +671,7 @@ class SessionTests(TestCase):
# Log in # Log in
login = self.client.login(username='testclient',password='password') login = self.client.login(username='testclient',password='password')
self.failUnless(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Session should still contain the modified value # Session should still contain the modified value
response = self.client.get('/test_client_regress/check_session/') response = self.client.get('/test_client_regress/check_session/')
@ -681,7 +682,7 @@ class SessionTests(TestCase):
"""Logout should work whether the user is logged in or not (#9978).""" """Logout should work whether the user is logged in or not (#9978)."""
self.client.logout() self.client.logout()
login = self.client.login(username='testclient',password='password') login = self.client.login(username='testclient',password='password')
self.failUnless(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
self.client.logout() self.client.logout()
self.client.logout() self.client.logout()
@ -875,4 +876,3 @@ class ResponseTemplateDeprecationTests(TestCase):
def test_response_no_template(self): def test_response_no_template(self):
response = self.client.get("/test_client_regress/request_methods/") response = self.client.get("/test_client_regress/request_methods/")
self.assertEqual(response.template, None) self.assertEqual(response.template, None)

View File

@ -27,8 +27,8 @@ class DebugViewTests(TestCase):
'file_data.txt': SimpleUploadedFile('file_data.txt', 'haha'), 'file_data.txt': SimpleUploadedFile('file_data.txt', 'haha'),
} }
response = self.client.post('/views/raises/', data) response = self.client.post('/views/raises/', data)
self.failUnless('file_data.txt' in response.content) self.assertTrue('file_data.txt' in response.content)
self.failIf('haha' in response.content) self.assertFalse('haha' in response.content)
def test_404(self): def test_404(self):
response = self.client.get('/views/raises404/') response = self.client.get('/views/raises404/')
@ -45,7 +45,6 @@ class DebugViewTests(TestCase):
self.client.get(reverse('template_exception', args=(n,))) self.client.get(reverse('template_exception', args=(n,)))
except TemplateSyntaxError, e: except TemplateSyntaxError, e:
raising_loc = inspect.trace()[-1][-2][0].strip() raising_loc = inspect.trace()[-1][-2][0].strip()
self.failIf(raising_loc.find('raise BrokenException') == -1, self.assertFalse(raising_loc.find('raise BrokenException') == -1,
"Failed to find 'raise BrokenException' in last frame of traceback, instead found: %s" % "Failed to find 'raise BrokenException' in last frame of traceback, instead found: %s" %
raising_loc) raising_loc)

View File

@ -19,7 +19,7 @@ class CreateObjectTest(TestCase):
self.assertRedirects(response, '/accounts/login/?next=%s' % view_url) self.assertRedirects(response, '/accounts/login/?next=%s' % view_url)
# Now login and try again. # Now login and try again.
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.failUnless(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
response = self.client.get(view_url) response = self.client.get(view_url)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'views/article_form.html') self.assertTemplateUsed(response, 'views/article_form.html')