Updated test assertions that have been deprecated by the move to unittest2. In summary, this means:

assert_ -> assertTrue
 assertEquals -> assertEqual
 failUnless -> assertTrue

For full details, see http://www.voidspace.org.uk/python/articles/unittest2.shtml#deprecations

git-svn-id: http://code.djangoproject.com/svn/django/trunk@15728 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Russell Keith-Magee 2011-03-03 15:04:39 +00:00
parent b7c41c1fbb
commit afd040d4d3
110 changed files with 1197 additions and 1197 deletions

View File

@ -61,7 +61,7 @@ class BasicTestCase(TestCase):
command_output = new_io.getvalue().strip()
self.assertEqual(command_output, 'Superuser created successfully.')
u = User.objects.get(username="joe")
self.assertEquals(u.email, 'joe@somewhere.org')
self.assertEqual(u.email, 'joe@somewhere.org')
# created password should be unusable
self.assertFalse(u.has_usable_password())
@ -78,7 +78,7 @@ class BasicTestCase(TestCase):
command_output = new_io.getvalue().strip()
self.assertEqual(command_output, '')
u = User.objects.get(username="joe2")
self.assertEquals(u.email, 'joe2@somewhere.org')
self.assertEqual(u.email, 'joe2@somewhere.org')
self.assertFalse(u.has_usable_password())
@ -90,6 +90,6 @@ class BasicTestCase(TestCase):
stdout=new_io
)
u = User.objects.get(username="joe+admin@somewhere.org")
self.assertEquals(u.email, 'joe@somewhere.org')
self.assertEqual(u.email, 'joe@somewhere.org')
self.assertFalse(u.has_usable_password())

View File

@ -32,7 +32,7 @@ class LoginRequiredTestCase(AuthViewsTestCase):
"""
response = self.client.get(view_url)
self.assertEqual(response.status_code, 302)
self.assert_(login_url in response['Location'])
self.assertTrue(login_url in response['Location'])
self.login()
response = self.client.get(view_url)
self.assertEqual(response.status_code, 200)

View File

@ -30,15 +30,15 @@ class RemoteUserTest(TestCase):
num_users = User.objects.count()
response = self.client.get('/remote_user/')
self.assert_(response.context['user'].is_anonymous())
self.assertTrue(response.context['user'].is_anonymous())
self.assertEqual(User.objects.count(), num_users)
response = self.client.get('/remote_user/', REMOTE_USER=None)
self.assert_(response.context['user'].is_anonymous())
self.assertTrue(response.context['user'].is_anonymous())
self.assertEqual(User.objects.count(), num_users)
response = self.client.get('/remote_user/', REMOTE_USER='')
self.assert_(response.context['user'].is_anonymous())
self.assertTrue(response.context['user'].is_anonymous())
self.assertEqual(User.objects.count(), num_users)
def test_unknown_user(self):
@ -115,7 +115,7 @@ class RemoteUserNoCreateTest(RemoteUserTest):
def test_unknown_user(self):
num_users = User.objects.count()
response = self.client.get('/remote_user/', REMOTE_USER='newuser')
self.assert_(response.context['user'].is_anonymous())
self.assertTrue(response.context['user'].is_anonymous())
self.assertEqual(User.objects.count(), num_users)

View File

@ -40,53 +40,53 @@ class AuthViewsTestCase(TestCase):
'password': password
}
)
self.assertEquals(response.status_code, 302)
self.assert_(response['Location'].endswith(settings.LOGIN_REDIRECT_URL))
self.assert_(SESSION_KEY in self.client.session)
self.assertEqual(response.status_code, 302)
self.assertTrue(response['Location'].endswith(settings.LOGIN_REDIRECT_URL))
self.assertTrue(SESSION_KEY in self.client.session)
class PasswordResetTest(AuthViewsTestCase):
def test_email_not_found(self):
"Error is raised if the provided email address isn't currently registered"
response = self.client.get('/password_reset/')
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'})
self.assertContains(response, "That e-mail address doesn't have an associated user account")
self.assertEquals(len(mail.outbox), 0)
self.assertEqual(len(mail.outbox), 0)
def test_email_found(self):
"Email is sent if a valid email address is provided for password reset"
response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
self.assertEquals(response.status_code, 302)
self.assertEquals(len(mail.outbox), 1)
self.assert_("http://" in mail.outbox[0].body)
self.assertEquals(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email)
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
self.assertTrue("http://" in mail.outbox[0].body)
self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email)
def test_email_found_custom_from(self):
"Email is sent if a valid email address is provided for password reset when a custom from_email is provided."
response = self.client.post('/password_reset_from_email/', {'email': 'staffmember@example.com'})
self.assertEquals(response.status_code, 302)
self.assertEquals(len(mail.outbox), 1)
self.assertEquals("staffmember@example.com", mail.outbox[0].from_email)
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual("staffmember@example.com", mail.outbox[0].from_email)
def _test_confirm_start(self):
# Start by creating the email
response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
self.assertEquals(response.status_code, 302)
self.assertEquals(len(mail.outbox), 1)
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
return self._read_signup_email(mail.outbox[0])
def _read_signup_email(self, email):
urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
self.assert_(urlmatch is not None, "No URL found in sent email")
self.assertTrue(urlmatch is not None, "No URL found in sent email")
return urlmatch.group(), urlmatch.groups()[0]
def test_confirm_valid(self):
url, path = self._test_confirm_start()
response = self.client.get(path)
# redirect to a 'complete' page:
self.assertEquals(response.status_code, 200)
self.assert_("Please enter your new password" in response.content)
self.assertEqual(response.status_code, 200)
self.assertTrue("Please enter your new password" in response.content)
def test_confirm_invalid(self):
url, path = self._test_confirm_start()
@ -95,20 +95,20 @@ class PasswordResetTest(AuthViewsTestCase):
path = path[:-5] + ("0"*4) + path[-1]
response = self.client.get(path)
self.assertEquals(response.status_code, 200)
self.assert_("The password reset link was invalid" in response.content)
self.assertEqual(response.status_code, 200)
self.assertTrue("The password reset link was invalid" in response.content)
def test_confirm_invalid_user(self):
# Ensure that we get a 200 response for a non-existant user, not a 404
response = self.client.get('/reset/123456-1-1/')
self.assertEquals(response.status_code, 200)
self.assert_("The password reset link was invalid" in response.content)
self.assertEqual(response.status_code, 200)
self.assertTrue("The password reset link was invalid" in response.content)
def test_confirm_overflow_user(self):
# Ensure that we get a 200 response for a base36 user id that overflows int
response = self.client.get('/reset/zzzzzzzzzzzzz-1-1/')
self.assertEquals(response.status_code, 200)
self.assert_("The password reset link was invalid" in response.content)
self.assertEqual(response.status_code, 200)
self.assertTrue("The password reset link was invalid" in response.content)
def test_confirm_invalid_post(self):
# Same as test_confirm_invalid, but trying
@ -120,29 +120,29 @@ class PasswordResetTest(AuthViewsTestCase):
'new_password2':' anewpassword'})
# Check the password has not been changed
u = User.objects.get(email='staffmember@example.com')
self.assert_(not u.check_password("anewpassword"))
self.assertTrue(not u.check_password("anewpassword"))
def test_confirm_complete(self):
url, path = self._test_confirm_start()
response = self.client.post(path, {'new_password1': 'anewpassword',
'new_password2': 'anewpassword'})
# It redirects us to a 'complete' page:
self.assertEquals(response.status_code, 302)
self.assertEqual(response.status_code, 302)
# Check the password has been changed
u = User.objects.get(email='staffmember@example.com')
self.assert_(u.check_password("anewpassword"))
self.assertTrue(u.check_password("anewpassword"))
# Check we can't use the link again
response = self.client.get(path)
self.assertEquals(response.status_code, 200)
self.assert_("The password reset link was invalid" in response.content)
self.assertEqual(response.status_code, 200)
self.assertTrue("The password reset link was invalid" in response.content)
def test_confirm_different_passwords(self):
url, path = self._test_confirm_start()
response = self.client.post(path, {'new_password1': 'anewpassword',
'new_password2':' x'})
self.assertEquals(response.status_code, 200)
self.assert_("The two password fields didn't match" in response.content)
self.assertEqual(response.status_code, 200)
self.assertTrue("The two password fields didn't match" in response.content)
class ChangePasswordTest(AuthViewsTestCase):
@ -152,8 +152,8 @@ class ChangePasswordTest(AuthViewsTestCase):
'password': password
}
)
self.assertEquals(response.status_code, 200)
self.assert_("Please enter a correct username and password. Note that both fields are case-sensitive." in response.content)
self.assertEqual(response.status_code, 200)
self.assertTrue("Please enter a correct username and password. Note that both fields are case-sensitive." in response.content)
def logout(self):
response = self.client.get('/logout/')
@ -166,8 +166,8 @@ class ChangePasswordTest(AuthViewsTestCase):
'new_password2': 'password1',
}
)
self.assertEquals(response.status_code, 200)
self.assert_("Your old password was entered incorrectly. Please enter it again." in response.content)
self.assertEqual(response.status_code, 200)
self.assertTrue("Your old password was entered incorrectly. Please enter it again." in response.content)
def test_password_change_fails_with_mismatched_passwords(self):
self.login()
@ -177,8 +177,8 @@ class ChangePasswordTest(AuthViewsTestCase):
'new_password2': 'donuts',
}
)
self.assertEquals(response.status_code, 200)
self.assert_("The two password fields didn't match." in response.content)
self.assertEqual(response.status_code, 200)
self.assertTrue("The two password fields didn't match." in response.content)
def test_password_change_succeeds(self):
self.login()
@ -188,8 +188,8 @@ class ChangePasswordTest(AuthViewsTestCase):
'new_password2': 'password1',
}
)
self.assertEquals(response.status_code, 302)
self.assert_(response['Location'].endswith('/password_change/done/'))
self.assertEqual(response.status_code, 302)
self.assertTrue(response['Location'].endswith('/password_change/done/'))
self.fail_login()
self.login(password='password1')
@ -197,14 +197,14 @@ class LoginTest(AuthViewsTestCase):
def test_current_site_in_context_after_login(self):
response = self.client.get(reverse('django.contrib.auth.views.login'))
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
if Site._meta.installed:
site = Site.objects.get_current()
self.assertEquals(response.context['site'], site)
self.assertEquals(response.context['site_name'], site.name)
self.assertEqual(response.context['site'], site)
self.assertEqual(response.context['site_name'], site.name)
else:
self.assertIsInstance(response.context['site'], RequestSite)
self.assert_(isinstance(response.context['form'], AuthenticationForm),
self.assertTrue(isinstance(response.context['form'], AuthenticationForm),
'Login form is not an AuthenticationForm')
def test_security_check(self, password='password'):
@ -226,7 +226,7 @@ class LoginTest(AuthViewsTestCase):
'password': password,
}
)
self.assertEquals(response.status_code, 302)
self.assertEqual(response.status_code, 302)
self.assertFalse(bad_url in response['Location'],
"%s should be blocked" % bad_url)
@ -249,7 +249,7 @@ class LoginTest(AuthViewsTestCase):
'password': password,
}
)
self.assertEquals(response.status_code, 302)
self.assertEqual(response.status_code, 302)
self.assertTrue(good_url in response['Location'],
"%s should be allowed" % good_url)
@ -268,7 +268,7 @@ class LoginURLSettings(AuthViewsTestCase):
def get_login_required_url(self, login_url):
settings.LOGIN_URL = login_url
response = self.client.get('/login_required/')
self.assertEquals(response.status_code, 302)
self.assertEqual(response.status_code, 302)
return response['Location']
def test_standard_login_url(self):
@ -317,14 +317,14 @@ class LogoutTest(AuthViewsTestCase):
urls = 'django.contrib.auth.tests.urls'
def confirm_logged_out(self):
self.assert_(SESSION_KEY not in self.client.session)
self.assertTrue(SESSION_KEY not in self.client.session)
def test_logout_default(self):
"Logout without next_page option renders the default template"
self.login()
response = self.client.get('/logout/')
self.assertEquals(200, response.status_code)
self.assert_('Logged out' in response.content)
self.assertEqual(200, response.status_code)
self.assertTrue('Logged out' in response.content)
self.confirm_logged_out()
def test_14377(self):
@ -338,11 +338,11 @@ class LogoutTest(AuthViewsTestCase):
self.login()
response = self.client.get('/logout/next_page/')
self.assertEqual(response.status_code, 302)
self.assert_(response['Location'].endswith('/somewhere/'))
self.assertTrue(response['Location'].endswith('/somewhere/'))
response = self.client.get('/logout/next_page/?next=/login/')
self.assertEqual(response.status_code, 302)
self.assert_(response['Location'].endswith('/login/'))
self.assertTrue(response['Location'].endswith('/login/'))
self.confirm_logged_out()
@ -351,7 +351,7 @@ class LogoutTest(AuthViewsTestCase):
self.login()
response = self.client.get('/logout/next_page/')
self.assertEqual(response.status_code, 302)
self.assert_(response['Location'].endswith('/somewhere/'))
self.assertTrue(response['Location'].endswith('/somewhere/'))
self.confirm_logged_out()
def test_logout_with_redirect_argument(self):
@ -359,7 +359,7 @@ class LogoutTest(AuthViewsTestCase):
self.login()
response = self.client.get('/logout/?next=/login/')
self.assertEqual(response.status_code, 302)
self.assert_(response['Location'].endswith('/login/'))
self.assertTrue(response['Location'].endswith('/login/'))
self.confirm_logged_out()
def test_logout_with_custom_redirect_argument(self):
@ -367,7 +367,7 @@ class LogoutTest(AuthViewsTestCase):
self.login()
response = self.client.get('/logout/custom_query/?follow=/somewhere/')
self.assertEqual(response.status_code, 302)
self.assert_(response['Location'].endswith('/somewhere/'))
self.assertTrue(response['Location'].endswith('/somewhere/'))
self.confirm_logged_out()
def test_security_check(self, password='password'):
@ -386,7 +386,7 @@ class LogoutTest(AuthViewsTestCase):
}
self.login()
response = self.client.get(nasty_url)
self.assertEquals(response.status_code, 302)
self.assertEqual(response.status_code, 302)
self.assertFalse(bad_url in response['Location'],
"%s should be blocked" % bad_url)
self.confirm_logged_out()
@ -407,7 +407,7 @@ class LogoutTest(AuthViewsTestCase):
}
self.login()
response = self.client.get(safe_url)
self.assertEquals(response.status_code, 302)
self.assertEqual(response.status_code, 302)
self.assertTrue(good_url in response['Location'],
"%s should be allowed" % good_url)
self.confirm_logged_out()

View File

@ -34,13 +34,13 @@ class FlatpageCSRFTests(TestCase):
def test_view_flatpage(self):
"A flatpage can be served through a view, even when the middleware is in use"
response = self.client.get('/flatpage_root/flatpage/')
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it flat!</p>")
def test_view_non_existent_flatpage(self):
"A non-existent flatpage raises 404 when served through a view, even when the middleware is in use"
response = self.client.get('/flatpage_root/no_such_flatpage/')
self.assertEquals(response.status_code, 404)
self.assertEqual(response.status_code, 404)
def test_view_authenticated_flatpage(self):
"A flatpage served through a view can require authentication"
@ -49,31 +49,31 @@ class FlatpageCSRFTests(TestCase):
User.objects.create_user('testuser', 'test@example.com', 's3krit')
self.client.login(username='testuser',password='s3krit')
response = self.client.get('/flatpage_root/sekrit/')
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it sekrit!</p>")
def test_fallback_flatpage(self):
"A flatpage can be served by the fallback middlware"
response = self.client.get('/flatpage/')
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it flat!</p>")
def test_fallback_non_existent_flatpage(self):
"A non-existent flatpage raises a 404 when served by the fallback middlware"
response = self.client.get('/no_such_flatpage/')
self.assertEquals(response.status_code, 404)
self.assertEqual(response.status_code, 404)
def test_post_view_flatpage(self):
"POSTing to a flatpage served through a view will raise a CSRF error if no token is provided (Refs #14156)"
response = self.client.post('/flatpage_root/flatpage/')
self.assertEquals(response.status_code, 403)
self.assertEqual(response.status_code, 403)
def test_post_fallback_flatpage(self):
"POSTing to a flatpage served by the middleware will raise a CSRF error if no token is provided (Refs #14156)"
response = self.client.post('/flatpage/')
self.assertEquals(response.status_code, 403)
self.assertEqual(response.status_code, 403)
def test_post_unknown_page(self):
"POSTing to an unknown page isn't caught as a 403 CSRF error"
response = self.client.post('/no_such_page/')
self.assertEquals(response.status_code, 404)
self.assertEqual(response.status_code, 404)

View File

@ -30,13 +30,13 @@ class FlatpageMiddlewareTests(TestCase):
def test_view_flatpage(self):
"A flatpage can be served through a view, even when the middleware is in use"
response = self.client.get('/flatpage_root/flatpage/')
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it flat!</p>")
def test_view_non_existent_flatpage(self):
"A non-existent flatpage raises 404 when served through a view, even when the middleware is in use"
response = self.client.get('/flatpage_root/no_such_flatpage/')
self.assertEquals(response.status_code, 404)
self.assertEqual(response.status_code, 404)
def test_view_authenticated_flatpage(self):
"A flatpage served through a view can require authentication"
@ -45,19 +45,19 @@ class FlatpageMiddlewareTests(TestCase):
User.objects.create_user('testuser', 'test@example.com', 's3krit')
self.client.login(username='testuser',password='s3krit')
response = self.client.get('/flatpage_root/sekrit/')
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it sekrit!</p>")
def test_fallback_flatpage(self):
"A flatpage can be served by the fallback middlware"
response = self.client.get('/flatpage/')
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it flat!</p>")
def test_fallback_non_existent_flatpage(self):
"A non-existent flatpage raises a 404 when served by the fallback middlware"
response = self.client.get('/no_such_flatpage/')
self.assertEquals(response.status_code, 404)
self.assertEqual(response.status_code, 404)
def test_fallback_authenticated_flatpage(self):
"A flatpage served by the middleware can require authentication"
@ -66,5 +66,5 @@ class FlatpageMiddlewareTests(TestCase):
User.objects.create_user('testuser', 'test@example.com', 's3krit')
self.client.login(username='testuser',password='s3krit')
response = self.client.get('/sekrit/')
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it sekrit!</p>")

View File

@ -35,7 +35,7 @@ class FlatpageTemplateTagTests(TestCase):
"{{ page.title }},"
"{% endfor %}"
).render(Context())
self.assertEquals(out, "A Flatpage,A Nested Flatpage,")
self.assertEqual(out, "A Flatpage,A Nested Flatpage,")
def test_get_flatpages_tag_for_anon_user(self):
"The flatpage template tag retrives unregistered flatpages for an anonymous user"
@ -48,7 +48,7 @@ class FlatpageTemplateTagTests(TestCase):
).render(Context({
'anonuser': AnonymousUser()
}))
self.assertEquals(out, "A Flatpage,A Nested Flatpage,")
self.assertEqual(out, "A Flatpage,A Nested Flatpage,")
def test_get_flatpages_tag_for_user(self):
"The flatpage template tag retrives all flatpages for an authenticated user"
@ -61,7 +61,7 @@ class FlatpageTemplateTagTests(TestCase):
).render(Context({
'me': self.me
}))
self.assertEquals(out, "A Flatpage,A Nested Flatpage,Sekrit Nested Flatpage,Sekrit Flatpage,")
self.assertEqual(out, "A Flatpage,A Nested Flatpage,Sekrit Nested Flatpage,Sekrit Flatpage,")
def test_get_flatpages_with_prefix(self):
"The flatpage template tag retrives unregistered prefixed flatpages by default"
@ -72,7 +72,7 @@ class FlatpageTemplateTagTests(TestCase):
"{{ page.title }},"
"{% endfor %}"
).render(Context())
self.assertEquals(out, "A Nested Flatpage,")
self.assertEqual(out, "A Nested Flatpage,")
def test_get_flatpages_with_prefix_for_anon_user(self):
"The flatpage template tag retrives unregistered prefixed flatpages for an anonymous user"
@ -85,7 +85,7 @@ class FlatpageTemplateTagTests(TestCase):
).render(Context({
'anonuser': AnonymousUser()
}))
self.assertEquals(out, "A Nested Flatpage,")
self.assertEqual(out, "A Nested Flatpage,")
def test_get_flatpages_with_prefix_for_user(self):
"The flatpage template tag retrive prefixed flatpages for an authenticated user"
@ -98,7 +98,7 @@ class FlatpageTemplateTagTests(TestCase):
).render(Context({
'me': self.me
}))
self.assertEquals(out, "A Nested Flatpage,Sekrit Nested Flatpage,")
self.assertEqual(out, "A Nested Flatpage,Sekrit Nested Flatpage,")
def test_get_flatpages_with_variable_prefix(self):
"The prefix for the flatpage template tag can be a template variable"
@ -111,7 +111,7 @@ class FlatpageTemplateTagTests(TestCase):
).render(Context({
'location_prefix': '/location/'
}))
self.assertEquals(out, "A Nested Flatpage,")
self.assertEqual(out, "A Nested Flatpage,")
def test_parsing_errors(self):
"There are various ways that the flatpages template tag won't parse"

View File

@ -31,13 +31,13 @@ class FlatpageViewTests(TestCase):
def test_view_flatpage(self):
"A flatpage can be served through a view"
response = self.client.get('/flatpage_root/flatpage/')
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it flat!</p>")
def test_view_non_existent_flatpage(self):
"A non-existent flatpage raises 404 when served through a view"
response = self.client.get('/flatpage_root/no_such_flatpage/')
self.assertEquals(response.status_code, 404)
self.assertEqual(response.status_code, 404)
def test_view_authenticated_flatpage(self):
"A flatpage served through a view can require authentication"
@ -46,18 +46,18 @@ class FlatpageViewTests(TestCase):
User.objects.create_user('testuser', 'test@example.com', 's3krit')
self.client.login(username='testuser',password='s3krit')
response = self.client.get('/flatpage_root/sekrit/')
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it sekrit!</p>")
def test_fallback_flatpage(self):
"A fallback flatpage won't be served if the middleware is disabled"
response = self.client.get('/flatpage/')
self.assertEquals(response.status_code, 404)
self.assertEqual(response.status_code, 404)
def test_fallback_non_existent_flatpage(self):
"A non-existent flatpage won't be served if the fallback middlware is disabled"
response = self.client.get('/no_such_flatpage/')
self.assertEquals(response.status_code, 404)
self.assertEqual(response.status_code, 404)
def test_view_flatpage_special_chars(self):
"A flatpage with special chars in the URL can be served through a view"
@ -71,5 +71,5 @@ class FlatpageViewTests(TestCase):
fp.sites.add(1)
response = self.client.get('/flatpage_root/some.very_special~chars-here/')
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "<p>Isn't it special!</p>")

View File

@ -65,8 +65,8 @@ class PreviewTests(TestCase):
response = self.client.get('/test1/')
stage = self.input % 1
self.assertContains(response, stage, 1)
self.assertEquals(response.context['custom_context'], True)
self.assertEquals(response.context['form'].initial, {'field1': 'Works!'})
self.assertEqual(response.context['custom_context'], True)
self.assertEqual(response.context['form'].initial, {'field1': 'Works!'})
def test_form_preview(self):
"""
@ -291,14 +291,14 @@ class WizardTests(TestCase):
step should be zero for the first form
"""
response = self.client.get('/wizard/')
self.assertEquals(0, response.context['step0'])
self.assertEqual(0, response.context['step0'])
def test_step_increments(self):
"""
step should be incremented when we go to the next page
"""
response = self.client.post('/wizard/', {"0-field":"test", "wizard_step":"0"})
self.assertEquals(1, response.context['step0'])
self.assertEqual(1, response.context['step0'])
def test_bad_hash(self):
"""
@ -308,7 +308,7 @@ class WizardTests(TestCase):
{"0-field":"test",
"1-field":"test2",
"wizard_step": "1"})
self.assertEquals(0, response.context['step0'])
self.assertEqual(0, response.context['step0'])
def test_good_hash_django12(self):
"""
@ -322,7 +322,7 @@ class WizardTests(TestCase):
"hash_0": "2fdbefd4c0cad51509478fbacddf8b13",
"wizard_step": "1"}
response = self.client.post('/wizard/', data)
self.assertEquals(2, response.context['step0'])
self.assertEqual(2, response.context['step0'])
def test_good_hash_django12_subclass(self):
"""
@ -337,7 +337,7 @@ class WizardTests(TestCase):
"hash_0": "2fdbefd4c0cad51509478fbacddf8b13",
"wizard_step": "1"}
response = self.client.post('/wizard2/', data)
self.assertEquals(0, response.context['step0'])
self.assertEqual(0, response.context['step0'])
def test_good_hash_current(self):
"""
@ -349,7 +349,7 @@ class WizardTests(TestCase):
"hash_0": "7e9cea465f6a10a6fb47fcea65cb9a76350c9a5c",
"wizard_step": "1"}
response = self.client.post('/wizard/', data)
self.assertEquals(2, response.context['step0'])
self.assertEqual(2, response.context['step0'])
def test_14498(self):
"""

View File

@ -49,8 +49,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
def test00b_geomtype_25d(self):
"Testing OGRGeomType object with 25D types."
wkb25bit = OGRGeomType.wkb25bit
self.failUnless(OGRGeomType(wkb25bit + 1) == 'Point25D')
self.failUnless(OGRGeomType('MultiLineString25D') == (5 + wkb25bit))
self.assertTrue(OGRGeomType(wkb25bit + 1) == 'Point25D')
self.assertTrue(OGRGeomType('MultiLineString25D') == (5 + wkb25bit))
self.assertEqual('GeometryCollectionField', OGRGeomType('GeometryCollection25D').django)
def test01a_wkt(self):

View File

@ -867,7 +867,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
g1 = g.transform(4326, clone=True)
self.assertEqual(g1.tuple, g.tuple)
self.assertEqual(g1.srid, 4326)
self.assert_(g1 is not g, "Clone didn't happen")
self.assertTrue(g1 is not g, "Clone didn't happen")
old_has_gdal = gdal.HAS_GDAL
try:
@ -883,7 +883,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
g1 = g.transform(4326, clone=True)
self.assertEqual(g1.tuple, g.tuple)
self.assertEqual(g1.srid, 4326)
self.assert_(g1 is not g, "Clone didn't happen")
self.assertTrue(g1 is not g, "Clone didn't happen")
finally:
gdal.HAS_GDAL = old_has_gdal
@ -907,7 +907,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)
g1 = g.transform(2774, clone=True)
self.assert_(g1 is None)
self.assertTrue(g1 is None)
g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)
g.transform(2774)
@ -916,7 +916,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)
g1 = g.transform(2774, clone=True)
self.assert_(g1 is None)
self.assertTrue(g1 is None)
finally:
warnings.simplefilter('default', UserWarning)
@ -1032,17 +1032,17 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
if not GEOS_PREPARE: return
g = GEOSGeometry("POINT(0 0)")
self.assert_(g.valid)
self.assert_(isinstance(g.valid_reason, basestring))
self.assertTrue(g.valid)
self.assertTrue(isinstance(g.valid_reason, basestring))
self.assertEqual(g.valid_reason, "Valid Geometry")
print "\nBEGIN - expecting GEOS_NOTICE; safe to ignore.\n"
g = GEOSGeometry("LINESTRING(0 0, 0 0)")
self.assert_(not g.valid)
self.assert_(isinstance(g.valid_reason, basestring))
self.assert_(g.valid_reason.startswith("Too few points in geometry component"))
self.assertTrue(not g.valid)
self.assertTrue(isinstance(g.valid_reason, basestring))
self.assertTrue(g.valid_reason.startswith("Too few points in geometry component"))
print "\nEND - expecting GEOS_NOTICE; safe to ignore.\n"

View File

@ -362,26 +362,26 @@ class ListMixinTest(unittest.TestCase):
pl, ul = self.lists_of_len()
self.assertEqual(pl, ul, 'cmp for equal')
self.assert_(pl >= ul, 'cmp for gte self')
self.assert_(pl <= ul, 'cmp for lte self')
self.assert_(ul >= pl, 'cmp for self gte')
self.assert_(ul <= pl, 'cmp for self lte')
self.assertTrue(pl >= ul, 'cmp for gte self')
self.assertTrue(pl <= ul, 'cmp for lte self')
self.assertTrue(ul >= pl, 'cmp for self gte')
self.assertTrue(ul <= pl, 'cmp for self lte')
self.assert_(pl + [5] > ul, 'cmp')
self.assert_(pl + [5] >= ul, 'cmp')
self.assert_(pl < ul + [2], 'cmp')
self.assert_(pl <= ul + [2], 'cmp')
self.assert_(ul + [5] > pl, 'cmp')
self.assert_(ul + [5] >= pl, 'cmp')
self.assert_(ul < pl + [2], 'cmp')
self.assert_(ul <= pl + [2], 'cmp')
self.assertTrue(pl + [5] > ul, 'cmp')
self.assertTrue(pl + [5] >= ul, 'cmp')
self.assertTrue(pl < ul + [2], 'cmp')
self.assertTrue(pl <= ul + [2], 'cmp')
self.assertTrue(ul + [5] > pl, 'cmp')
self.assertTrue(ul + [5] >= pl, 'cmp')
self.assertTrue(ul < pl + [2], 'cmp')
self.assertTrue(ul <= pl + [2], 'cmp')
pl[1] = 20
self.assert_(pl > ul, 'cmp for gt self')
self.assert_(ul < pl, 'cmp for self lt')
self.assertTrue(pl > ul, 'cmp for gt self')
self.assertTrue(ul < pl, 'cmp for self lt')
pl[1] = -20
self.assert_(pl < ul, 'cmp for lt self')
self.assert_(pl < ul, 'cmp for lt self')
self.assertTrue(pl < ul, 'cmp for lt self')
self.assertTrue(pl < ul, 'cmp for lt self')
class ListMixinTestSingle(ListMixinTest):
listType = UserListB

View File

@ -72,7 +72,7 @@ class Geo3DTest(TestCase):
pnt = Point(x, y, z, srid=4326)
City3D.objects.create(name=name, point=pnt)
city = City3D.objects.get(name=name)
self.failUnless(city.point.hasz)
self.assertTrue(city.point.hasz)
self.assertEqual(z, city.point.z)
# Interstate (2D / 3D and Geographic/Projected variants)
@ -93,7 +93,7 @@ class Geo3DTest(TestCase):
interstate = Interstate3D.objects.get(name=name)
interstate_proj = InterstateProj3D.objects.get(name=name)
for i in [interstate, interstate_proj]:
self.failUnless(i.line.hasz)
self.assertTrue(i.line.hasz)
self.assertEqual(exp_z, tuple(i.line.z))
# Creating 3D Polygon.
@ -101,7 +101,7 @@ class Geo3DTest(TestCase):
Polygon2D.objects.create(name='2D BBox', poly=bbox2d)
Polygon3D.objects.create(name='3D BBox', poly=bbox3d)
p3d = Polygon3D.objects.get(name='3D BBox')
self.failUnless(p3d.poly.hasz)
self.assertTrue(p3d.poly.hasz)
self.assertEqual(bbox3d, p3d.poly)
def test01a_3d_layermapping(self):
@ -138,7 +138,7 @@ class Geo3DTest(TestCase):
# KML should be 3D.
# `SELECT ST_AsKML(point, 6) FROM geo3d_city3d WHERE name = 'Houston';`
ref_kml_regex = re.compile(r'^<Point><coordinates>-95.363\d+,29.763\d+,18</coordinates></Point>$')
self.failUnless(ref_kml_regex.match(h.kml))
self.assertTrue(ref_kml_regex.match(h.kml))
def test02b_geojson(self):
"Test GeoQuerySet.geojson() with Z values."
@ -146,7 +146,7 @@ class Geo3DTest(TestCase):
# GeoJSON should be 3D
# `SELECT ST_AsGeoJSON(point, 6) FROM geo3d_city3d WHERE name='Houston';`
ref_json_regex = re.compile(r'^{"type":"Point","coordinates":\[-95.363151,29.763374,18(\.0+)?\]}$')
self.failUnless(ref_json_regex.match(h.geojson))
self.assertTrue(ref_json_regex.match(h.geojson))
def test03a_union(self):
"Testing the Union aggregate of 3D models."
@ -155,7 +155,7 @@ class Geo3DTest(TestCase):
ref_ewkt = 'SRID=4326;MULTIPOINT(-123.305196 48.462611 15,-104.609252 38.255001 1433,-97.521157 34.464642 380,-96.801611 32.782057 147,-95.363151 29.763374 18,-95.23506 38.971823 251,-87.650175 41.850385 181,174.783117 -41.315268 14)'
ref_union = GEOSGeometry(ref_ewkt)
union = City3D.objects.aggregate(Union('point'))['point__union']
self.failUnless(union.hasz)
self.assertTrue(union.hasz)
self.assertEqual(ref_union, union)
def test03b_extent(self):

View File

@ -133,11 +133,11 @@ class GeoModelTest(TestCase):
# No precision parameter for Oracle :-/
gml_regex = re.compile(r'^<gml:Point srsName="SDO:4326" xmlns:gml="http://www.opengis.net/gml"><gml:coordinates decimal="\." cs="," ts=" ">-104.60925\d+,38.25500\d+ </gml:coordinates></gml:Point>')
for ptown in [ptown1, ptown2]:
self.failUnless(gml_regex.match(ptown.gml))
self.assertTrue(gml_regex.match(ptown.gml))
else:
gml_regex = re.compile(r'^<gml:Point srsName="EPSG:4326"><gml:coordinates>-104\.60925\d+,38\.255001</gml:coordinates></gml:Point>')
for ptown in [ptown1, ptown2]:
self.failUnless(gml_regex.match(ptown.gml))
self.assertTrue(gml_regex.match(ptown.gml))
def test03c_geojson(self):
"Testing GeoJSON output from the database using GeoQuerySet.geojson()."
@ -678,15 +678,15 @@ class GeoModelTest(TestCase):
# SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country" WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr('MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))')
self.failUnless(ref.equals_exact(Country.objects.snap_to_grid(0.1).get(name='San Marino').snap_to_grid, tol))
self.assertTrue(ref.equals_exact(Country.objects.snap_to_grid(0.1).get(name='San Marino').snap_to_grid, tol))
# SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country" WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr('MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))')
self.failUnless(ref.equals_exact(Country.objects.snap_to_grid(0.05, 0.23).get(name='San Marino').snap_to_grid, tol))
self.assertTrue(ref.equals_exact(Country.objects.snap_to_grid(0.05, 0.23).get(name='San Marino').snap_to_grid, tol))
# SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country" WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr('MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,12.45 43.87,12.4 43.87)))')
self.failUnless(ref.equals_exact(Country.objects.snap_to_grid(0.05, 0.23, 0.5, 0.17).get(name='San Marino').snap_to_grid, tol))
self.assertTrue(ref.equals_exact(Country.objects.snap_to_grid(0.05, 0.23, 0.5, 0.17).get(name='San Marino').snap_to_grid, tol))
@no_mysql
@no_spatialite

View File

@ -173,8 +173,8 @@ class RelatedGeoModelTest(TestCase):
for m, d, t in zip(gqs, gvqs, gvlqs):
# The values should be Geometry objects and not raw strings returned
# by the spatial database.
self.failUnless(isinstance(d['point'], Geometry))
self.failUnless(isinstance(t[1], Geometry))
self.assertTrue(isinstance(d['point'], Geometry))
self.assertTrue(isinstance(t[1], Geometry))
self.assertEqual(m.point, d['point'])
self.assertEqual(m.point, t[1])
@ -207,8 +207,8 @@ class RelatedGeoModelTest(TestCase):
combined = qs1 | qs2
names = [c.name for c in combined]
self.assertEqual(2, len(names))
self.failUnless('Aurora' in names)
self.failUnless('Kecksburg' in names)
self.assertTrue('Aurora' in names)
self.assertTrue('Kecksburg' in names)
def test11_geoquery_pickle(self):
"Ensuring GeoQuery objects are unpickled correctly. See #10839."

View File

@ -26,7 +26,7 @@ class GeometryFieldTest(unittest.TestCase):
xform_geom = GEOSGeometry('POINT (951640.547328465 4219369.26171664)', srid=32140)
# The cleaned geometry should be transformed to 32140.
cleaned_geom = fld.clean('SRID=4326;POINT (-95.363151 29.763374)')
self.failUnless(xform_geom.equals_exact(cleaned_geom, tol))
self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol))
def test02_null(self):
"Testing GeometryField's handling of null (None) geometries."

View File

@ -107,7 +107,7 @@ class DistanceTest(unittest.TestCase):
self.assertEqual(d4.m, 10)
a5 = d1 * D(m=10)
self.assert_(isinstance(a5, Area))
self.assertTrue(isinstance(a5, Area))
self.assertEqual(a5.sq_m, 100*10)
try:
@ -151,9 +151,9 @@ class DistanceTest(unittest.TestCase):
d2 = D(km=1)
d3 = D(km=0)
self.assert_(d2 > d1)
self.assert_(d1 == d1)
self.assert_(d1 < d2)
self.assertTrue(d2 > d1)
self.assertTrue(d1 == d1)
self.assertTrue(d1 < d2)
self.failIf(d3)
def testUnitsStr(self):
@ -309,9 +309,9 @@ class AreaTest(unittest.TestCase):
a2 = A(sq_km=1)
a3 = A(sq_km=0)
self.assert_(a2 > a1)
self.assert_(a1 == a1)
self.assert_(a1 < a2)
self.assertTrue(a2 > a1)
self.assertTrue(a1 == a1)
self.assertTrue(a1 < a2)
self.failIf(a3)
def testUnitsStr(self):

View File

@ -349,7 +349,7 @@ class BaseTest(TestCase):
self.assertFalse(storage.used)
# After iterating the storage engine directly, the used flag is set.
data = list(storage)
self.assert_(storage.used)
self.assertTrue(storage.used)
# The data does not disappear because it has been iterated.
self.assertEqual(data, list(storage))
@ -357,7 +357,7 @@ class BaseTest(TestCase):
storage = self.get_existing_storage()
self.assertFalse(storage.added_new)
storage.add(constants.INFO, 'Test message 3')
self.assert_(storage.added_new)
self.assertTrue(storage.added_new)
def test_default_level(self):
# get_level works even with no storage on the request.
@ -378,7 +378,7 @@ class BaseTest(TestCase):
storage = self.storage_class(request)
request._messages = storage
self.assert_(set_level(request, 5))
self.assertTrue(set_level(request, 5))
self.assertEqual(get_level(request), 5)
add_level_messages(storage)
@ -389,7 +389,7 @@ class BaseTest(TestCase):
storage = self.storage_class(request)
request._messages = storage
self.assert_(set_level(request, 30))
self.assertTrue(set_level(request, 30))
self.assertEqual(get_level(request), 30)
add_level_messages(storage)

View File

@ -83,7 +83,7 @@ class CookieTest(BaseTest):
self.assertEqual(cookie_storing, 4)
self.assertEqual(len(unstored_messages), 1)
self.assert_(unstored_messages[0].message == '0' * msg_size)
self.assertTrue(unstored_messages[0].message == '0' * msg_size)
def test_json_encoder_decoder(self):
"""

View File

@ -40,7 +40,7 @@ class SitemapTests(TestCase):
# Retrieve the sitemap.
response = self.client.get('/simple/index.xml')
# Check for all the important bits:
self.assertEquals(response.content, """<?xml version="1.0" encoding="UTF-8"?>
self.assertEqual(response.content, """<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap>
</sitemapindex>
@ -51,7 +51,7 @@ class SitemapTests(TestCase):
# Retrieve the sitemap.
response = self.client.get('/simple/custom-index.xml')
# Check for all the important bits:
self.assertEquals(response.content, """<?xml version="1.0" encoding="UTF-8"?>
self.assertEqual(response.content, """<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a customised template -->
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap>
@ -63,7 +63,7 @@ class SitemapTests(TestCase):
# Retrieve the sitemap.
response = self.client.get('/simple/sitemap.xml')
# Check for all the important bits:
self.assertEquals(response.content, """<?xml version="1.0" encoding="UTF-8"?>
self.assertEqual(response.content, """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
</urlset>
@ -74,7 +74,7 @@ class SitemapTests(TestCase):
# Retrieve the sitemap.
response = self.client.get('/simple/custom-sitemap.xml')
# Check for all the important bits:
self.assertEquals(response.content, """<?xml version="1.0" encoding="UTF-8"?>
self.assertEqual(response.content, """<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a customised template -->
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
@ -105,7 +105,7 @@ class SitemapTests(TestCase):
for username in User.objects.values_list("username", flat=True):
expected += "<url><loc>%s/users/%s/</loc></url>" % (self.base_url, username)
# Check for all the important bits:
self.assertEquals(response.content, """<?xml version="1.0" encoding="UTF-8"?>
self.assertEqual(response.content, """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
%s
</urlset>
@ -148,7 +148,7 @@ class SitemapTests(TestCase):
# Retrieve the sitemap.
response = self.client.get('/simple/sitemap.xml')
# Check for all the important bits:
self.assertEquals(response.content, """<?xml version="1.0" encoding="UTF-8"?>
self.assertEqual(response.content, """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>http://testserver/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
</urlset>

View File

@ -18,7 +18,7 @@ class SitesFrameworkTests(TestCase):
def test_site_manager(self):
# Make sure that get_current() does not return a deleted Site object.
s = Site.objects.get_current()
self.assert_(isinstance(s, Site))
self.assertTrue(isinstance(s, Site))
s.delete()
self.assertRaises(ObjectDoesNotExist, Site.objects.get_current)
@ -41,7 +41,7 @@ class SitesFrameworkTests(TestCase):
"SERVER_PORT": "80",
}
site = get_current_site(request)
self.assert_(isinstance(site, Site))
self.assertTrue(isinstance(site, Site))
self.assertEqual(site.id, settings.SITE_ID)
# Test that an exception is raised if the sites framework is installed
@ -52,5 +52,5 @@ class SitesFrameworkTests(TestCase):
# A RequestSite is returned if the sites framework is not installed
Site._meta.installed = False
site = get_current_site(request)
self.assert_(isinstance(site, RequestSite))
self.assertTrue(isinstance(site, RequestSite))
self.assertEqual(site.name, u"example.com")

View File

@ -831,8 +831,8 @@ class TestCase(unittest.TestCase):
self.fail(self._formatMessage(msg, standardMsg))
def assertDictEqual(self, d1, d2, msg=None):
self.assert_(isinstance(d1, dict), 'First argument is not a dictionary')
self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary')
self.assertTrue(isinstance(d1, dict), 'First argument is not a dictionary')
self.assertTrue(isinstance(d2, dict), 'Second argument is not a dictionary')
if d1 != d2:
standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
@ -909,9 +909,9 @@ class TestCase(unittest.TestCase):
def assertMultiLineEqual(self, first, second, msg=None):
"""Assert that two multi-line strings are equal."""
self.assert_(isinstance(first, basestring), (
self.assertTrue(isinstance(first, basestring), (
'First argument is not a string'))
self.assert_(isinstance(second, basestring), (
self.assertTrue(isinstance(second, basestring), (
'Second argument is not a string'))
if first != second:

View File

@ -1079,7 +1079,7 @@ The following is a simple unit test using the request factory::
# Test my_view() as if it were deployed at /customer/details
response = my_view(request)
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
TestCase
--------

View File

@ -41,7 +41,7 @@ class BaseAggregateTestCase(TestCase):
vals = Book.objects.aggregate(Sum("publisher__num_awards"))
self.assertEqual(len(vals), 1)
self.assertEquals(vals["publisher__num_awards__sum"], 30)
self.assertEqual(vals["publisher__num_awards__sum"], 30)
vals = Publisher.objects.aggregate(Sum("book__price"))
self.assertEqual(len(vals), 1)

View File

@ -946,7 +946,7 @@ class ModelFormsetTest(TestCase):
# default. This is required to ensure the value is tested for change correctly
# when determine what extra forms have changed to save.
self.assertEquals(len(formset.forms), 1) # this formset only has one form
self.assertEqual(len(formset.forms), 1) # this formset only has one form
form = formset.forms[0]
now = form.fields['date_joined'].initial()
result = form.as_p()

View File

@ -11,7 +11,7 @@ class InheritanceSameModelNameTests(TestCase):
def test_inheritance_related_name(self):
from modeltests.model_inheritance.models import Copy
self.assertEquals(
self.assertEqual(
self.title.attached_model_inheritance_copy_set.create(
content='Save $ on V1agr@',
url='http://v1agra.com/',
@ -20,7 +20,7 @@ class InheritanceSameModelNameTests(TestCase):
def test_inheritance_with_same_model_name(self):
from modeltests.model_inheritance_same_model_name.models import Copy
self.assertEquals(
self.assertEqual(
self.title.attached_model_inheritance_same_model_name_copy_set.create(
content='The Web framework for perfectionists with deadlines.',
url='http://www.djangoproject.com/',

View File

@ -32,5 +32,5 @@ class ProxyModelInheritanceTests(TransactionTestCase):
sys.path = self.old_sys_path
def test_table_exists(self):
self.assertEquals(NiceModel.objects.all().count(), 0)
self.assertEquals(ProxyModel.objects.all().count(), 0)
self.assertEqual(NiceModel.objects.all().count(), 0)
self.assertEqual(ProxyModel.objects.all().count(), 0)

View File

@ -30,10 +30,10 @@ class RawQueryTests(TestCase):
for field in model._meta.fields:
# Check that all values on the model are equal
self.assertEquals(getattr(item,field.attname),
self.assertEqual(getattr(item,field.attname),
getattr(orig_item,field.attname))
# This includes checking that they are the same type
self.assertEquals(type(getattr(item,field.attname)),
self.assertEqual(type(getattr(item,field.attname)),
type(getattr(orig_item,field.attname)))
def assertNoAnnotations(self, results):
@ -67,9 +67,9 @@ class RawQueryTests(TestCase):
iterated over.
"""
q = Author.objects.raw('SELECT * FROM raw_query_author')
self.assert_(q.query.cursor is None)
self.assertTrue(q.query.cursor is None)
list(q)
self.assert_(q.query.cursor is not None)
self.assertTrue(q.query.cursor is not None)
def testFkeyRawQuery(self):
"""
@ -204,7 +204,7 @@ class RawQueryTests(TestCase):
self.assertEqual(third_author.first_name, 'Bob')
first_two = Author.objects.raw(query)[0:2]
self.assertEquals(len(first_two), 2)
self.assertEqual(len(first_two), 2)
self.assertRaises(TypeError, lambda: Author.objects.raw(query)['test'])

View File

@ -225,7 +225,7 @@ class SerializersTestBase(object):
serial_str = serializers.serialize(self.serializer_name, [a])
date_values = self._get_field_values(serial_str, "pub_date")
self.assertEquals(date_values[0], "0001-02-03 04:05:06")
self.assertEqual(date_values[0], "0001-02-03 04:05:06")
def test_pkless_serialized_strings(self):
"""

View File

@ -79,7 +79,7 @@ class ClientTest(TestCase):
"Check the value of HTTP headers returned in a response"
response = self.client.get("/test_client/header_view/")
self.assertEquals(response['X-DJANGO-TEST'], 'Slartibartfast')
self.assertEqual(response['X-DJANGO-TEST'], 'Slartibartfast')
def test_raw_post(self):
"POST raw data (with a content type) to a view"
@ -140,7 +140,7 @@ class ClientTest(TestCase):
"A URL that redirects can be followed to termination."
response = self.client.get('/test_client/double_redirect_view/', follow=True)
self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=302, target_status_code=200)
self.assertEquals(len(response.redirect_chain), 2)
self.assertEqual(len(response.redirect_chain), 2)
def test_redirect_http(self):
"GET a URL that redirects to an http URI"
@ -400,7 +400,7 @@ class ClientTest(TestCase):
response = self.client.post('/test_client/session_view/')
# Check that the session was modified
self.assertEquals(self.client.session['tobacconist'], 'hovercraft')
self.assertEqual(self.client.session['tobacconist'], 'hovercraft')
def test_view_with_exception(self):
"Request a page that is known to throw an error"

View File

@ -47,7 +47,7 @@ class ManyToManyUnmanagedTests(TestCase):
"""
table = Unmanaged2._meta.get_field('mm').m2m_db_table()
tables = connection.introspection.table_names()
self.assert_(table not in tables, "Table '%s' should not exist, but it does." % table)
self.assertTrue(table not in tables, "Table '%s' should not exist, but it does." % table)
def test_many_to_many_between_unmanaged_and_managed(self):
"""
@ -55,4 +55,4 @@ class ManyToManyUnmanagedTests(TestCase):
"""
table = Managed1._meta.get_field('mm').m2m_db_table()
tables = connection.introspection.table_names()
self.assert_(table in tables, "Table '%s' does not exist." % table)
self.assertTrue(table in tables, "Table '%s' does not exist." % table)

View File

@ -8,13 +8,13 @@ class CommandTests(TestCase):
def test_command(self):
out = StringIO()
management.call_command('dance', stdout=out)
self.assertEquals(out.getvalue(),
self.assertEqual(out.getvalue(),
"I don't feel like dancing Rock'n'Roll.")
def test_command_style(self):
out = StringIO()
management.call_command('dance', style='Jive', stdout=out)
self.assertEquals(out.getvalue(),
self.assertEqual(out.getvalue(),
"I don't feel like dancing Jive.")
def test_explode(self):

View File

@ -8,7 +8,7 @@ class ValidationTestCase(unittest.TestCase):
try:
clean()
except ValidationError, e:
self.assertEquals(sorted(failed_fields), sorted(e.message_dict.keys()))
self.assertEqual(sorted(failed_fields), sorted(e.message_dict.keys()))
def assertFieldFailsValidationWithMessage(self, clean, field_name, message):
self.assertRaises(ValidationError, clean)
@ -16,6 +16,6 @@ class ValidationTestCase(unittest.TestCase):
clean()
except ValidationError, e:
self.assertTrue(field_name in e.message_dict)
self.assertEquals(message, e.message_dict[field_name])
self.assertEqual(message, e.message_dict[field_name])

View File

@ -141,18 +141,18 @@ def create_simple_test_method(validator, expected, value, num):
class TestSimpleValidators(TestCase):
def test_single_message(self):
v = ValidationError('Not Valid')
self.assertEquals(str(v), "[u'Not Valid']")
self.assertEquals(repr(v), "ValidationError([u'Not Valid'])")
self.assertEqual(str(v), "[u'Not Valid']")
self.assertEqual(repr(v), "ValidationError([u'Not Valid'])")
def test_message_list(self):
v = ValidationError(['First Problem', 'Second Problem'])
self.assertEquals(str(v), "[u'First Problem', u'Second Problem']")
self.assertEquals(repr(v), "ValidationError([u'First Problem', u'Second Problem'])")
self.assertEqual(str(v), "[u'First Problem', u'Second Problem']")
self.assertEqual(repr(v), "ValidationError([u'First Problem', u'Second Problem'])")
def test_message_dict(self):
v = ValidationError({'first': 'First Problem'})
self.assertEquals(str(v), "{'first': 'First Problem'}")
self.assertEquals(repr(v), "ValidationError({'first': 'First Problem'})")
self.assertEqual(str(v), "{'first': 'First Problem'}")
self.assertEqual(repr(v), "ValidationError({'first': 'First Problem'})")
test_counter = 0
for validator, value, expected in TEST_DATA:

View File

@ -42,20 +42,20 @@ class FilterSpecsTests(TestCase):
# Make sure the last choice is None and is selected
filterspec = changelist.get_filters(request)[0][0]
self.assertEquals(force_unicode(filterspec.title()), u'year')
self.assertEqual(force_unicode(filterspec.title()), u'year')
choices = list(filterspec.choices(changelist))
self.assertEquals(choices[-1]['selected'], True)
self.assertEquals(choices[-1]['query_string'], '?year__isnull=True')
self.assertEqual(choices[-1]['selected'], True)
self.assertEqual(choices[-1]['query_string'], '?year__isnull=True')
request = self.request_factory.get('/', {'year': '2002'})
changelist = self.get_changelist(request, Book, modeladmin)
# Make sure the correct choice is selected
filterspec = changelist.get_filters(request)[0][0]
self.assertEquals(force_unicode(filterspec.title()), u'year')
self.assertEqual(force_unicode(filterspec.title()), u'year')
choices = list(filterspec.choices(changelist))
self.assertEquals(choices[2]['selected'], True)
self.assertEquals(choices[2]['query_string'], '?year=2002')
self.assertEqual(choices[2]['selected'], True)
self.assertEqual(choices[2]['query_string'], '?year=2002')
def test_RelatedFilterSpec_ForeignKey(self):
modeladmin = BookAdmin(Book, admin.site)
@ -70,20 +70,20 @@ class FilterSpecsTests(TestCase):
# Make sure the last choice is None and is selected
filterspec = changelist.get_filters(request)[0][1]
self.assertEquals(force_unicode(filterspec.title()), u'author')
self.assertEqual(force_unicode(filterspec.title()), u'author')
choices = list(filterspec.choices(changelist))
self.assertEquals(choices[-1]['selected'], True)
self.assertEquals(choices[-1]['query_string'], '?author__isnull=True')
self.assertEqual(choices[-1]['selected'], True)
self.assertEqual(choices[-1]['query_string'], '?author__isnull=True')
request = self.request_factory.get('/', {'author__id__exact': '1'})
changelist = self.get_changelist(request, Book, modeladmin)
# Make sure the correct choice is selected
filterspec = changelist.get_filters(request)[0][1]
self.assertEquals(force_unicode(filterspec.title()), u'author')
self.assertEqual(force_unicode(filterspec.title()), u'author')
choices = list(filterspec.choices(changelist))
self.assertEquals(choices[1]['selected'], True)
self.assertEquals(choices[1]['query_string'], '?author__id__exact=1')
self.assertEqual(choices[1]['selected'], True)
self.assertEqual(choices[1]['query_string'], '?author__id__exact=1')
def test_RelatedFilterSpec_ManyToMany(self):
modeladmin = BookAdmin(Book, admin.site)
@ -96,20 +96,20 @@ class FilterSpecsTests(TestCase):
# Make sure the last choice is None and is selected
filterspec = changelist.get_filters(request)[0][2]
self.assertEquals(force_unicode(filterspec.title()), u'user')
self.assertEqual(force_unicode(filterspec.title()), u'user')
choices = list(filterspec.choices(changelist))
self.assertEquals(choices[-1]['selected'], True)
self.assertEquals(choices[-1]['query_string'], '?contributors__isnull=True')
self.assertEqual(choices[-1]['selected'], True)
self.assertEqual(choices[-1]['query_string'], '?contributors__isnull=True')
request = self.request_factory.get('/', {'contributors__id__exact': '2'})
changelist = self.get_changelist(request, Book, modeladmin)
# Make sure the correct choice is selected
filterspec = changelist.get_filters(request)[0][2]
self.assertEquals(force_unicode(filterspec.title()), u'user')
self.assertEqual(force_unicode(filterspec.title()), u'user')
choices = list(filterspec.choices(changelist))
self.assertEquals(choices[2]['selected'], True)
self.assertEquals(choices[2]['query_string'], '?contributors__id__exact=2')
self.assertEqual(choices[2]['selected'], True)
self.assertEqual(choices[2]['query_string'], '?contributors__id__exact=2')
def test_RelatedFilterSpec_reverse_relationships(self):
@ -124,20 +124,20 @@ class FilterSpecsTests(TestCase):
# Make sure the last choice is None and is selected
filterspec = changelist.get_filters(request)[0][0]
self.assertEquals(force_unicode(filterspec.title()), u'book')
self.assertEqual(force_unicode(filterspec.title()), u'book')
choices = list(filterspec.choices(changelist))
self.assertEquals(choices[-1]['selected'], True)
self.assertEquals(choices[-1]['query_string'], '?books_authored__isnull=True')
self.assertEqual(choices[-1]['selected'], True)
self.assertEqual(choices[-1]['query_string'], '?books_authored__isnull=True')
request = self.request_factory.get('/', {'books_authored__id__exact': '1'})
changelist = self.get_changelist(request, User, modeladmin)
# Make sure the correct choice is selected
filterspec = changelist.get_filters(request)[0][0]
self.assertEquals(force_unicode(filterspec.title()), u'book')
self.assertEqual(force_unicode(filterspec.title()), u'book')
choices = list(filterspec.choices(changelist))
self.assertEquals(choices[1]['selected'], True)
self.assertEquals(choices[1]['query_string'], '?books_authored__id__exact=1')
self.assertEqual(choices[1]['selected'], True)
self.assertEqual(choices[1]['query_string'], '?books_authored__id__exact=1')
# M2M relationship -----
request = self.request_factory.get('/', {'books_contributed__isnull': 'True'})
@ -148,20 +148,20 @@ class FilterSpecsTests(TestCase):
# Make sure the last choice is None and is selected
filterspec = changelist.get_filters(request)[0][1]
self.assertEquals(force_unicode(filterspec.title()), u'book')
self.assertEqual(force_unicode(filterspec.title()), u'book')
choices = list(filterspec.choices(changelist))
self.assertEquals(choices[-1]['selected'], True)
self.assertEquals(choices[-1]['query_string'], '?books_contributed__isnull=True')
self.assertEqual(choices[-1]['selected'], True)
self.assertEqual(choices[-1]['query_string'], '?books_contributed__isnull=True')
request = self.request_factory.get('/', {'books_contributed__id__exact': '2'})
changelist = self.get_changelist(request, User, modeladmin)
# Make sure the correct choice is selected
filterspec = changelist.get_filters(request)[0][1]
self.assertEquals(force_unicode(filterspec.title()), u'book')
self.assertEqual(force_unicode(filterspec.title()), u'book')
choices = list(filterspec.choices(changelist))
self.assertEquals(choices[2]['selected'], True)
self.assertEquals(choices[2]['query_string'], '?books_contributed__id__exact=2')
self.assertEqual(choices[2]['selected'], True)
self.assertEqual(choices[2]['query_string'], '?books_contributed__id__exact=2')
class CustomUserAdmin(UserAdmin):
list_filter = ('books_authored', 'books_contributed')

View File

@ -155,7 +155,7 @@ class AdminScriptTestCase(unittest.TestCase):
def assertNoOutput(self, stream):
"Utility assertion: assert that the given stream is empty"
self.assertEquals(len(stream), 0, "Stream should be empty: actually contains '%s'" % stream)
self.assertEqual(len(stream), 0, "Stream should be empty: actually contains '%s'" % stream)
def assertOutput(self, stream, msg):
"Utility assertion: assert that the given message exists in the output"
self.assertTrue(msg in stream, "'%s' does not match actual output text '%s'" % (msg, stream))
@ -545,7 +545,7 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase):
args = ['startapp','settings_test']
out, err = self.run_django_admin(args,'settings')
self.assertNoOutput(err)
self.assert_(os.path.exists(os.path.join(test_dir, 'settings_test')))
self.assertTrue(os.path.exists(os.path.join(test_dir, 'settings_test')))
shutil.rmtree(os.path.join(test_dir, 'settings_test'))
def test_builtin_command(self):

View File

@ -24,7 +24,7 @@ class NestedObjectsTests(TestCase):
self.objs = [Count.objects.create(num=i) for i in range(5)]
def _check(self, target):
self.assertEquals(self.n.nested(lambda obj: obj.num), target)
self.assertEqual(self.n.nested(lambda obj: obj.num), target)
def _connect(self, i, j):
self.objs[i].parent = self.objs[j]
@ -146,24 +146,24 @@ class UtilTests(unittest.TestCase):
"""
Tests for label_for_field
"""
self.assertEquals(
self.assertEqual(
label_for_field("title", Article),
"title"
)
self.assertEquals(
self.assertEqual(
label_for_field("title2", Article),
"another name"
)
self.assertEquals(
self.assertEqual(
label_for_field("title2", Article, return_attr=True),
("another name", None)
)
self.assertEquals(
self.assertEqual(
label_for_field("__unicode__", Article),
"article"
)
self.assertEquals(
self.assertEqual(
label_for_field("__str__", Article),
"article"
)
@ -175,29 +175,29 @@ class UtilTests(unittest.TestCase):
def test_callable(obj):
return "nothing"
self.assertEquals(
self.assertEqual(
label_for_field(test_callable, Article),
"Test callable"
)
self.assertEquals(
self.assertEqual(
label_for_field(test_callable, Article, return_attr=True),
("Test callable", test_callable)
)
self.assertEquals(
self.assertEqual(
label_for_field("test_from_model", Article),
"Test from model"
)
self.assertEquals(
self.assertEqual(
label_for_field("test_from_model", Article, return_attr=True),
("Test from model", Article.test_from_model)
)
self.assertEquals(
self.assertEqual(
label_for_field("test_from_model_with_override", Article),
"not What you Expect"
)
self.assertEquals(
self.assertEqual(
label_for_field(lambda x: "nothing", Article),
"--"
)
@ -207,11 +207,11 @@ class UtilTests(unittest.TestCase):
return "nothing"
test_from_model.short_description = "not Really the Model"
self.assertEquals(
self.assertEqual(
label_for_field("test_from_model", Article, model_admin=MockModelAdmin),
"not Really the Model"
)
self.assertEquals(
self.assertEqual(
label_for_field("test_from_model", Article,
model_admin = MockModelAdmin,
return_attr = True
@ -223,15 +223,15 @@ class UtilTests(unittest.TestCase):
"""
Regression test for #13963
"""
self.assertEquals(
self.assertEqual(
label_for_field('location', Event, return_attr=True),
('location', None),
)
self.assertEquals(
self.assertEqual(
label_for_field('event', Location, return_attr=True),
('awesome event', None),
)
self.assertEquals(
self.assertEqual(
label_for_field('guest', Event, return_attr=True),
('awesome guest', None),
)

View File

@ -478,7 +478,7 @@ class SaveAsTests(TestCase):
initial model.
"""
response = self.client.get('/test_admin/admin/admin_views/person/1/')
self.assert_(response.context['save_as'])
self.assertTrue(response.context['save_as'])
post_data = {'_saveasnew':'', 'name':'John M', 'gender':3, 'alive':'checked'}
response = self.client.post('/test_admin/admin/admin_views/person/1/', post_data)
self.assertEqual(response.context['form_url'], '../add/')
@ -503,32 +503,32 @@ class CustomModelAdminTest(AdminViewBasicTest):
self.client.logout()
request = self.client.get('/test_admin/admin2/')
self.assertTemplateUsed(request, 'custom_admin/login.html')
self.assert_('Hello from a custom login template' in request.content)
self.assertTrue('Hello from a custom login template' in request.content)
def testCustomAdminSiteLogoutTemplate(self):
request = self.client.get('/test_admin/admin2/logout/')
self.assertTemplateUsed(request, 'custom_admin/logout.html')
self.assert_('Hello from a custom logout template' in request.content)
self.assertTrue('Hello from a custom logout template' in request.content)
def testCustomAdminSiteIndexViewAndTemplate(self):
request = self.client.get('/test_admin/admin2/')
self.assertTemplateUsed(request, 'custom_admin/index.html')
self.assert_('Hello from a custom index template *bar*' in request.content)
self.assertTrue('Hello from a custom index template *bar*' in request.content)
def testCustomAdminSitePasswordChangeTemplate(self):
request = self.client.get('/test_admin/admin2/password_change/')
self.assertTemplateUsed(request, 'custom_admin/password_change_form.html')
self.assert_('Hello from a custom password change form template' in request.content)
self.assertTrue('Hello from a custom password change form template' in request.content)
def testCustomAdminSitePasswordChangeDoneTemplate(self):
request = self.client.get('/test_admin/admin2/password_change/done/')
self.assertTemplateUsed(request, 'custom_admin/password_change_done.html')
self.assert_('Hello from a custom password change done template' in request.content)
self.assertTrue('Hello from a custom password change done template' in request.content)
def testCustomAdminSiteView(self):
self.client.login(username='super', password='secret')
response = self.client.get('/test_admin/%s/my_view/' % self.urlbit)
self.assert_(response.content == "Django is a magical pony!", response.content)
self.assertTrue(response.content == "Django is a magical pony!", response.content)
def get_perm(Model, perm):
"""Return the permission object, for the Model"""
@ -725,8 +725,8 @@ class AdminViewPermissionsTest(TestCase):
post = self.client.post('/test_admin/admin/admin_views/article/add/', add_dict)
self.assertRedirects(post, '/test_admin/admin/')
self.assertEqual(Article.objects.all().count(), 4)
self.assertEquals(len(mail.outbox), 1)
self.assertEquals(mail.outbox[0].subject, 'Greetings from a created object')
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, 'Greetings from a created object')
self.client.get('/test_admin/admin/logout/')
# Super can add too, but is redirected to the change list view
@ -801,12 +801,12 @@ class AdminViewPermissionsTest(TestCase):
request = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/1/')
self.assertEqual(request.status_code, 403)
request = self.client.post('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/1/', {'name': 'changed'})
self.assertEquals(RowLevelChangePermissionModel.objects.get(id=1).name, 'odd id')
self.assertEqual(RowLevelChangePermissionModel.objects.get(id=1).name, 'odd id')
self.assertEqual(request.status_code, 403)
request = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/2/')
self.assertEqual(request.status_code, 200)
request = self.client.post('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/2/', {'name': 'changed'})
self.assertEquals(RowLevelChangePermissionModel.objects.get(id=2).name, 'changed')
self.assertEqual(RowLevelChangePermissionModel.objects.get(id=2).name, 'changed')
self.assertRedirects(request, '/test_admin/admin/')
self.client.get('/test_admin/admin/logout/')
for login_dict in [self.joepublic_login, self.no_username_login]:
@ -815,14 +815,14 @@ class AdminViewPermissionsTest(TestCase):
self.assertEqual(request.status_code, 200)
self.assertContains(request, 'login-form')
request = self.client.post('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/1/', {'name': 'changed'})
self.assertEquals(RowLevelChangePermissionModel.objects.get(id=1).name, 'odd id')
self.assertEqual(RowLevelChangePermissionModel.objects.get(id=1).name, 'odd id')
self.assertEqual(request.status_code, 200)
self.assertContains(request, 'login-form')
request = self.client.get('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/2/')
self.assertEqual(request.status_code, 200)
self.assertContains(request, 'login-form')
request = self.client.post('/test_admin/admin/admin_views/rowlevelchangepermissionmodel/2/', {'name': 'changed again'})
self.assertEquals(RowLevelChangePermissionModel.objects.get(id=2).name, 'changed')
self.assertEqual(RowLevelChangePermissionModel.objects.get(id=2).name, 'changed')
self.assertEqual(request.status_code, 200)
self.assertContains(request, 'login-form')
self.client.get('/test_admin/admin/logout/')
@ -856,7 +856,7 @@ class AdminViewPermissionsTest(TestCase):
# Test custom change list template with custom extra context
request = self.client.get('/test_admin/admin/admin_views/customarticle/')
self.assertEqual(request.status_code, 200)
self.assert_("var hello = 'Hello!';" in request.content)
self.assertTrue("var hello = 'Hello!';" in request.content)
self.assertTemplateUsed(request, 'custom_admin/change_list.html')
# Test custom add form template
@ -916,8 +916,8 @@ class AdminViewPermissionsTest(TestCase):
post = self.client.post('/test_admin/admin/admin_views/article/1/delete/', delete_dict)
self.assertRedirects(post, '/test_admin/admin/')
self.assertEqual(Article.objects.all().count(), 2)
self.assertEquals(len(mail.outbox), 1)
self.assertEquals(mail.outbox[0].subject, 'Greetings from a deleted object')
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, 'Greetings from a deleted object')
article_ct = ContentType.objects.get_for_model(Article)
logged = LogEntry.objects.get(content_type=article_ct, action_flag=DELETION)
self.assertEqual(logged.object_id, u'1')
@ -1108,7 +1108,7 @@ class AdminViewStringPrimaryKeyTest(TestCase):
counted_presence_before = response.content.count(should_contain)
response = self.client.get('/test_admin/admin/')
counted_presence_after = response.content.count(should_contain)
self.assertEquals(counted_presence_before - 1,
self.assertEqual(counted_presence_before - 1,
counted_presence_after)
def test_deleteconfirmation_link(self):
@ -1568,7 +1568,7 @@ class AdminViewListEditable(TestCase):
}
response = self.client.post('/test_admin/admin/admin_views/person/', data)
non_form_errors = response.context['cl'].formset.non_form_errors()
self.assert_(isinstance(non_form_errors, ErrorList))
self.assertTrue(isinstance(non_form_errors, ErrorList))
self.assertEqual(str(non_form_errors), str(ErrorList(["Grace is not a Zombie"])))
def test_list_editable_ordering(self):
@ -1853,8 +1853,8 @@ class AdminActionsTest(TestCase):
'index': 0,
}
response = self.client.post('/test_admin/admin/admin_views/subscriber/', action_data)
self.assertEquals(len(mail.outbox), 1)
self.assertEquals(mail.outbox[0].subject, 'Greetings from a ModelAdmin action')
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, 'Greetings from a ModelAdmin action')
def test_model_admin_default_delete_action(self):
"Tests the default delete action defined as a ModelAdmin method"
@ -1927,8 +1927,8 @@ class AdminActionsTest(TestCase):
'index': 0,
}
response = self.client.post('/test_admin/admin/admin_views/externalsubscriber/', action_data)
self.assertEquals(len(mail.outbox), 1)
self.assertEquals(mail.outbox[0].subject, 'Greetings from a function action')
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, 'Greetings from a function action')
def test_custom_function_action_with_redirect(self):
"Tests a custom action defined in a function"
@ -1958,19 +1958,19 @@ class AdminActionsTest(TestCase):
def test_model_without_action(self):
"Tests a ModelAdmin without any action"
response = self.client.get('/test_admin/admin/admin_views/oldsubscriber/')
self.assertEquals(response.context["action_form"], None)
self.assert_(
self.assertEqual(response.context["action_form"], None)
self.assertTrue(
'<input type="checkbox" class="action-select"' not in response.content,
"Found an unexpected action toggle checkboxbox in response"
)
self.assert_('action-checkbox-column' not in response.content,
self.assertTrue('action-checkbox-column' not in response.content,
"Found unexpected action-checkbox-column class in response")
def test_model_without_action_still_has_jquery(self):
"Tests that a ModelAdmin without any actions still gets jQuery included in page"
response = self.client.get('/test_admin/admin/admin_views/oldsubscriber/')
self.assertEquals(response.context["action_form"], None)
self.assert_('jquery.min.js' in response.content,
self.assertEqual(response.context["action_form"], None)
self.assertTrue('jquery.min.js' in response.content,
"jQuery missing from admin pages for model with no admin actions"
)
@ -1978,7 +1978,7 @@ class AdminActionsTest(TestCase):
"Tests that the checkbox column class is present in the response"
response = self.client.get('/test_admin/admin/admin_views/subscriber/')
self.assertNotEqual(response.context["action_form"], None)
self.assert_('action-checkbox-column' in response.content,
self.assertTrue('action-checkbox-column' in response.content,
"Expected an action-checkbox-column in response")
def test_multiple_actions_form(self):
@ -1995,8 +1995,8 @@ class AdminActionsTest(TestCase):
response = self.client.post('/test_admin/admin/admin_views/externalsubscriber/', action_data)
# Send mail, don't delete.
self.assertEquals(len(mail.outbox), 1)
self.assertEquals(mail.outbox[0].subject, 'Greetings from a function action')
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, 'Greetings from a function action')
def test_user_message_on_none_selected(self):
"""
@ -2039,7 +2039,7 @@ class AdminActionsTest(TestCase):
self.assertNotEquals(response.context["action_form"], None)
response = self.client.get(
'/test_admin/admin/admin_views/subscriber/?%s' % IS_POPUP_VAR)
self.assertEquals(response.context["action_form"], None)
self.assertEqual(response.context["action_form"], None)
class TestCustomChangeList(TestCase):

View File

@ -47,7 +47,7 @@ class AdminFormfieldForDBFieldTests(TestCase):
widget = ff.widget
# Check that we got a field of the right type
self.assert_(
self.assertTrue(
isinstance(widget, widgetclass),
"Wrong widget for %s.%s: expected %s, got %s" % \
(model.__class__.__name__, fieldname, widgetclass, type(widget))
@ -127,8 +127,8 @@ class AdminFormfieldForDBFieldWithRequestTests(DjangoTestCase):
"""
self.client.login(username="super", password="secret")
response = self.client.get("/widget_admin/admin_widgets/cartire/add/")
self.assert_("BMW M3" not in response.content)
self.assert_("Volkswagon Passat" in response.content)
self.assertTrue("BMW M3" not in response.content)
self.assertTrue("Volkswagon Passat" in response.content)
class AdminForeignKeyWidgetChangeList(DjangoTestCase):

View File

@ -480,21 +480,21 @@ class AggregationTests(TestCase):
# age is a field on Author, so it shouldn't be allowed as an aggregate.
# But age isn't included in the ValuesQuerySet, so it is.
results = Author.objects.values('name').annotate(age=Count('book_contact_set')).order_by('name')
self.assertEquals(len(results), 9)
self.assertEquals(results[0]['name'], u'Adrian Holovaty')
self.assertEquals(results[0]['age'], 1)
self.assertEqual(len(results), 9)
self.assertEqual(results[0]['name'], u'Adrian Holovaty')
self.assertEqual(results[0]['age'], 1)
# Same problem, but aggregating over m2m fields
results = Author.objects.values('name').annotate(age=Avg('friends__age')).order_by('name')
self.assertEquals(len(results), 9)
self.assertEquals(results[0]['name'], u'Adrian Holovaty')
self.assertEquals(results[0]['age'], 32.0)
self.assertEqual(len(results), 9)
self.assertEqual(results[0]['name'], u'Adrian Holovaty')
self.assertEqual(results[0]['age'], 32.0)
# Same problem, but colliding with an m2m field
results = Author.objects.values('name').annotate(friends=Count('friends')).order_by('name')
self.assertEquals(len(results), 9)
self.assertEquals(results[0]['name'], u'Adrian Holovaty')
self.assertEquals(results[0]['friends'], 2)
self.assertEqual(len(results), 9)
self.assertEqual(results[0]['name'], u'Adrian Holovaty')
self.assertEqual(results[0]['friends'], 2)
def test_reverse_relation_name_conflict(self):
# Regression for #11256 - providing an aggregate name that conflicts with a reverse-related name on the model raises ValueError

View File

@ -16,7 +16,7 @@ class InstalledAppsGlobbingTest(TestCase):
def test_globbing(self):
settings = Settings('test_settings')
self.assertEquals(settings.INSTALLED_APPS, ['parent.app', 'parent.app1', 'parent.app_2'])
self.assertEqual(settings.INSTALLED_APPS, ['parent.app', 'parent.app1', 'parent.app_2'])
def tearDown(self):
sys.path = self.OLD_SYS_PATH

View File

@ -41,7 +41,7 @@ class WSGIFileWrapperTests(TestCase):
err = StringIO()
handler = FileWrapperHandler(None, StringIO(), err, env)
handler.run(wsgi_app_file_wrapper)
self.assert_(handler._used_sendfile)
self.assertTrue(handler._used_sendfile)
def test_file_wrapper_no_sendfile(self):
env = {'SERVER_PROTOCOL': 'HTTP/1.0'}

View File

@ -767,8 +767,8 @@ class LocMemCacheTests(unittest.TestCase, BaseCacheTests):
other_cache = get_cache('django.core.cache.backends.locmem.LocMemCache', LOCATION='other')
self.cache.set('value1', 42)
self.assertEquals(mirror_cache.get('value1'), 42)
self.assertEquals(other_cache.get('value1'), None)
self.assertEqual(mirror_cache.get('value1'), 42)
self.assertEqual(other_cache.get('value1'), None)
# memcached backend isn't guaranteed to be available.
# To check the memcached backend, the test settings file will
@ -824,7 +824,7 @@ class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
key = self.cache.make_key("foo")
keyhash = md5_constructor(key).hexdigest()
keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
self.assert_(os.path.exists(keypath))
self.assertTrue(os.path.exists(keypath))
def test_subdirectory_removal(self):
"""
@ -834,12 +834,12 @@ class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
key = self.cache.make_key("foo")
keyhash = md5_constructor(key).hexdigest()
keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
self.assert_(os.path.exists(keypath))
self.assertTrue(os.path.exists(keypath))
self.cache.delete("foo")
self.assert_(not os.path.exists(keypath))
self.assert_(not os.path.exists(os.path.dirname(keypath)))
self.assert_(not os.path.exists(os.path.dirname(os.path.dirname(keypath))))
self.assertTrue(not os.path.exists(keypath))
self.assertTrue(not os.path.exists(os.path.dirname(keypath)))
self.assertTrue(not os.path.exists(os.path.dirname(os.path.dirname(keypath))))
def test_cull(self):
self.perform_cull_test(50, 29)
@ -1208,27 +1208,27 @@ class CacheMiddlewareTest(unittest.TestCase):
middleware = CacheMiddleware()
# Now test object attributes against values defined in setUp above
self.assertEquals(middleware.cache_timeout, 30)
self.assertEquals(middleware.key_prefix, 'middlewareprefix')
self.assertEquals(middleware.cache_alias, 'other')
self.assertEquals(middleware.cache_anonymous_only, False)
self.assertEqual(middleware.cache_timeout, 30)
self.assertEqual(middleware.key_prefix, 'middlewareprefix')
self.assertEqual(middleware.cache_alias, 'other')
self.assertEqual(middleware.cache_anonymous_only, False)
# If arguments are being passed in construction, it's being used as a decorator.
# First, test with "defaults":
as_view_decorator = CacheMiddleware(cache_alias=None, key_prefix=None)
self.assertEquals(as_view_decorator.cache_timeout, 300) # Timeout value for 'default' cache, i.e. 300
self.assertEquals(as_view_decorator.key_prefix, '')
self.assertEquals(as_view_decorator.cache_alias, 'default') # Value of DEFAULT_CACHE_ALIAS from django.core.cache
self.assertEquals(as_view_decorator.cache_anonymous_only, False)
self.assertEqual(as_view_decorator.cache_timeout, 300) # Timeout value for 'default' cache, i.e. 300
self.assertEqual(as_view_decorator.key_prefix, '')
self.assertEqual(as_view_decorator.cache_alias, 'default') # Value of DEFAULT_CACHE_ALIAS from django.core.cache
self.assertEqual(as_view_decorator.cache_anonymous_only, False)
# Next, test with custom values:
as_view_decorator_with_custom = CacheMiddleware(cache_anonymous_only=True, cache_timeout=60, cache_alias='other', key_prefix='foo')
self.assertEquals(as_view_decorator_with_custom.cache_timeout, 60)
self.assertEquals(as_view_decorator_with_custom.key_prefix, 'foo')
self.assertEquals(as_view_decorator_with_custom.cache_alias, 'other')
self.assertEquals(as_view_decorator_with_custom.cache_anonymous_only, True)
self.assertEqual(as_view_decorator_with_custom.cache_timeout, 60)
self.assertEqual(as_view_decorator_with_custom.key_prefix, 'foo')
self.assertEqual(as_view_decorator_with_custom.cache_alias, 'other')
self.assertEqual(as_view_decorator_with_custom.cache_anonymous_only, True)
def test_middleware(self):
middleware = CacheMiddleware()
@ -1239,7 +1239,7 @@ class CacheMiddlewareTest(unittest.TestCase):
# Put the request through the request middleware
result = middleware.process_request(request)
self.assertEquals(result, None)
self.assertEqual(result, None)
response = hello_world_view(request, '1')
@ -1249,16 +1249,16 @@ class CacheMiddlewareTest(unittest.TestCase):
# Repeating the request should result in a cache hit
result = middleware.process_request(request)
self.assertNotEquals(result, None)
self.assertEquals(result.content, 'Hello World 1')
self.assertEqual(result.content, 'Hello World 1')
# The same request through a different middleware won't hit
result = prefix_middleware.process_request(request)
self.assertEquals(result, None)
self.assertEqual(result, None)
# The same request with a timeout _will_ hit
result = timeout_middleware.process_request(request)
self.assertNotEquals(result, None)
self.assertEquals(result.content, 'Hello World 1')
self.assertEqual(result.content, 'Hello World 1')
def test_cache_middleware_anonymous_only_wont_cause_session_access(self):
""" The cache middleware shouldn't cause a session access due to
@ -1279,7 +1279,7 @@ class CacheMiddlewareTest(unittest.TestCase):
session_middleware.process_request(request)
auth_middleware.process_request(request)
result = middleware.process_request(request)
self.assertEquals(result, None)
self.assertEqual(result, None)
response = hello_world_view(request, '1')
@ -1327,43 +1327,43 @@ class CacheMiddlewareTest(unittest.TestCase):
# Request the view once
response = default_view(request, '1')
self.assertEquals(response.content, 'Hello World 1')
self.assertEqual(response.content, 'Hello World 1')
# Request again -- hit the cache
response = default_view(request, '2')
self.assertEquals(response.content, 'Hello World 1')
self.assertEqual(response.content, 'Hello World 1')
# Requesting the same view with the explicit cache should yield the same result
response = explicit_default_view(request, '3')
self.assertEquals(response.content, 'Hello World 1')
self.assertEqual(response.content, 'Hello World 1')
# Requesting with a prefix will hit a different cache key
response = explicit_default_with_prefix_view(request, '4')
self.assertEquals(response.content, 'Hello World 4')
self.assertEqual(response.content, 'Hello World 4')
# Hitting the same view again gives a cache hit
response = explicit_default_with_prefix_view(request, '5')
self.assertEquals(response.content, 'Hello World 4')
self.assertEqual(response.content, 'Hello World 4')
# And going back to the implicit cache will hit the same cache
response = default_with_prefix_view(request, '6')
self.assertEquals(response.content, 'Hello World 4')
self.assertEqual(response.content, 'Hello World 4')
# Requesting from an alternate cache won't hit cache
response = other_view(request, '7')
self.assertEquals(response.content, 'Hello World 7')
self.assertEqual(response.content, 'Hello World 7')
# But a repeated hit will hit cache
response = other_view(request, '8')
self.assertEquals(response.content, 'Hello World 7')
self.assertEqual(response.content, 'Hello World 7')
# And prefixing the alternate cache yields yet another cache entry
response = other_with_prefix_view(request, '9')
self.assertEquals(response.content, 'Hello World 9')
self.assertEqual(response.content, 'Hello World 9')
# Request from the alternate cache with a new prefix and a custom timeout
response = other_with_timeout_view(request, '10')
self.assertEquals(response.content, 'Hello World 10')
self.assertEqual(response.content, 'Hello World 10')
# But if we wait a couple of seconds...
time.sleep(2)
@ -1371,38 +1371,38 @@ class CacheMiddlewareTest(unittest.TestCase):
# ... the default cache will still hit
cache = get_cache('default')
response = default_view(request, '11')
self.assertEquals(response.content, 'Hello World 1')
self.assertEqual(response.content, 'Hello World 1')
# ... the default cache with a prefix will still hit
response = default_with_prefix_view(request, '12')
self.assertEquals(response.content, 'Hello World 4')
self.assertEqual(response.content, 'Hello World 4')
# ... the explicit default cache will still hit
response = explicit_default_view(request, '13')
self.assertEquals(response.content, 'Hello World 1')
self.assertEqual(response.content, 'Hello World 1')
# ... the explicit default cache with a prefix will still hit
response = explicit_default_with_prefix_view(request, '14')
self.assertEquals(response.content, 'Hello World 4')
self.assertEqual(response.content, 'Hello World 4')
# .. but a rapidly expiring cache won't hit
response = other_view(request, '15')
self.assertEquals(response.content, 'Hello World 15')
self.assertEqual(response.content, 'Hello World 15')
# .. even if it has a prefix
response = other_with_prefix_view(request, '16')
self.assertEquals(response.content, 'Hello World 16')
self.assertEqual(response.content, 'Hello World 16')
# ... but a view with a custom timeout will still hit
response = other_with_timeout_view(request, '17')
self.assertEquals(response.content, 'Hello World 10')
self.assertEqual(response.content, 'Hello World 10')
# And if we wait a few more seconds
time.sleep(2)
# the custom timeouot cache will miss
response = other_with_timeout_view(request, '18')
self.assertEquals(response.content, 'Hello World 18')
self.assertEqual(response.content, 'Hello World 18')
if __name__ == '__main__':
unittest.main()

View File

@ -20,7 +20,7 @@ class CommentFormTests(CommentTestCase):
def testValidPost(self):
a = Article.objects.get(pk=1)
f = CommentForm(a, data=self.getValidData(a))
self.assert_(f.is_valid(), f.errors)
self.assertTrue(f.is_valid(), f.errors)
return f
def tamperWithForm(self, **kwargs):
@ -65,12 +65,12 @@ class CommentFormTests(CommentTestCase):
def testSecurityErrors(self):
f = self.tamperWithForm(honeypot="I am a robot")
self.assert_("honeypot" in f.security_errors())
self.assertTrue("honeypot" in f.security_errors())
def testGetCommentObject(self):
f = self.testValidPost()
c = f.get_comment_object()
self.assert_(isinstance(c, Comment))
self.assertTrue(isinstance(c, Comment))
self.assertEqual(c.content_object, Article.objects.get(pk=1))
self.assertEqual(c.comment, "This is my comment")
c.save()

View File

@ -65,29 +65,29 @@ class CommentUtilsModeratorTests(CommentTestCase):
def testEmailNotification(self):
moderator.register(Entry, EntryModerator1)
self.createSomeComments()
self.assertEquals(len(mail.outbox), 2)
self.assertEqual(len(mail.outbox), 2)
def testCommentsEnabled(self):
moderator.register(Entry, EntryModerator2)
self.createSomeComments()
self.assertEquals(Comment.objects.all().count(), 1)
self.assertEqual(Comment.objects.all().count(), 1)
def testAutoCloseField(self):
moderator.register(Entry, EntryModerator3)
self.createSomeComments()
self.assertEquals(Comment.objects.all().count(), 0)
self.assertEqual(Comment.objects.all().count(), 0)
def testAutoModerateField(self):
moderator.register(Entry, EntryModerator4)
c1, c2 = self.createSomeComments()
self.assertEquals(c2.is_public, False)
self.assertEqual(c2.is_public, False)
def testAutoModerateFieldImmediate(self):
moderator.register(Entry, EntryModerator5)
c1, c2 = self.createSomeComments()
self.assertEquals(c2.is_public, False)
self.assertEqual(c2.is_public, False)
def testAutoCloseFieldImmediate(self):
moderator.register(Entry, EntryModerator6)
c1, c2 = self.createSomeComments()
self.assertEquals(Comment.objects.all().count(), 0)
self.assertEqual(Comment.objects.all().count(), 0)

View File

@ -155,7 +155,7 @@ class CommentViewTests(CommentTestCase):
# callback
def receive(sender, **kwargs):
self.assertEqual(kwargs['comment'].comment, "This is my comment")
self.assert_('request' in kwargs)
self.assertTrue('request' in kwargs)
received_signals.append(kwargs.get('signal'))
# Connect signals and keep track of handled ones
@ -269,7 +269,7 @@ class CommentViewTests(CommentTestCase):
response = self.client.post("/post/", data)
location = response["Location"]
match = re.search(r"^http://testserver/somewhere/else/\?foo=bar&c=\d+#baz$", location)
self.failUnless(match != None, "Unexpected redirect location: %s" % location)
self.assertTrue(match != None, "Unexpected redirect location: %s" % location)
# Without a query string
a = Article.objects.get(pk=1)
@ -279,4 +279,4 @@ class CommentViewTests(CommentTestCase):
response = self.client.post("/post/", data)
location = response["Location"]
match = re.search(r"^http://testserver/somewhere/else/\?c=\d+#baz$", location)
self.failUnless(match != None, "Unexpected redirect location: %s" % location)
self.assertTrue(match != None, "Unexpected redirect location: %s" % location)

View File

@ -11,8 +11,8 @@ class CommentFeedTests(CommentTestCase):
def test_feed(self):
response = self.client.get(self.feed_url)
self.assertEquals(response.status_code, 200)
self.assertEquals(response['Content-Type'], 'application/rss+xml')
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/rss+xml')
self.assertContains(response, '<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">')
self.assertContains(response, '<title>example.com comments</title>')
self.assertContains(response, '<link>http://example.com/</link>')

View File

@ -182,14 +182,14 @@ class AdminActionsTests(CommentTestCase):
comments = self.createSomeComments()
self.client.login(username="normaluser", password="normaluser")
response = self.client.get("/admin/comments/comment/")
self.assertEquals("approve_comments" in response.content, False)
self.assertEqual("approve_comments" in response.content, False)
def testActionsModerator(self):
comments = self.createSomeComments()
makeModerator("normaluser")
self.client.login(username="normaluser", password="normaluser")
response = self.client.get("/admin/comments/comment/")
self.assertEquals("approve_comments" in response.content, True)
self.assertEqual("approve_comments" in response.content, True)
def testActionsDisabledDelete(self):
"Tests a CommentAdmin where 'delete_selected' has been disabled."
@ -197,7 +197,7 @@ class AdminActionsTests(CommentTestCase):
self.client.login(username="normaluser", password="normaluser")
response = self.client.get('/admin2/comments/comment/')
self.assertEqual(response.status_code, 200)
self.assert_(
self.assertTrue(
'<option value="delete_selected">' not in response.content,
"Found an unexpected delete_selected in response"
)

View File

@ -20,7 +20,7 @@ class CommentTemplateTagTests(CommentTestCase):
t = "{% load comments %}" + (tag or "{% get_comment_form for comment_tests.article a.id as form %}")
ctx, out = self.render(t, a=Article.objects.get(pk=1))
self.assertEqual(out, "")
self.assert_(isinstance(ctx["form"], CommentForm))
self.assertTrue(isinstance(ctx["form"], CommentForm))
def testGetCommentFormFromLiteral(self):
self.testGetCommentForm("{% get_comment_form for comment_tests.article 1 as form %}")
@ -31,8 +31,8 @@ class CommentTemplateTagTests(CommentTestCase):
def testRenderCommentForm(self, tag=None):
t = "{% load comments %}" + (tag or "{% render_comment_form for comment_tests.article a.id %}")
ctx, out = self.render(t, a=Article.objects.get(pk=1))
self.assert_(out.strip().startswith("<form action="))
self.assert_(out.strip().endswith("</form>"))
self.assertTrue(out.strip().startswith("<form action="))
self.assertTrue(out.strip().endswith("</form>"))
def testRenderCommentFormFromLiteral(self):
self.testRenderCommentForm("{% render_comment_form for comment_tests.article 1 %}")
@ -86,8 +86,8 @@ class CommentTemplateTagTests(CommentTestCase):
def testRenderCommentList(self, tag=None):
t = "{% load comments %}" + (tag or "{% render_comment_list for comment_tests.article a.id %}")
ctx, out = self.render(t, a=Article.objects.get(pk=1))
self.assert_(out.strip().startswith("<dl id=\"comments\">"))
self.assert_(out.strip().endswith("</dl>"))
self.assertTrue(out.strip().startswith("<dl id=\"comments\">"))
self.assertTrue(out.strip().endswith("</dl>"))
def testRenderCommentListFromLiteral(self):
self.testRenderCommentList("{% render_comment_list for comment_tests.article 1 %}")

View File

@ -17,16 +17,16 @@ EXPIRED_ETAG = '7fae4cd4b0f81e7d2914700043aa8ed6'
class ConditionalGet(TestCase):
def assertFullResponse(self, response, check_last_modified=True, check_etag=True):
self.assertEquals(response.status_code, 200)
self.assertEquals(response.content, FULL_RESPONSE)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, FULL_RESPONSE)
if check_last_modified:
self.assertEquals(response['Last-Modified'], LAST_MODIFIED_STR)
self.assertEqual(response['Last-Modified'], LAST_MODIFIED_STR)
if check_etag:
self.assertEquals(response['ETag'], '"%s"' % ETAG)
self.assertEqual(response['ETag'], '"%s"' % ETAG)
def assertNotModified(self, response):
self.assertEquals(response.status_code, 304)
self.assertEquals(response.content, '')
self.assertEqual(response.status_code, 304)
self.assertEqual(response.content, '')
def testWithoutConditions(self):
response = self.client.get('/condition/')
@ -62,10 +62,10 @@ class ConditionalGet(TestCase):
def testIfMatch(self):
self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % ETAG
response = self.client.put('/condition/etag/', {'data': ''})
self.assertEquals(response.status_code, 200)
self.assertEqual(response.status_code, 200)
self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % EXPIRED_ETAG
response = self.client.put('/condition/etag/', {'data': ''})
self.assertEquals(response.status_code, 412)
self.assertEqual(response.status_code, 412)
def testBothHeaders(self):
self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR
@ -130,11 +130,11 @@ class ConditionalGet(TestCase):
class ETagProcessing(unittest.TestCase):
def testParsing(self):
etags = parse_etags(r'"", "etag", "e\"t\"ag", "e\\tag", W/"weak"')
self.assertEquals(etags, ['', 'etag', 'e"t"ag', r'e\tag', 'weak'])
self.assertEqual(etags, ['', 'etag', 'e"t"ag', r'e\tag', 'weak'])
def testQuoting(self):
quoted_etag = quote_etag(r'e\t"ag')
self.assertEquals(quoted_etag, r'"e\\t\"ag"')
self.assertEqual(quoted_etag, r'"e\\t\"ag"')
class HttpDateProcessing(unittest.TestCase):

View File

@ -133,7 +133,7 @@ class CsrfMiddlewareTest(TestCase):
self.assertNotEqual(resp_content, resp2.content)
self._check_token_present(resp2, csrf_cookie.value)
# Check the Vary header got patched correctly
self.assert_('Cookie' in resp2.get('Vary',''))
self.assertTrue('Cookie' in resp2.get('Vary',''))
def test_process_response_for_exempt_view(self):
"""
@ -210,7 +210,7 @@ class CsrfMiddlewareTest(TestCase):
resp = post_form_response_non_html()
resp_content = resp.content # needed because process_response modifies resp
resp2 = CsrfMiddleware().process_response(req, resp)
self.assertEquals(resp_content, resp2.content)
self.assertEqual(resp_content, resp2.content)
def test_process_response_exempt_view(self):
"""
@ -223,7 +223,7 @@ class CsrfMiddlewareTest(TestCase):
resp = view(req)
resp_content = resp.content
resp2 = CsrfMiddleware().process_response(req, resp)
self.assertEquals(resp_content, resp2.content)
self.assertEqual(resp_content, resp2.content)
# Check the request processing
def test_process_request_no_session_no_csrf_cookie(self):
@ -233,7 +233,7 @@ class CsrfMiddlewareTest(TestCase):
"""
req = self._get_POST_no_csrf_cookie_request()
req2 = CsrfMiddleware().process_view(req, post_form_view, (), {})
self.assertEquals(403, req2.status_code)
self.assertEqual(403, req2.status_code)
def test_process_request_csrf_cookie_no_token(self):
"""
@ -242,7 +242,7 @@ class CsrfMiddlewareTest(TestCase):
"""
req = self._get_POST_csrf_cookie_request()
req2 = CsrfMiddleware().process_view(req, post_form_view, (), {})
self.assertEquals(403, req2.status_code)
self.assertEqual(403, req2.status_code)
def test_process_request_csrf_cookie_and_token(self):
"""
@ -250,7 +250,7 @@ class CsrfMiddlewareTest(TestCase):
"""
req = self._get_POST_request_with_token()
req2 = CsrfMiddleware().process_view(req, post_form_view, (), {})
self.assertEquals(None, req2)
self.assertEqual(None, req2)
def test_process_request_session_cookie_no_csrf_cookie_token(self):
"""
@ -262,7 +262,7 @@ class CsrfMiddlewareTest(TestCase):
try:
req = self._get_POST_session_request_with_token()
req2 = CsrfMiddleware().process_view(req, post_form_view, (), {})
self.assertEquals(None, req2)
self.assertEqual(None, req2)
finally:
settings.SECRET_KEY = orig_secret_key
@ -273,7 +273,7 @@ class CsrfMiddlewareTest(TestCase):
"""
req = self._get_POST_session_request_no_token()
req2 = CsrfMiddleware().process_view(req, post_form_view, (), {})
self.assertEquals(403, req2.status_code)
self.assertEqual(403, req2.status_code)
def test_process_request_csrf_cookie_no_token_exempt_view(self):
"""
@ -282,7 +282,7 @@ class CsrfMiddlewareTest(TestCase):
"""
req = self._get_POST_csrf_cookie_request()
req2 = CsrfMiddleware().process_view(req, csrf_exempt(post_form_view), (), {})
self.assertEquals(None, req2)
self.assertEqual(None, req2)
def test_csrf_token_in_header(self):
"""
@ -291,7 +291,7 @@ class CsrfMiddlewareTest(TestCase):
req = self._get_POST_csrf_cookie_request()
req.META['HTTP_X_CSRFTOKEN'] = self._csrf_id
req2 = CsrfMiddleware().process_view(req, post_form_view, (), {})
self.assertEquals(None, req2)
self.assertEqual(None, req2)
# Tests for the template tag method
def test_token_node_no_csrf_cookie(self):
@ -300,7 +300,7 @@ class CsrfMiddlewareTest(TestCase):
"""
req = self._get_GET_no_csrf_cookie_request()
resp = token_view(req)
self.assertEquals(u"", resp.content)
self.assertEqual(u"", resp.content)
def test_token_node_empty_csrf_cookie(self):
"""
@ -370,7 +370,7 @@ class CsrfMiddlewareTest(TestCase):
req.META['HTTP_REFERER'] = 'https://www.evil.org/somepage'
req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
self.assertNotEqual(None, req2)
self.assertEquals(403, req2.status_code)
self.assertEqual(403, req2.status_code)
def test_https_good_referer(self):
"""
@ -381,4 +381,4 @@ class CsrfMiddlewareTest(TestCase):
req.META['HTTP_HOST'] = 'www.example.com'
req.META['HTTP_REFERER'] = 'https://www.example.com/somepage'
req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
self.assertEquals(None, req2)
self.assertEqual(None, req2)

View File

@ -72,7 +72,7 @@ class DataTypesTestCase(TestCase):
database should be unicode."""
d = Donut.objects.create(name=u'Jelly Donut', review=u'Outstanding')
newd = Donut.objects.get(id=d.id)
self.assert_(isinstance(newd.review, unicode))
self.assertTrue(isinstance(newd.review, unicode))
@skipIfDBFeature('supports_timezones')
def test_error_on_timezone(self):
@ -88,7 +88,7 @@ class DataTypesTestCase(TestCase):
a Python datetime.date, not a datetime.datetime"""
b = RumBaba.objects.create()
# Verify we didn't break DateTimeField behavior
self.assert_(isinstance(b.baked_timestamp, datetime.datetime))
self.assertTrue(isinstance(b.baked_timestamp, datetime.datetime))
# We need to test this this way because datetime.datetime inherits
# from datetime.date:
self.assert_(isinstance(b.baked_date, datetime.date) and not isinstance(b.baked_date, datetime.datetime))
self.assertTrue(isinstance(b.baked_date, datetime.date) and not isinstance(b.baked_date, datetime.datetime))

View File

@ -56,9 +56,9 @@ class DecoratorsTest(TestCase):
Tests that django decorators set certain attributes of the wrapped
function.
"""
self.assertEquals(fully_decorated.__name__, 'fully_decorated')
self.assertEquals(fully_decorated.__doc__, 'Expected __doc__')
self.assertEquals(fully_decorated.__dict__['anything'], 'Expected __dict__')
self.assertEqual(fully_decorated.__name__, 'fully_decorated')
self.assertEqual(fully_decorated.__doc__, 'Expected __doc__')
self.assertEqual(fully_decorated.__dict__['anything'], 'Expected __dict__')
def test_user_passes_test_composition(self):
"""

View File

@ -76,11 +76,11 @@ class DeleteCascadeTests(TestCase):
award = Award.objects.create(name='Nobel', content_object=person)
note = AwardNote.objects.create(note='a peace prize',
award=award)
self.assertEquals(AwardNote.objects.count(), 1)
self.assertEqual(AwardNote.objects.count(), 1)
person.delete()
self.assertEquals(Award.objects.count(), 0)
self.assertEqual(Award.objects.count(), 0)
# first two asserts are just sanity checks, this is the kicker:
self.assertEquals(AwardNote.objects.count(), 0)
self.assertEqual(AwardNote.objects.count(), 0)
def test_fk_to_m2m_through(self):
"""
@ -96,11 +96,11 @@ class DeleteCascadeTests(TestCase):
date=datetime.date.today())
note = PlayedWithNote.objects.create(played=played,
note='the next Jackson Pollock')
self.assertEquals(PlayedWithNote.objects.count(), 1)
self.assertEqual(PlayedWithNote.objects.count(), 1)
paints.delete()
self.assertEquals(PlayedWith.objects.count(), 0)
self.assertEqual(PlayedWith.objects.count(), 0)
# first two asserts just sanity checks, this is the kicker:
self.assertEquals(PlayedWithNote.objects.count(), 0)
self.assertEqual(PlayedWithNote.objects.count(), 0)
class DeleteCascadeTransactionTests(TransactionTestCase):
@ -136,4 +136,4 @@ class LargeDeleteTests(TestCase):
for x in range(300):
track = Book.objects.create(pagecount=x+100)
Book.objects.all().delete()
self.assertEquals(Book.objects.count(), 0)
self.assertEqual(Book.objects.count(), 0)

View File

@ -99,7 +99,7 @@ class DispatcherTests(unittest.TestCase):
a_signal.connect(fails)
result = a_signal.send_robust(sender=self, val="test")
err = result[0][1]
self.assert_(isinstance(err, ValueError))
self.assertTrue(isinstance(err, ValueError))
self.assertEqual(err.args, ('this',))
a_signal.disconnect(fails)
self._testIsClean(a_signal)

View File

@ -40,12 +40,12 @@ class Tester(unittest.TestCase):
def testIn(self):
"""Test the "in" operator for safe references (cmp)"""
for t in self.ts[:50]:
self.assert_(safeRef(t.x) in self.ss)
self.assertTrue(safeRef(t.x) in self.ss)
def testValid(self):
"""Test that the references are valid (return instance methods)"""
for s in self.ss:
self.assert_(s())
self.assertTrue(s())
def testShortCircuit (self):
"""Test that creation short-circuits to reuse existing references"""
@ -54,11 +54,11 @@ class Tester(unittest.TestCase):
sd[s] = 1
for t in self.ts:
if hasattr(t, 'x'):
self.assert_(sd.has_key(safeRef(t.x)))
self.assert_(safeRef(t.x) in sd)
self.assertTrue(sd.has_key(safeRef(t.x)))
self.assertTrue(safeRef(t.x) in sd)
else:
self.assert_(sd.has_key(safeRef(t)))
self.assert_(safeRef(t) in sd)
self.assertTrue(sd.has_key(safeRef(t)))
self.assertTrue(safeRef(t) in sd)
def testRepresentation (self):
"""Test that the reference object's representation works

View File

@ -106,7 +106,7 @@ class FileStorageTests(unittest.TestCase):
f = self.storage.open('storage_test', 'w')
f.write('storage contents')
f.close()
self.assert_(self.storage.exists('storage_test'))
self.assertTrue(self.storage.exists('storage_test'))
f = self.storage.open('storage_test', 'r')
self.assertEqual(f.read(), 'storage contents')
@ -179,7 +179,7 @@ class FileStorageTests(unittest.TestCase):
self.assertEqual(storage_f_name, f.name)
self.assert_(os.path.exists(os.path.join(self.temp_dir, f.name)))
self.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name)))
self.storage.delete(storage_f_name)
@ -229,7 +229,7 @@ class FileStorageTests(unittest.TestCase):
f = ContentFile('custom contents')
f_name = self.storage.save('test.file', f)
self.assert_(isinstance(
self.assertTrue(isinstance(
self.storage.open('test.file', mixin=TestFileMixin),
TestFileMixin
))
@ -325,8 +325,8 @@ class FileSaveRaceConditionTest(unittest.TestCase):
self.thread.start()
name = self.save_file('conflict')
self.thread.join()
self.assert_(self.storage.exists('conflict'))
self.assert_(self.storage.exists('conflict_1'))
self.assertTrue(self.storage.exists('conflict'))
self.assertTrue(self.storage.exists('conflict_1'))
self.storage.delete('conflict')
self.storage.delete('conflict_1')
@ -366,8 +366,8 @@ class FileStoragePathParsing(unittest.TestCase):
self.storage.save('dotted.path/test', ContentFile("2"))
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_1')))
self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test')))
self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_1')))
def test_first_character_dot(self):
"""
@ -377,13 +377,13 @@ class FileStoragePathParsing(unittest.TestCase):
self.storage.save('dotted.path/.test', ContentFile("1"))
self.storage.save('dotted.path/.test', ContentFile("2"))
self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test')))
self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test')))
# Before 2.6, a leading dot was treated as an extension, and so
# underscore gets added to beginning instead of end.
if sys.version_info < (2, 6):
self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_1.test')))
self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_1.test')))
else:
self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1')))
self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1')))
class DimensionClosingBug(unittest.TestCase):
"""
@ -398,7 +398,7 @@ class DimensionClosingBug(unittest.TestCase):
try:
get_image_dimensions(empty_io)
finally:
self.assert_(not empty_io.closed)
self.assertTrue(not empty_io.closed)
@unittest.skipUnless(Image, "PIL not installed")
def test_closing_of_filenames(self):
@ -430,7 +430,7 @@ class DimensionClosingBug(unittest.TestCase):
get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png"))
finally:
del images.open
self.assert_(FileWrapper._closed)
self.assertTrue(FileWrapper._closed)
class InconsistentGetImageDimensionsBug(unittest.TestCase):
"""

View File

@ -148,7 +148,7 @@ class FileUploadTests(TestCase):
'wsgi.input': client.FakePayload(payload),
}
got = simplejson.loads(self.client.request(**r).content)
self.assert_(len(got['file']) < 256, "Got a long file name (%s characters)." % len(got['file']))
self.assertTrue(len(got['file']) < 256, "Got a long file name (%s characters)." % len(got['file']))
def test_custom_upload_handler(self):
# A small file (under the 5M quota)
@ -164,12 +164,12 @@ class FileUploadTests(TestCase):
# Small file posting should work.
response = self.client.post('/file_uploads/quota/', {'f': smallfile})
got = simplejson.loads(response.content)
self.assert_('f' in got)
self.assertTrue('f' in got)
# Large files don't go through.
response = self.client.post("/file_uploads/quota/", {'f': bigfile})
got = simplejson.loads(response.content)
self.assert_('f' not in got)
self.assertTrue('f' not in got)
def test_broken_custom_upload_handler(self):
f = tempfile.NamedTemporaryFile()
@ -275,7 +275,7 @@ class DirectoryCreationTests(unittest.TestCase):
try:
self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
except OSError, err:
self.assertEquals(err.errno, errno.EACCES)
self.assertEqual(err.errno, errno.EACCES)
except Exception, err:
self.fail("OSError [Errno %s] not raised." % errno.EACCES)
@ -289,7 +289,7 @@ class DirectoryCreationTests(unittest.TestCase):
except IOError, err:
# The test needs to be done on a specific string as IOError
# is raised even without the patch (just not early enough)
self.assertEquals(err.args[0],
self.assertEqual(err.args[0],
"%s exists and is not a directory." % UPLOAD_TO)
except:
self.fail("IOError not raised")

View File

@ -351,7 +351,7 @@ class FILocalFlavorTests(LocalFlavorTestCase):
<option value="ahtari">\xc4ht\xe4ri</option>
<option value="aanekoski">\xc4\xe4nekoski</option>
</select>'''
self.assertEquals(f.render('municipalities', 'turku'), out)
self.assertEqual(f.render('municipalities', 'turku'), out)
def test_FIZipCodeField(self):
error_format = [u'Enter a zip code in the format XXXXX.']

View File

@ -68,7 +68,7 @@ class USLocalFlavorTests(LocalFlavorTestCase):
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>'''
self.assertEquals(f.render('state', 'IL'), out)
self.assertEqual(f.render('state', 'IL'), out)
def test_USZipCodeField(self):
error_format = [u'Enter a zip code in the format XXXXX or XXXXX-XXXX.']

View File

@ -856,13 +856,13 @@ class TestIsBoundBehavior(TestCase):
'form-INITIAL_FORMS': u'0',
}
formset = ArticleFormSet(data)
self.assertEquals(0, formset.initial_form_count())
self.assertEquals(1, formset.total_form_count())
self.assertEqual(0, formset.initial_form_count())
self.assertEqual(1, formset.total_form_count())
self.assertTrue(formset.is_bound)
self.assertTrue(formset.forms[0].is_bound)
self.assertTrue(formset.is_valid())
self.assertTrue(formset.forms[0].is_valid())
self.assertEquals([{}], formset.cleaned_data)
self.assertEqual([{}], formset.cleaned_data)
def test_form_errors_are_cought_by_formset(self):
@ -876,7 +876,7 @@ class TestIsBoundBehavior(TestCase):
}
formset = ArticleFormSet(data)
self.assertFalse(formset.is_valid())
self.assertEquals([{}, {'pub_date': [u'This field is required.']}], formset.errors)
self.assertEqual([{}, {'pub_date': [u'This field is required.']}], formset.errors)
def test_empty_forms_are_unbound(self):
data = {

View File

@ -33,15 +33,15 @@ class ModelFormCallableModelDefault(TestCase):
option = ChoiceOptionModel.objects.create(name='default')
choices = list(ChoiceFieldForm().fields['choice'].choices)
self.assertEquals(len(choices), 1)
self.assertEquals(choices[0], (option.pk, unicode(option)))
self.assertEqual(len(choices), 1)
self.assertEqual(choices[0], (option.pk, unicode(option)))
def test_callable_initial_value(self):
"The initial value for a callable default returning a queryset is the pk (refs #13769)"
obj1 = ChoiceOptionModel.objects.create(id=1, name='default')
obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2')
obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3')
self.assertEquals(ChoiceFieldForm().as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
self.assertEqual(ChoiceFieldForm().as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
<option value="1" selected="selected">ChoiceOption 1</option>
<option value="2">ChoiceOption 2</option>
<option value="3">ChoiceOption 3</option>
@ -67,7 +67,7 @@ class ModelFormCallableModelDefault(TestCase):
obj1 = ChoiceOptionModel.objects.create(id=1, name='default')
obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2')
obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3')
self.assertEquals(ChoiceFieldForm(initial={
self.assertEqual(ChoiceFieldForm(initial={
'choice': obj2,
'choice_int': obj2,
'multi_choice': [obj2,obj3],

View File

@ -92,24 +92,24 @@ class GenericAdminViewTest(TestCase):
# Works with no queryset
formset = EpisodeMediaFormSet(instance=e)
self.assertEquals(len(formset.forms), 5)
self.assertEquals(formset.forms[0].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-0-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-0-url" type="text" name="generic_inline_admin-media-content_type-object_id-0-url" value="http://example.com/podcast.mp3" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-0-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-0-id" /></p>' % self.mp3_media_pk)
self.assertEquals(formset.forms[1].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-1-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-1-url" type="text" name="generic_inline_admin-media-content_type-object_id-1-url" value="http://example.com/logo.png" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-1-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-1-id" /></p>' % self.png_media_pk)
self.assertEquals(formset.forms[2].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-2-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-2-url" type="text" name="generic_inline_admin-media-content_type-object_id-2-url" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-2-id" id="id_generic_inline_admin-media-content_type-object_id-2-id" /></p>')
self.assertEqual(len(formset.forms), 5)
self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-0-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-0-url" type="text" name="generic_inline_admin-media-content_type-object_id-0-url" value="http://example.com/podcast.mp3" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-0-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-0-id" /></p>' % self.mp3_media_pk)
self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-1-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-1-url" type="text" name="generic_inline_admin-media-content_type-object_id-1-url" value="http://example.com/logo.png" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-1-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-1-id" /></p>' % self.png_media_pk)
self.assertEqual(formset.forms[2].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-2-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-2-url" type="text" name="generic_inline_admin-media-content_type-object_id-2-url" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-2-id" id="id_generic_inline_admin-media-content_type-object_id-2-id" /></p>')
# A queryset can be used to alter display ordering
formset = EpisodeMediaFormSet(instance=e, queryset=Media.objects.order_by('url'))
self.assertEquals(len(formset.forms), 5)
self.assertEquals(formset.forms[0].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-0-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-0-url" type="text" name="generic_inline_admin-media-content_type-object_id-0-url" value="http://example.com/logo.png" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-0-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-0-id" /></p>' % self.png_media_pk)
self.assertEquals(formset.forms[1].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-1-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-1-url" type="text" name="generic_inline_admin-media-content_type-object_id-1-url" value="http://example.com/podcast.mp3" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-1-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-1-id" /></p>' % self.mp3_media_pk)
self.assertEquals(formset.forms[2].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-2-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-2-url" type="text" name="generic_inline_admin-media-content_type-object_id-2-url" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-2-id" id="id_generic_inline_admin-media-content_type-object_id-2-id" /></p>')
self.assertEqual(len(formset.forms), 5)
self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-0-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-0-url" type="text" name="generic_inline_admin-media-content_type-object_id-0-url" value="http://example.com/logo.png" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-0-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-0-id" /></p>' % self.png_media_pk)
self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-1-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-1-url" type="text" name="generic_inline_admin-media-content_type-object_id-1-url" value="http://example.com/podcast.mp3" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-1-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-1-id" /></p>' % self.mp3_media_pk)
self.assertEqual(formset.forms[2].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-2-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-2-url" type="text" name="generic_inline_admin-media-content_type-object_id-2-url" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-2-id" id="id_generic_inline_admin-media-content_type-object_id-2-id" /></p>')
# Works with a queryset that omits items
formset = EpisodeMediaFormSet(instance=e, queryset=Media.objects.filter(url__endswith=".png"))
self.assertEquals(len(formset.forms), 4)
self.assertEquals(formset.forms[0].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-0-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-0-url" type="text" name="generic_inline_admin-media-content_type-object_id-0-url" value="http://example.com/logo.png" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-0-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-0-id" /></p>' % self.png_media_pk)
self.assertEquals(formset.forms[1].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-1-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-1-url" type="text" name="generic_inline_admin-media-content_type-object_id-1-url" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-1-id" id="id_generic_inline_admin-media-content_type-object_id-1-id" /></p>')
self.assertEqual(len(formset.forms), 4)
self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-0-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-0-url" type="text" name="generic_inline_admin-media-content_type-object_id-0-url" value="http://example.com/logo.png" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-0-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-0-id" /></p>' % self.png_media_pk)
self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-1-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-1-url" type="text" name="generic_inline_admin-media-content_type-object_id-1-url" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-1-id" id="id_generic_inline_admin-media-content_type-object_id-1-id" /></p>')
def testGenericInlineFormsetFactory(self):
# Regression test for #10522.

View File

@ -232,32 +232,32 @@ class RedirectViewTest(unittest.TestCase):
def test_no_url(self):
"Without any configuration, returns HTTP 410 GONE"
response = RedirectView.as_view()(self.rf.get('/foo/'))
self.assertEquals(response.status_code, 410)
self.assertEqual(response.status_code, 410)
def test_permanaent_redirect(self):
"Default is a permanent redirect"
response = RedirectView.as_view(url='/bar/')(self.rf.get('/foo/'))
self.assertEquals(response.status_code, 301)
self.assertEquals(response['Location'], '/bar/')
self.assertEqual(response.status_code, 301)
self.assertEqual(response['Location'], '/bar/')
def test_temporary_redirect(self):
"Permanent redirects are an option"
response = RedirectView.as_view(url='/bar/', permanent=False)(self.rf.get('/foo/'))
self.assertEquals(response.status_code, 302)
self.assertEquals(response['Location'], '/bar/')
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], '/bar/')
def test_include_args(self):
"GET arguments can be included in the redirected URL"
response = RedirectView.as_view(url='/bar/')(self.rf.get('/foo/'))
self.assertEquals(response.status_code, 301)
self.assertEquals(response['Location'], '/bar/')
self.assertEqual(response.status_code, 301)
self.assertEqual(response['Location'], '/bar/')
response = RedirectView.as_view(url='/bar/', query_string=True)(self.rf.get('/foo/?pork=spam'))
self.assertEquals(response.status_code, 301)
self.assertEquals(response['Location'], '/bar/?pork=spam')
self.assertEqual(response.status_code, 301)
self.assertEqual(response['Location'], '/bar/?pork=spam')
def test_parameter_substitution(self):
"Redirection URLs can be parameterized"
response = RedirectView.as_view(url='/bar/%(object_id)d/')(self.rf.get('/foo/42/'), object_id=42)
self.assertEquals(response.status_code, 301)
self.assertEquals(response['Location'], '/bar/42/')
self.assertEqual(response.status_code, 301)
self.assertEqual(response['Location'], '/bar/42/')

View File

@ -253,8 +253,8 @@ class CookieTests(unittest.TestCase):
# That's not the bug this test is looking for, so ignore it.
c = SimpleCookie()
c['test'] = "An,awkward;value"
self.assert_(";" not in c.output().rstrip(';')) # IE compat
self.assert_("," not in c.output().rstrip(';')) # Safari compat
self.assertTrue(";" not in c.output().rstrip(';')) # IE compat
self.assertTrue("," not in c.output().rstrip(';')) # Safari compat
def test_decode(self):
"""

View File

@ -30,12 +30,12 @@ class ExtractorTests(TestCase):
def assertMsgId(self, msgid, s, use_quotes=True):
if use_quotes:
msgid = '"%s"' % msgid
return self.assert_(re.search('^msgid %s' % msgid, s, re.MULTILINE))
return self.assertTrue(re.search('^msgid %s' % msgid, s, re.MULTILINE))
def assertNotMsgId(self, msgid, s, use_quotes=True):
if use_quotes:
msgid = '"%s"' % msgid
return self.assert_(not re.search('^msgid %s' % msgid, s, re.MULTILINE))
return self.assertTrue(not re.search('^msgid %s' % msgid, s, re.MULTILINE))
class BasicExtractorTests(ExtractorTests):
@ -43,18 +43,18 @@ class BasicExtractorTests(ExtractorTests):
def test_comments_extractor(self):
os.chdir(self.test_dir)
management.call_command('makemessages', locale=LOCALE, verbosity=0)
self.assert_(os.path.exists(self.PO_FILE))
self.assertTrue(os.path.exists(self.PO_FILE))
po_contents = open(self.PO_FILE, 'r').read()
self.assert_('#. Translators: This comment should be extracted' in po_contents)
self.assert_('This comment should not be extracted' not in po_contents)
self.assertTrue('#. Translators: This comment should be extracted' in po_contents)
self.assertTrue('This comment should not be extracted' not in po_contents)
# Comments in templates
self.assert_('#. Translators: Django template comment for translators' in po_contents)
self.assert_('#. Translators: Django comment block for translators' in po_contents)
self.assertTrue('#. Translators: Django template comment for translators' in po_contents)
self.assertTrue('#. Translators: Django comment block for translators' in po_contents)
def test_templatize(self):
os.chdir(self.test_dir)
management.call_command('makemessages', locale=LOCALE, verbosity=0)
self.assert_(os.path.exists(self.PO_FILE))
self.assertTrue(os.path.exists(self.PO_FILE))
po_contents = open(self.PO_FILE, 'r').read()
self.assertMsgId('I think that 100%% is more that 50%% of anything.', po_contents)
self.assertMsgId('I think that 100%% is more that 50%% of %\(obj\)s.', po_contents)
@ -80,7 +80,7 @@ class JavascriptExtractorTests(ExtractorTests):
def test_javascript_literals(self):
os.chdir(self.test_dir)
management.call_command('makemessages', domain='djangojs', locale=LOCALE, verbosity=0)
self.assert_(os.path.exists(self.PO_FILE))
self.assertTrue(os.path.exists(self.PO_FILE))
po_contents = open(self.PO_FILE, 'r').read()
self.assertMsgId('This literal should be included.', po_contents)
self.assertMsgId('This one as well.', po_contents)
@ -91,7 +91,7 @@ class IgnoredExtractorTests(ExtractorTests):
def test_ignore_option(self):
os.chdir(self.test_dir)
management.call_command('makemessages', locale=LOCALE, verbosity=0, ignore_patterns=['ignore_dir/*'])
self.assert_(os.path.exists(self.PO_FILE))
self.assertTrue(os.path.exists(self.PO_FILE))
po_contents = open(self.PO_FILE, 'r').read()
self.assertMsgId('This literal should be included.', po_contents)
self.assertNotMsgId('This should be ignored.', po_contents)
@ -116,15 +116,15 @@ class SymlinkExtractorTests(ExtractorTests):
def test_symlink(self):
if hasattr(os, 'symlink'):
if os.path.exists(self.symlinked_dir):
self.assert_(os.path.islink(self.symlinked_dir))
self.assertTrue(os.path.islink(self.symlinked_dir))
else:
os.symlink(os.path.join(self.test_dir, 'templates'), self.symlinked_dir)
os.chdir(self.test_dir)
management.call_command('makemessages', locale=LOCALE, verbosity=0, symlinks=True)
self.assert_(os.path.exists(self.PO_FILE))
self.assertTrue(os.path.exists(self.PO_FILE))
po_contents = open(self.PO_FILE, 'r').read()
self.assertMsgId('This literal should be included.', po_contents)
self.assert_('templates_symlinked/test.html' in po_contents)
self.assertTrue('templates_symlinked/test.html' in po_contents)
class CopyPluralFormsExtractorTests(ExtractorTests):
@ -132,9 +132,9 @@ class CopyPluralFormsExtractorTests(ExtractorTests):
def test_copy_plural_forms(self):
os.chdir(self.test_dir)
management.call_command('makemessages', locale=LOCALE, verbosity=0)
self.assert_(os.path.exists(self.PO_FILE))
self.assertTrue(os.path.exists(self.PO_FILE))
po_contents = open(self.PO_FILE, 'r').read()
self.assert_('Plural-Forms: nplurals=2; plural=(n != 1)' in po_contents)
self.assertTrue('Plural-Forms: nplurals=2; plural=(n != 1)' in po_contents)
class NoWrapExtractorTests(ExtractorTests):
@ -142,13 +142,13 @@ class NoWrapExtractorTests(ExtractorTests):
def test_no_wrap_enabled(self):
os.chdir(self.test_dir)
management.call_command('makemessages', locale=LOCALE, verbosity=0, no_wrap=True)
self.assert_(os.path.exists(self.PO_FILE))
self.assertTrue(os.path.exists(self.PO_FILE))
po_contents = open(self.PO_FILE, 'r').read()
self.assertMsgId('This literal should also be included wrapped or not wrapped depending on the use of the --no-wrap option.', po_contents)
def test_no_wrap_disabled(self):
os.chdir(self.test_dir)
management.call_command('makemessages', locale=LOCALE, verbosity=0, no_wrap=False)
self.assert_(os.path.exists(self.PO_FILE))
self.assertTrue(os.path.exists(self.PO_FILE))
po_contents = open(self.PO_FILE, 'r').read()
self.assertMsgId('""\n"This literal should also be included wrapped or not wrapped depending on the "\n"use of the --no-wrap option."', po_contents, use_quotes=False)

View File

@ -460,7 +460,7 @@ class FormattingTests(TestCase):
self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added'])
settings.USE_THOUSAND_SEPARATOR = True
# Checking for the localized "products_delivered" field
self.assert_(u'<input type="text" name="products_delivered" value="12.000" id="id_products_delivered" />' in form6.as_ul())
self.assertTrue(u'<input type="text" name="products_delivered" value="12.000" id="id_products_delivered" />' in form6.as_ul())
finally:
deactivate()

View File

@ -38,9 +38,9 @@ class IntrospectionTests(TestCase):
def test_table_names(self):
tl = connection.introspection.table_names()
self.assert_(Reporter._meta.db_table in tl,
self.assertTrue(Reporter._meta.db_table in tl,
"'%s' isn't in table_list()." % Reporter._meta.db_table)
self.assert_(Article._meta.db_table in tl,
self.assertTrue(Article._meta.db_table in tl,
"'%s' isn't in table_list()." % Article._meta.db_table)
def test_django_table_names(self):
@ -48,7 +48,7 @@ class IntrospectionTests(TestCase):
cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);');
tl = connection.introspection.django_table_names()
cursor.execute("DROP TABLE django_ixn_test_table;")
self.assert_('django_ixn_testcase_table' not in tl,
self.assertTrue('django_ixn_testcase_table' not in tl,
"django_table_names() returned a non-Django table")
def test_installed_models(self):
@ -59,7 +59,7 @@ class IntrospectionTests(TestCase):
def test_sequence_list(self):
sequences = connection.introspection.sequence_list()
expected = {'table': Reporter._meta.db_table, 'column': 'id'}
self.assert_(expected in sequences,
self.assertTrue(expected in sequences,
'Reporter sequence not found in sequence_list()')
def test_get_table_description_names(self):

View File

@ -332,7 +332,7 @@ class BaseEmailBackendTests(object):
num_sent = mail.get_connection().send_messages([email1, email2])
self.assertEqual(num_sent, 2)
messages = self.get_mailbox_content()
self.assertEquals(len(messages), 2)
self.assertEqual(len(messages), 2)
self.assertEqual(messages[0].get_payload(), "Content1")
self.assertEqual(messages[1].get_payload(), "Content2")

View File

@ -5,7 +5,7 @@ from regressiontests.max_lengths.models import PersonWithDefaultMaxLengths, Pers
class MaxLengthArgumentsTests(unittest.TestCase):
def verify_max_length(self, model,field,length):
self.assertEquals(model._meta.get_field(field).max_length,length)
self.assertEqual(model._meta.get_field(field).max_length,length)
def test_default_max_lengths(self):
self.verify_max_length(PersonWithDefaultMaxLengths, 'email', 75)

View File

@ -31,7 +31,7 @@ class CommonMiddlewareTest(TestCase):
"""
settings.APPEND_SLASH = True
request = self._get_request('slash/')
self.assertEquals(CommonMiddleware().process_request(request), None)
self.assertEqual(CommonMiddleware().process_request(request), None)
def test_append_slash_slashless_resource(self):
"""
@ -39,7 +39,7 @@ class CommonMiddlewareTest(TestCase):
"""
settings.APPEND_SLASH = True
request = self._get_request('noslash')
self.assertEquals(CommonMiddleware().process_request(request), None)
self.assertEqual(CommonMiddleware().process_request(request), None)
def test_append_slash_slashless_unknown(self):
"""
@ -47,7 +47,7 @@ class CommonMiddlewareTest(TestCase):
"""
settings.APPEND_SLASH = True
request = self._get_request('unknown')
self.assertEquals(CommonMiddleware().process_request(request), None)
self.assertEqual(CommonMiddleware().process_request(request), None)
def test_append_slash_redirect(self):
"""
@ -56,8 +56,8 @@ class CommonMiddlewareTest(TestCase):
settings.APPEND_SLASH = True
request = self._get_request('slash')
r = CommonMiddleware().process_request(request)
self.assertEquals(r.status_code, 301)
self.assertEquals(r['Location'], 'http://testserver/middleware/slash/')
self.assertEqual(r.status_code, 301)
self.assertEqual(r['Location'], 'http://testserver/middleware/slash/')
def test_append_slash_no_redirect_on_POST_in_DEBUG(self):
"""
@ -85,7 +85,7 @@ class CommonMiddlewareTest(TestCase):
"""
settings.APPEND_SLASH = False
request = self._get_request('slash')
self.assertEquals(CommonMiddleware().process_request(request), None)
self.assertEqual(CommonMiddleware().process_request(request), None)
def test_append_slash_quoted(self):
"""
@ -95,8 +95,8 @@ class CommonMiddlewareTest(TestCase):
settings.APPEND_SLASH = True
request = self._get_request('needsquoting#')
r = CommonMiddleware().process_request(request)
self.assertEquals(r.status_code, 301)
self.assertEquals(
self.assertEqual(r.status_code, 301)
self.assertEqual(
r['Location'],
'http://testserver/middleware/needsquoting%23/')
@ -105,8 +105,8 @@ class CommonMiddlewareTest(TestCase):
settings.APPEND_SLASH = False
request = self._get_request('path/')
r = CommonMiddleware().process_request(request)
self.assertEquals(r.status_code, 301)
self.assertEquals(
self.assertEqual(r.status_code, 301)
self.assertEqual(
r['Location'],
'http://www.testserver/middleware/path/')
@ -115,8 +115,8 @@ class CommonMiddlewareTest(TestCase):
settings.APPEND_SLASH = True
request = self._get_request('slash/')
r = CommonMiddleware().process_request(request)
self.assertEquals(r.status_code, 301)
self.assertEquals(r['Location'],
self.assertEqual(r.status_code, 301)
self.assertEqual(r['Location'],
'http://www.testserver/middleware/slash/')
def test_prepend_www_append_slash_slashless(self):
@ -124,8 +124,8 @@ class CommonMiddlewareTest(TestCase):
settings.APPEND_SLASH = True
request = self._get_request('slash')
r = CommonMiddleware().process_request(request)
self.assertEquals(r.status_code, 301)
self.assertEquals(r['Location'],
self.assertEqual(r.status_code, 301)
self.assertEqual(r['Location'],
'http://www.testserver/middleware/slash/')
@ -139,7 +139,7 @@ class CommonMiddlewareTest(TestCase):
settings.APPEND_SLASH = True
request = self._get_request('customurlconf/slash/')
request.urlconf = 'regressiontests.middleware.extra_urls'
self.assertEquals(CommonMiddleware().process_request(request), None)
self.assertEqual(CommonMiddleware().process_request(request), None)
def test_append_slash_slashless_resource_custom_urlconf(self):
"""
@ -148,7 +148,7 @@ class CommonMiddlewareTest(TestCase):
settings.APPEND_SLASH = True
request = self._get_request('customurlconf/noslash')
request.urlconf = 'regressiontests.middleware.extra_urls'
self.assertEquals(CommonMiddleware().process_request(request), None)
self.assertEqual(CommonMiddleware().process_request(request), None)
def test_append_slash_slashless_unknown_custom_urlconf(self):
"""
@ -157,7 +157,7 @@ class CommonMiddlewareTest(TestCase):
settings.APPEND_SLASH = True
request = self._get_request('customurlconf/unknown')
request.urlconf = 'regressiontests.middleware.extra_urls'
self.assertEquals(CommonMiddleware().process_request(request), None)
self.assertEqual(CommonMiddleware().process_request(request), None)
def test_append_slash_redirect_custom_urlconf(self):
"""
@ -169,8 +169,8 @@ class CommonMiddlewareTest(TestCase):
r = CommonMiddleware().process_request(request)
self.assertFalse(r is None,
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
self.assertEquals(r.status_code, 301)
self.assertEquals(r['Location'], 'http://testserver/middleware/customurlconf/slash/')
self.assertEqual(r.status_code, 301)
self.assertEqual(r['Location'], 'http://testserver/middleware/customurlconf/slash/')
def test_append_slash_no_redirect_on_POST_in_DEBUG_custom_urlconf(self):
"""
@ -200,7 +200,7 @@ class CommonMiddlewareTest(TestCase):
settings.APPEND_SLASH = False
request = self._get_request('customurlconf/slash')
request.urlconf = 'regressiontests.middleware.extra_urls'
self.assertEquals(CommonMiddleware().process_request(request), None)
self.assertEqual(CommonMiddleware().process_request(request), None)
def test_append_slash_quoted_custom_urlconf(self):
"""
@ -213,8 +213,8 @@ class CommonMiddlewareTest(TestCase):
r = CommonMiddleware().process_request(request)
self.assertFalse(r is None,
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
self.assertEquals(r.status_code, 301)
self.assertEquals(
self.assertEqual(r.status_code, 301)
self.assertEqual(
r['Location'],
'http://testserver/middleware/customurlconf/needsquoting%23/')
@ -224,8 +224,8 @@ class CommonMiddlewareTest(TestCase):
request = self._get_request('customurlconf/path/')
request.urlconf = 'regressiontests.middleware.extra_urls'
r = CommonMiddleware().process_request(request)
self.assertEquals(r.status_code, 301)
self.assertEquals(
self.assertEqual(r.status_code, 301)
self.assertEqual(
r['Location'],
'http://www.testserver/middleware/customurlconf/path/')
@ -235,8 +235,8 @@ class CommonMiddlewareTest(TestCase):
request = self._get_request('customurlconf/slash/')
request.urlconf = 'regressiontests.middleware.extra_urls'
r = CommonMiddleware().process_request(request)
self.assertEquals(r.status_code, 301)
self.assertEquals(r['Location'],
self.assertEqual(r.status_code, 301)
self.assertEqual(r['Location'],
'http://www.testserver/middleware/customurlconf/slash/')
def test_prepend_www_append_slash_slashless_custom_urlconf(self):
@ -245,8 +245,8 @@ class CommonMiddlewareTest(TestCase):
request = self._get_request('customurlconf/slash')
request.urlconf = 'regressiontests.middleware.extra_urls'
r = CommonMiddleware().process_request(request)
self.assertEquals(r.status_code, 301)
self.assertEquals(r['Location'],
self.assertEqual(r.status_code, 301)
self.assertEqual(r['Location'],
'http://www.testserver/middleware/customurlconf/slash/')
class ConditionalGetMiddlewareTest(TestCase):
@ -287,50 +287,50 @@ class ConditionalGetMiddlewareTest(TestCase):
def test_if_none_match_and_no_etag(self):
self.req.META['HTTP_IF_NONE_MATCH'] = 'spam'
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
self.assertEquals(self.resp.status_code, 200)
self.assertEqual(self.resp.status_code, 200)
def test_no_if_none_match_and_etag(self):
self.resp['ETag'] = 'eggs'
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
self.assertEquals(self.resp.status_code, 200)
self.assertEqual(self.resp.status_code, 200)
def test_if_none_match_and_same_etag(self):
self.req.META['HTTP_IF_NONE_MATCH'] = self.resp['ETag'] = 'spam'
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
self.assertEquals(self.resp.status_code, 304)
self.assertEqual(self.resp.status_code, 304)
def test_if_none_match_and_different_etag(self):
self.req.META['HTTP_IF_NONE_MATCH'] = 'spam'
self.resp['ETag'] = 'eggs'
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
self.assertEquals(self.resp.status_code, 200)
self.assertEqual(self.resp.status_code, 200)
# Tests for the Last-Modified header
def test_if_modified_since_and_no_last_modified(self):
self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
self.assertEquals(self.resp.status_code, 200)
self.assertEqual(self.resp.status_code, 200)
def test_no_if_modified_since_and_last_modified(self):
self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:38:44 GMT'
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
self.assertEquals(self.resp.status_code, 200)
self.assertEqual(self.resp.status_code, 200)
def test_if_modified_since_and_same_last_modified(self):
self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'
self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:38:44 GMT'
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
self.assertEquals(self.resp.status_code, 304)
self.assertEqual(self.resp.status_code, 304)
def test_if_modified_since_and_last_modified_in_the_past(self):
self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'
self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:35:44 GMT'
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
self.assertEquals(self.resp.status_code, 304)
self.assertEqual(self.resp.status_code, 304)
def test_if_modified_since_and_last_modified_in_the_future(self):
self.req.META['HTTP_IF_MODIFIED_SINCE'] = 'Sat, 12 Feb 2011 17:38:44 GMT'
self.resp['Last-Modified'] = 'Sat, 12 Feb 2011 17:41:44 GMT'
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
self.assertEquals(self.resp.status_code, 200)
self.assertEqual(self.resp.status_code, 200)

View File

@ -125,10 +125,10 @@ class BaseMiddlewareExceptionTest(TestCase):
except Exception, e:
if type(extra_error) != type(e):
self.fail("Unexpected exception: %s" % e)
self.assertEquals(len(self.exceptions), len(errors))
self.assertEqual(len(self.exceptions), len(errors))
for i, error in enumerate(errors):
exception, value, tb = self.exceptions[i]
self.assertEquals(value.args, (error, ))
self.assertEqual(value.args, (error, ))
def assert_middleware_usage(self, middleware, request, view, template_response, response, exception):
self.assertEqual(middleware.process_request_called, request)

View File

@ -324,10 +324,10 @@ class TypeCoercionTests(test.TestCase):
"""
def test_lookup_integer_in_charfield(self):
self.assertEquals(Post.objects.filter(title=9).count(), 0)
self.assertEqual(Post.objects.filter(title=9).count(), 0)
def test_lookup_integer_in_textfield(self):
self.assertEquals(Post.objects.filter(body=24).count(), 0)
self.assertEqual(Post.objects.filter(body=24).count(), 0)
class FileFieldTests(unittest.TestCase):
def test_clearable(self):

View File

@ -80,7 +80,7 @@ class OverrideCleanTests(TestCase):
self.assertTrue(form.is_valid())
# form.instance.left will be None if the instance was not constructed
# by form.full_clean().
self.assertEquals(form.instance.left, 1)
self.assertEqual(form.instance.left, 1)
# Regression test for #12960.
# Make sure the cleaned_data returned from ModelForm.clean() is applied to the
@ -133,7 +133,7 @@ class ManyToManyCallableInitialTests(TestCase):
# Create a ModelForm, instantiate it, and check that the output is as expected
ModelForm = modelform_factory(Article, formfield_callback=formfield_for_dbfield)
form = ModelForm()
self.assertEquals(form.as_ul(), u"""<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="100" /></li>
self.assertEqual(form.as_ul(), u"""<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="100" /></li>
<li><label for="id_publications">Publications:</label> <select multiple="multiple" name="publications" id="id_publications">
<option value="1" selected="selected">First Book</option>
<option value="2" selected="selected">Second Book</option>
@ -193,7 +193,7 @@ class OneToOneFieldTests(TestCase):
date_published=date(1991, 8, 22))
author = Author.objects.create(publication=publication, full_name='John Doe')
form = AuthorForm({'publication':u'', 'full_name':'John Doe'}, instance=author)
self.assert_(form.is_valid())
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['publication'], None)
author = form.save()
# author object returned from form still retains original publication object
@ -211,7 +211,7 @@ class OneToOneFieldTests(TestCase):
date_published=date(1991, 8, 22))
author = Author1.objects.create(publication=publication, full_name='John Doe')
form = AuthorForm({'publication':u'', 'full_name':'John Doe'}, instance=author)
self.assert_(not form.is_valid())
self.assertTrue(not form.is_valid())
class ModelChoiceForm(forms.Form):
@ -224,8 +224,8 @@ class TestTicket11183(TestCase):
field1 = form1.fields['person']
# To allow the widget to change the queryset of field1.widget.choices correctly,
# without affecting other forms, the following must hold:
self.assert_(field1 is not ModelChoiceForm.base_fields['person'])
self.assert_(field1.widget.choices.field is field1)
self.assertTrue(field1 is not ModelChoiceForm.base_fields['person'])
self.assertTrue(field1.widget.choices.field is field1)
class HomepageForm(forms.ModelForm):
class Meta:
@ -253,12 +253,12 @@ class URLFieldTests(TestCase):
form = HomepageForm({'url': 'example.com'})
form.is_valid()
# self.assertTrue(form.is_valid())
# self.assertEquals(form.cleaned_data['url'], 'http://example.com/')
# self.assertEqual(form.cleaned_data['url'], 'http://example.com/')
form = HomepageForm({'url': 'example.com/test'})
form.is_valid()
# self.assertTrue(form.is_valid())
# self.assertEquals(form.cleaned_data['url'], 'http://example.com/test')
# self.assertEqual(form.cleaned_data['url'], 'http://example.com/test')
class FormFieldCallbackTests(TestCase):
@ -376,14 +376,14 @@ class FileFieldTests(unittest.TestCase):
"""
form = DocumentForm()
self.assert_('name="myfile"' in unicode(form))
self.assert_('myfile-clear' not in unicode(form))
self.assertTrue('name="myfile"' in unicode(form))
self.assertTrue('myfile-clear' not in unicode(form))
form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', 'content')})
self.assert_(form.is_valid())
self.assertTrue(form.is_valid())
doc = form.save(commit=False)
self.assertEqual(doc.myfile.name, 'something.txt')
form = DocumentForm(instance=doc)
self.assert_('myfile-clear' in unicode(form))
self.assertTrue('myfile-clear' in unicode(form))
form = DocumentForm(instance=doc, data={'myfile-clear': 'true'})
doc = form.save(commit=False)
self.assertEqual(bool(doc.myfile), False)
@ -396,17 +396,17 @@ class FileFieldTests(unittest.TestCase):
"""
form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', 'content')})
self.assert_(form.is_valid())
self.assertTrue(form.is_valid())
doc = form.save(commit=False)
form = DocumentForm(instance=doc,
files={'myfile': SimpleUploadedFile('something.txt', 'content')},
data={'myfile-clear': 'true'})
self.assert_(not form.is_valid())
self.assertTrue(not form.is_valid())
self.assertEqual(form.errors['myfile'],
[u'Please either submit a file or check the clear checkbox, not both.'])
rendered = unicode(form)
self.assert_('something.txt' in rendered)
self.assert_('myfile-clear' in rendered)
self.assertTrue('something.txt' in rendered)
self.assertTrue('myfile-clear' in rendered)
class EditionForm(forms.ModelForm):
author = forms.ModelChoiceField(queryset=Person.objects.all())
@ -428,13 +428,13 @@ class UniqueErrorsTests(TestCase):
def test_unique_error_message(self):
form = EditionForm(data={'author': self.author1.pk, 'publication': self.pub2.pk, 'edition': 1, 'isbn': '9783161484100'})
self.assertEquals(form.errors, {'isbn': [u'Edition with this Isbn already exists.']})
self.assertEqual(form.errors, {'isbn': [u'Edition with this Isbn already exists.']})
def test_unique_together_error_message(self):
form = EditionForm(data={'author': self.author1.pk, 'publication': self.pub1.pk, 'edition': 2, 'isbn': '9783161489999'})
self.assertEquals(form.errors, {'__all__': [u'Edition with this Author and Publication already exists.']})
self.assertEqual(form.errors, {'__all__': [u'Edition with this Author and Publication already exists.']})
form = EditionForm(data={'author': self.author2.pk, 'publication': self.pub1.pk, 'edition': 1, 'isbn': '9783161487777'})
self.assertEquals(form.errors, {'__all__': [u'Edition with this Publication and Edition already exists.']})
self.assertEqual(form.errors, {'__all__': [u'Edition with this Publication and Edition already exists.']})
class EmptyFieldsTestCase(TestCase):

View File

@ -367,7 +367,7 @@ class ModelInheritanceTest(TestCase):
# from an ABC even when there are one or more intermediate
# abstract models in the inheritance chain, for consistency with
# verbose_name.
self.assertEquals(
self.assertEqual(
InternalCertificationAudit._meta.verbose_name_plural,
u'Audits'
)
@ -394,12 +394,12 @@ class ModelInheritanceTest(TestCase):
# Regression test for #13987: Primary key is incorrectly determined
# when more than one model has a concrete->abstract->concrete
# inheritance hierarchy.
self.assertEquals(
self.assertEqual(
len([field for field in BusStation._meta.local_fields
if field.primary_key]),
1
)
self.assertEquals(
self.assertEqual(
len([field for field in TrainStation._meta.local_fields
if field.primary_key]),
1

View File

@ -37,7 +37,7 @@ class ModelAdminTests(TestCase):
def test_default_fields(self):
ma = ModelAdmin(Band, self.site)
self.assertEquals(ma.get_form(request).base_fields.keys(),
self.assertEqual(ma.get_form(request).base_fields.keys(),
['name', 'bio', 'sign_date'])
def test_default_fieldsets(self):

File diff suppressed because it is too large Load Diff

View File

@ -17,8 +17,8 @@ class NullFkTests(TestCase):
# that come after the NULLs, or else data that should exist won't). Regression
# test for #7369.
c = Comment.objects.select_related().get(id=1)
self.assertEquals(c.post, p)
self.assertEquals(Comment.objects.select_related().get(id=2).post, None)
self.assertEqual(c.post, p)
self.assertEqual(Comment.objects.select_related().get(id=2).post, None)
self.assertQuerysetEqual(
Comment.objects.select_related('post__forum__system_info').all(),

View File

@ -44,7 +44,7 @@ class NullQueriesTests(TestCase):
# Related managers use __exact=None implicitly if the object hasn't been saved.
p2 = Poll(question="How?")
self.assertEquals(repr(p2.choice_set.all()), '[]')
self.assertEqual(repr(p2.choice_set.all()), '[]')
def test_reverse_relations(self):
"""

View File

@ -50,8 +50,8 @@ class OneToOneRegressionTests(TestCase):
Check that the name of the cache for the reverse object is correct.
"""
self.assertEquals(self.p1.restaurant, self.r1)
self.assertEquals(self.p1.bar, self.b1)
self.assertEqual(self.p1.restaurant, self.r1)
self.assertEqual(self.p1.bar, self.b1)
def test_related_object_cache(self):
""" Regression test for #6886 (the related-object cache) """

View File

@ -1402,13 +1402,13 @@ class SubqueryTests(TestCase):
"Subselects honor any manual ordering"
try:
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2])
self.assertEquals(set(query.values_list('id', flat=True)), set([2,3]))
self.assertEqual(set(query.values_list('id', flat=True)), set([2,3]))
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[:2])
self.assertEquals(set(query.values_list('id', flat=True)), set([2,3]))
self.assertEqual(set(query.values_list('id', flat=True)), set([2,3]))
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[2:])
self.assertEquals(set(query.values_list('id', flat=True)), set([1]))
self.assertEqual(set(query.values_list('id', flat=True)), set([1]))
except DatabaseError:
# Oracle and MySQL both have problems with sliced subselects.
# This prevents us from even evaluating this test case at all.
@ -1419,7 +1419,7 @@ class SubqueryTests(TestCase):
"Delete queries can safely contain sliced subqueries"
try:
DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:1]).delete()
self.assertEquals(set(DumbCategory.objects.values_list('id', flat=True)), set([1,2]))
self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), set([1,2]))
except DatabaseError:
# Oracle and MySQL both have problems with sliced subselects.
# This prevents us from even evaluating this test case at all.
@ -1441,7 +1441,7 @@ class CloneTests(TestCase):
# Use the note queryset in a query, and evalute
# that query in a way that involves cloning.
try:
self.assertEquals(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good')
self.assertEqual(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good')
except:
self.fail('Query should be clonable')

View File

@ -22,11 +22,11 @@ class ReverseSingleRelatedTests(TestCase):
["<Source: Source object>"]
)
self.assertEquals(public_item.source, public_source)
self.assertEqual(public_item.source, public_source)
# Make sure that an item can still access its related source even if the default
# manager doesn't normally allow it.
self.assertEquals(private_item.source, private_source)
self.assertEqual(private_item.source, private_source)
# If the manager is marked "use_for_related_fields", it'll get used instead
# of the "bare" queryset. Usually you'd define this as a property on the class,

View File

@ -27,16 +27,16 @@ class SelectRelatedRegressTests(TestCase):
c2=Connection.objects.create(start=port2, end=port3)
connections=Connection.objects.filter(start__device__building=b, end__device__building=b).order_by('id')
self.assertEquals([(c.id, unicode(c.start), unicode(c.end)) for c in connections],
self.assertEqual([(c.id, unicode(c.start), unicode(c.end)) for c in connections],
[(1, u'router/4', u'switch/7'), (2, u'switch/7', u'server/1')])
connections=Connection.objects.filter(start__device__building=b, end__device__building=b).select_related().order_by('id')
self.assertEquals([(c.id, unicode(c.start), unicode(c.end)) for c in connections],
self.assertEqual([(c.id, unicode(c.start), unicode(c.end)) for c in connections],
[(1, u'router/4', u'switch/7'), (2, u'switch/7', u'server/1')])
# This final query should only join seven tables (port, device and building
# twice each, plus connection once).
self.assertEquals(connections.query.count_active_tables(), 7)
self.assertEqual(connections.query.count_active_tables(), 7)
def test_regression_8106(self):
@ -58,8 +58,8 @@ class SelectRelatedRegressTests(TestCase):
e = Enrollment.objects.create(std=s, cls=c)
e_related = Enrollment.objects.all().select_related()[0]
self.assertEquals(e_related.std.person.user.name, u"std")
self.assertEquals(e_related.cls.org.person.user.name, u"org")
self.assertEqual(e_related.std.person.user.name, u"std")
self.assertEqual(e_related.cls.org.person.user.name, u"org")
def test_regression_8036(self):
"""
@ -75,13 +75,13 @@ class SelectRelatedRegressTests(TestCase):
active = ClientStatus.objects.create(name='active')
client = Client.objects.create(name='client', status=active)
self.assertEquals(client.status, active)
self.assertEquals(Client.objects.select_related()[0].status, active)
self.assertEquals(Client.objects.select_related('state')[0].status, active)
self.assertEquals(Client.objects.select_related('state', 'status')[0].status, active)
self.assertEquals(Client.objects.select_related('state__country')[0].status, active)
self.assertEquals(Client.objects.select_related('state__country', 'status')[0].status, active)
self.assertEquals(Client.objects.select_related('status')[0].status, active)
self.assertEqual(client.status, active)
self.assertEqual(Client.objects.select_related()[0].status, active)
self.assertEqual(Client.objects.select_related('state')[0].status, active)
self.assertEqual(Client.objects.select_related('state', 'status')[0].status, active)
self.assertEqual(Client.objects.select_related('state__country')[0].status, active)
self.assertEqual(Client.objects.select_related('state__country', 'status')[0].status, active)
self.assertEqual(Client.objects.select_related('status')[0].status, active)
def test_multi_table_inheritance(self):
""" Exercising select_related() with multi-table model inheritance. """
@ -108,27 +108,27 @@ class SelectRelatedRegressTests(TestCase):
c1 = Client.objects.create(name='Brian Burke', state=wa, status=active)
burke = Client.objects.select_related('state').defer('state__name').get(name='Brian Burke')
self.assertEquals(burke.name, u'Brian Burke')
self.assertEquals(burke.state.name, u'Western Australia')
self.assertEqual(burke.name, u'Brian Burke')
self.assertEqual(burke.state.name, u'Western Australia')
# Still works if we're dealing with an inherited class
sc1 = SpecialClient.objects.create(name='Troy Buswell', state=wa, status=active, value=42)
troy = SpecialClient.objects.select_related('state').defer('state__name').get(name='Troy Buswell')
self.assertEquals(troy.name, u'Troy Buswell')
self.assertEquals(troy.value, 42)
self.assertEquals(troy.state.name, u'Western Australia')
self.assertEqual(troy.name, u'Troy Buswell')
self.assertEqual(troy.value, 42)
self.assertEqual(troy.state.name, u'Western Australia')
# Still works if we defer an attribute on the inherited class
troy = SpecialClient.objects.select_related('state').defer('value', 'state__name').get(name='Troy Buswell')
self.assertEquals(troy.name, u'Troy Buswell')
self.assertEquals(troy.value, 42)
self.assertEquals(troy.state.name, u'Western Australia')
self.assertEqual(troy.name, u'Troy Buswell')
self.assertEqual(troy.value, 42)
self.assertEqual(troy.state.name, u'Western Australia')
# Also works if you use only, rather than defer
troy = SpecialClient.objects.select_related('state').only('name').get(name='Troy Buswell')
self.assertEquals(troy.name, u'Troy Buswell')
self.assertEquals(troy.value, 42)
self.assertEquals(troy.state.name, u'Western Australia')
self.assertEqual(troy.name, u'Troy Buswell')
self.assertEqual(troy.value, 42)
self.assertEqual(troy.state.name, u'Western Australia')

View File

@ -381,7 +381,7 @@ def serializerTest(format, self):
# Assert that the number of objects deserialized is the
# same as the number that was serialized.
for klass, count in instance_count.items():
self.assertEquals(count, klass.objects.count())
self.assertEqual(count, klass.objects.count())
def fieldsTest(format, self):
obj = ComplexModel(field1='first', field2='second', field3='third')

View File

@ -67,19 +67,19 @@ class SignalsRegressTests(TestCase):
len(models.signals.pre_delete.receivers),
len(models.signals.post_delete.receivers))
self.assertEquals(self.pre_signals, post_signals)
self.assertEqual(self.pre_signals, post_signals)
def test_model_signals(self):
""" Model saves should throw some signals. """
a1 = Author(name='Neal Stephenson')
self.assertEquals(self.get_signal_output(a1.save), [
self.assertEqual(self.get_signal_output(a1.save), [
"pre_save signal, Neal Stephenson",
"post_save signal, Neal Stephenson",
"Is created"
])
b1 = Book(name='Snow Crash')
self.assertEquals(self.get_signal_output(b1.save), [
self.assertEqual(self.get_signal_output(b1.save), [
"pre_save signal, Snow Crash",
"post_save signal, Snow Crash",
"Is created"
@ -92,5 +92,5 @@ class SignalsRegressTests(TestCase):
self.get_signal_output(b1.save)
a1 = Author(name='Neal Stephenson')
self.get_signal_output(a1.save)
self.assertEquals(self.get_signal_output(setattr, b1, 'authors', [a1]), [])
self.assertEquals(self.get_signal_output(setattr, b1, 'authors', []), [])
self.assertEqual(self.get_signal_output(setattr, b1, 'authors', [a1]), [])
self.assertEqual(self.get_signal_output(setattr, b1, 'authors', []), [])

View File

@ -194,7 +194,7 @@ class TestFindStatic(BuildStaticTestCase, TestDefaults):
lines = [l.strip() for l in sys.stdout.readlines()]
finally:
sys.stdout = _stdout
self.assertEquals(len(lines), 3) # three because there is also the "Found <file> here" line
self.assertEqual(len(lines), 3) # three because there is also the "Found <file> here" line
self.assertTrue('project' in lines[1])
self.assertTrue('apps' in lines[2])
@ -244,7 +244,7 @@ class TestNoFilesCreated(object):
"""
Make sure no files were create in the destination directory.
"""
self.assertEquals(os.listdir(settings.STATIC_ROOT), [])
self.assertEqual(os.listdir(settings.STATIC_ROOT), [])
class TestBuildStaticDryRun(BuildStaticTestCase, TestNoFilesCreated):
@ -302,7 +302,7 @@ class TestServeStatic(StaticFilesTestCase):
self.assertContains(self._response(filepath), text)
def assertFileNotFound(self, filepath):
self.assertEquals(self._response(filepath).status_code, 404)
self.assertEqual(self._response(filepath).status_code, 404)
class TestServeDisabled(TestServeStatic):
@ -349,11 +349,11 @@ class FinderTestCase(object):
"""
def test_find_first(self):
src, dst = self.find_first
self.assertEquals(self.finder.find(src), dst)
self.assertEqual(self.finder.find(src), dst)
def test_find_all(self):
src, dst = self.find_all
self.assertEquals(self.finder.find(src, all=True), dst)
self.assertEqual(self.finder.find(src, all=True), dst)
class TestFileSystemFinder(StaticFilesTestCase, FinderTestCase):

View File

@ -23,11 +23,11 @@ class StringLookupTests(TestCase):
b1 = Bar(name="Bar1", normal=f1, fwd=w1, back=f2)
b1.save()
self.assertEquals(b1.normal, f1)
self.assertEqual(b1.normal, f1)
self.assertEquals(b1.fwd, w1)
self.assertEqual(b1.fwd, w1)
self.assertEquals(b1.back, f2)
self.assertEqual(b1.back, f2)
base1 = Base(name="Base1")
base1.save()
@ -35,7 +35,7 @@ class StringLookupTests(TestCase):
child1 = Child(name="Child1", parent=base1)
child1.save()
self.assertEquals(child1.parent, base1)
self.assertEqual(child1.parent, base1)
def test_unicode_chars_in_queries(self):
"""
@ -48,10 +48,10 @@ class StringLookupTests(TestCase):
fx = Foo(name='Bjorn', friend=u'François')
fx.save()
self.assertEquals(Foo.objects.get(friend__contains=u'\xe7'), fx)
self.assertEqual(Foo.objects.get(friend__contains=u'\xe7'), fx)
# We can also do the above query using UTF-8 strings.
self.assertEquals(Foo.objects.get(friend__contains='\xc3\xa7'), fx)
self.assertEqual(Foo.objects.get(friend__contains='\xc3\xa7'), fx)
def test_queries_on_textfields(self):
"""
@ -62,9 +62,9 @@ class StringLookupTests(TestCase):
a = Article(name='Test', text='The quick brown fox jumps over the lazy dog.')
a.save()
self.assertEquals(Article.objects.get(text__exact='The quick brown fox jumps over the lazy dog.'), a)
self.assertEqual(Article.objects.get(text__exact='The quick brown fox jumps over the lazy dog.'), a)
self.assertEquals(Article.objects.get(text__contains='quick brown fox'), a)
self.assertEqual(Article.objects.get(text__contains='quick brown fox'), a)
def test_ipaddress_on_postgresql(self):
"""
@ -74,5 +74,5 @@ class StringLookupTests(TestCase):
"""
a = Article(name='IP test', text='The body', submitted_from='192.0.2.100')
a.save()
self.assertEquals(repr(Article.objects.filter(submitted_from__contains='192.0.2')),
self.assertEqual(repr(Article.objects.filter(submitted_from__contains='192.0.2')),
repr([a]))

View File

@ -198,7 +198,7 @@ class SyndicationFeedTest(FeedTestCase):
link = item.getElementsByTagName('link')[0]
if link.firstChild.wholeText == 'http://example.com/blog/4/':
title = item.getElementsByTagName('title')[0]
self.assertEquals(title.firstChild.wholeText, u'A &amp; B &lt; C &gt; D')
self.assertEqual(title.firstChild.wholeText, u'A &amp; B &lt; C &gt; D')
def test_naive_datetime_conversion(self):
"""
@ -329,14 +329,14 @@ class DeprecatedSyndicationFeedTest(FeedTestCase):
Test that an empty feed_dict raises a 404.
"""
response = self.client.get('/syndication/depr-feeds-empty/aware-dates/')
self.assertEquals(response.status_code, 404)
self.assertEqual(response.status_code, 404)
def test_nonexistent_slug(self):
"""
Test that a non-existent slug raises a 404.
"""
response = self.client.get('/syndication/depr-feeds/foobar/')
self.assertEquals(response.status_code, 404)
self.assertEqual(response.status_code, 404)
def test_rss_feed(self):
"""
@ -360,5 +360,5 @@ class DeprecatedSyndicationFeedTest(FeedTestCase):
exception.
"""
response = self.client.get('/syndication/depr-feeds/complex/')
self.assertEquals(response.status_code, 404)
self.assertEqual(response.status_code, 404)

View File

@ -13,27 +13,27 @@ class CustomFilterTests(TestCase):
class CustomTagTests(TestCase):
def verify_tag(self, tag, name):
self.assertEquals(tag.__name__, name)
self.assertEquals(tag.__doc__, 'Expected %s __doc__' % name)
self.assertEquals(tag.__dict__['anything'], 'Expected %s __dict__' % name)
self.assertEqual(tag.__name__, name)
self.assertEqual(tag.__doc__, 'Expected %s __doc__' % name)
self.assertEqual(tag.__dict__['anything'], 'Expected %s __dict__' % name)
def test_simple_tags(self):
c = template.Context({'value': 42})
t = template.Template('{% load custom %}{% no_params %}')
self.assertEquals(t.render(c), u'no_params - Expected result')
self.assertEqual(t.render(c), u'no_params - Expected result')
t = template.Template('{% load custom %}{% one_param 37 %}')
self.assertEquals(t.render(c), u'one_param - Expected result: 37')
self.assertEqual(t.render(c), u'one_param - Expected result: 37')
t = template.Template('{% load custom %}{% explicit_no_context 37 %}')
self.assertEquals(t.render(c), u'explicit_no_context - Expected result: 37')
self.assertEqual(t.render(c), u'explicit_no_context - Expected result: 37')
t = template.Template('{% load custom %}{% no_params_with_context %}')
self.assertEquals(t.render(c), u'no_params_with_context - Expected result (context value: 42)')
self.assertEqual(t.render(c), u'no_params_with_context - Expected result (context value: 42)')
t = template.Template('{% load custom %}{% params_and_context 37 %}')
self.assertEquals(t.render(c), u'params_and_context - Expected result (context value: 42): 37')
self.assertEqual(t.render(c), u'params_and_context - Expected result (context value: 42): 37')
def test_simple_tag_registration(self):
# Test that the decorators preserve the decorated function's docstring, name and attributes.

View File

@ -166,7 +166,7 @@ class SimpleTemplateResponseTest(BaseTemplateResponseTest):
# When the content is rendered, all the callbacks are invoked, too.
response.render()
self.assertEqual('First template\n', response.content)
self.assertEquals(post, ['post1','post2'])
self.assertEqual(post, ['post1','post2'])
def test_pickling(self):
@ -184,9 +184,9 @@ class SimpleTemplateResponseTest(BaseTemplateResponseTest):
pickled_response = pickle.dumps(response)
unpickled_response = pickle.loads(pickled_response)
self.assertEquals(unpickled_response.content, response.content)
self.assertEquals(unpickled_response['content-type'], response['content-type'])
self.assertEquals(unpickled_response.status_code, response.status_code)
self.assertEqual(unpickled_response.content, response.content)
self.assertEqual(unpickled_response['content-type'], response['content-type'])
self.assertEqual(unpickled_response.status_code, response.status_code)
# ...and the unpickled reponse doesn't have the
# template-related attributes, so it can't be re-rendered
@ -249,9 +249,9 @@ class TemplateResponseTest(BaseTemplateResponseTest):
pickled_response = pickle.dumps(response)
unpickled_response = pickle.loads(pickled_response)
self.assertEquals(unpickled_response.content, response.content)
self.assertEquals(unpickled_response['content-type'], response['content-type'])
self.assertEquals(unpickled_response.status_code, response.status_code)
self.assertEqual(unpickled_response.content, response.content)
self.assertEqual(unpickled_response['content-type'], response['content-type'])
self.assertEqual(unpickled_response.status_code, response.status_code)
# ...and the unpickled reponse doesn't have the
# template-related attributes, so it can't be re-rendered

View File

@ -12,14 +12,14 @@ class SmartIfTests(unittest.TestCase):
def test_not(self):
var = IfParser(["not", False]).parse()
self.assertEqual("(not (literal False))", repr(var))
self.assert_(var.eval({}))
self.assertTrue(var.eval({}))
self.assertFalse(IfParser(["not", True]).parse().eval({}))
def test_or(self):
var = IfParser([True, "or", False]).parse()
self.assertEqual("(or (literal True) (literal False))", repr(var))
self.assert_(var.eval({}))
self.assertTrue(var.eval({}))
def test_in(self):
list_ = [1,2,3]

View File

@ -359,7 +359,7 @@ class Templates(unittest.TestCase):
except TemplateSyntaxError, e:
# Assert that we are getting the template syntax error and not the
# string encoding error.
self.assertEquals(e.args[0], "Caught NoReverseMatch while rendering: Reverse for 'will_not_match' with arguments '()' and keyword arguments '{}' not found.")
self.assertEqual(e.args[0], "Caught NoReverseMatch while rendering: Reverse for 'will_not_match' with arguments '()' and keyword arguments '{}' not found.")
settings.SETTINGS_MODULE = old_settings_module
settings.TEMPLATE_DEBUG = old_template_debug
@ -370,7 +370,7 @@ class Templates(unittest.TestCase):
try:
t = Template("{% if 1 %}lala{% endblock %}{% endif %}")
except TemplateSyntaxError, e:
self.assertEquals(e.args[0], "Invalid block tag: 'endblock', expected 'else' or 'endif'")
self.assertEqual(e.args[0], "Invalid block tag: 'endblock', expected 'else' or 'endif'")
def test_templates(self):
template_tests = self.get_template_tests()

View File

@ -258,8 +258,8 @@ class AssertRedirectsTests(TestCase):
self.assertRedirects(response, '/test_client_regress/no_template_view/',
status_code=301, target_status_code=200)
self.assertEquals(len(response.redirect_chain), 1)
self.assertEquals(response.redirect_chain[0], ('http://testserver/test_client_regress/no_template_view/', 301))
self.assertEqual(len(response.redirect_chain), 1)
self.assertEqual(response.redirect_chain[0], ('http://testserver/test_client_regress/no_template_view/', 301))
def test_multiple_redirect_chain(self):
"You can follow a redirect chain of multiple redirects"
@ -267,10 +267,10 @@ class AssertRedirectsTests(TestCase):
self.assertRedirects(response, '/test_client_regress/no_template_view/',
status_code=301, target_status_code=200)
self.assertEquals(len(response.redirect_chain), 3)
self.assertEquals(response.redirect_chain[0], ('http://testserver/test_client_regress/redirects/further/', 301))
self.assertEquals(response.redirect_chain[1], ('http://testserver/test_client_regress/redirects/further/more/', 301))
self.assertEquals(response.redirect_chain[2], ('http://testserver/test_client_regress/no_template_view/', 301))
self.assertEqual(len(response.redirect_chain), 3)
self.assertEqual(response.redirect_chain[0], ('http://testserver/test_client_regress/redirects/further/', 301))
self.assertEqual(response.redirect_chain[1], ('http://testserver/test_client_regress/redirects/further/more/', 301))
self.assertEqual(response.redirect_chain[2], ('http://testserver/test_client_regress/no_template_view/', 301))
def test_redirect_chain_to_non_existent(self):
"You can follow a chain to a non-existent view"
@ -284,7 +284,7 @@ class AssertRedirectsTests(TestCase):
# The chain of redirects stops once the cycle is detected.
self.assertRedirects(response, '/test_client_regress/redirect_to_self/',
status_code=301, target_status_code=301)
self.assertEquals(len(response.redirect_chain), 2)
self.assertEqual(len(response.redirect_chain), 2)
def test_circular_redirect(self):
"Circular redirect chains are caught and escaped"
@ -292,7 +292,7 @@ class AssertRedirectsTests(TestCase):
# The chain of redirects will get back to the starting point, but stop there.
self.assertRedirects(response, '/test_client_regress/circular_redirect_2/',
status_code=301, target_status_code=301)
self.assertEquals(len(response.redirect_chain), 4)
self.assertEqual(len(response.redirect_chain), 4)
def test_redirect_chain_post(self):
"A redirect chain will be followed from an initial POST post"
@ -300,7 +300,7 @@ class AssertRedirectsTests(TestCase):
{'nothing': 'to_send'}, follow=True)
self.assertRedirects(response,
'/test_client_regress/no_template_view/', 301, 200)
self.assertEquals(len(response.redirect_chain), 3)
self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_head(self):
"A redirect chain will be followed from an initial HEAD request"
@ -308,7 +308,7 @@ class AssertRedirectsTests(TestCase):
{'nothing': 'to_send'}, follow=True)
self.assertRedirects(response,
'/test_client_regress/no_template_view/', 301, 200)
self.assertEquals(len(response.redirect_chain), 3)
self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_options(self):
"A redirect chain will be followed from an initial OPTIONS request"
@ -316,7 +316,7 @@ class AssertRedirectsTests(TestCase):
{'nothing': 'to_send'}, follow=True)
self.assertRedirects(response,
'/test_client_regress/no_template_view/', 301, 200)
self.assertEquals(len(response.redirect_chain), 3)
self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_put(self):
"A redirect chain will be followed from an initial PUT request"
@ -324,7 +324,7 @@ class AssertRedirectsTests(TestCase):
{'nothing': 'to_send'}, follow=True)
self.assertRedirects(response,
'/test_client_regress/no_template_view/', 301, 200)
self.assertEquals(len(response.redirect_chain), 3)
self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_delete(self):
"A redirect chain will be followed from an initial DELETE request"
@ -332,7 +332,7 @@ class AssertRedirectsTests(TestCase):
{'nothing': 'to_send'}, follow=True)
self.assertRedirects(response,
'/test_client_regress/no_template_view/', 301, 200)
self.assertEquals(len(response.redirect_chain), 3)
self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_on_non_redirect_page(self):
"An assertion is raised if the original page couldn't be retrieved as expected"
@ -605,7 +605,7 @@ class UrlconfSubstitutionTests(TestCase):
def test_urlconf_was_changed(self):
"TestCase can enforce a custom URLconf on a per-test basis"
url = reverse('arg_view', args=['somename'])
self.assertEquals(url, '/arg_view/somename/')
self.assertEqual(url, '/arg_view/somename/')
# This test needs to run *after* UrlconfSubstitutionTests; the zz prefix in the
# name is to ensure alphabetical ordering.
@ -613,7 +613,7 @@ class zzUrlconfSubstitutionTests(TestCase):
def test_urlconf_was_reverted(self):
"URLconf is reverted to original value after modification in a TestCase"
url = reverse('arg_view', args=['somename'])
self.assertEquals(url, '/test_client_regress/arg_view/somename/')
self.assertEqual(url, '/test_client_regress/arg_view/somename/')
class ContextTests(TestCase):
fixtures = ['testdata']
@ -631,7 +631,7 @@ class ContextTests(TestCase):
response.context['does-not-exist']
self.fail('Should not be able to retrieve non-existent key')
except KeyError, e:
self.assertEquals(e.args[0], 'does-not-exist')
self.assertEqual(e.args[0], 'does-not-exist')
def test_inherited_context(self):
"Context variables can be retrieved from a list of contexts"
@ -647,7 +647,7 @@ class ContextTests(TestCase):
response.context['does-not-exist']
self.fail('Should not be able to retrieve non-existent key')
except KeyError, e:
self.assertEquals(e.args[0], 'does-not-exist')
self.assertEqual(e.args[0], 'does-not-exist')
def test_15368(self):
# Need to insert a context processor that assumes certain things about
@ -868,13 +868,13 @@ class RequestHeadersTest(TestCase):
def test_client_headers(self):
"A test client can receive custom headers"
response = self.client.get("/test_client_regress/check_headers/", HTTP_X_ARG_CHECK='Testing 123')
self.assertEquals(response.content, "HTTP_X_ARG_CHECK: Testing 123")
self.assertEquals(response.status_code, 200)
self.assertEqual(response.content, "HTTP_X_ARG_CHECK: Testing 123")
self.assertEqual(response.status_code, 200)
def test_client_headers_redirect(self):
"Test client headers are preserved through redirects"
response = self.client.get("/test_client_regress/check_headers_redirect/", follow=True, HTTP_X_ARG_CHECK='Testing 123')
self.assertEquals(response.content, "HTTP_X_ARG_CHECK: Testing 123")
self.assertEqual(response.content, "HTTP_X_ARG_CHECK: Testing 123")
self.assertRedirects(response, '/test_client_regress/check_headers/',
status_code=301, target_status_code=200)

View File

@ -23,70 +23,70 @@ class TextTests(TestCase):
def test_smart_split(self):
self.assertEquals(list(smart_split(r'''This is "a person" test.''')),
self.assertEqual(list(smart_split(r'''This is "a person" test.''')),
[u'This', u'is', u'"a person"', u'test.'])
self.assertEquals(list(smart_split(r'''This is "a person's" test.'''))[2],
self.assertEqual(list(smart_split(r'''This is "a person's" test.'''))[2],
u'"a person\'s"')
self.assertEquals(list(smart_split(r'''This is "a person\"s" test.'''))[2],
self.assertEqual(list(smart_split(r'''This is "a person\"s" test.'''))[2],
u'"a person\\"s"')
self.assertEquals(list(smart_split('''"a 'one''')), [u'"a', u"'one"])
self.assertEqual(list(smart_split('''"a 'one''')), [u'"a', u"'one"])
self.assertEquals(list(smart_split(r'''all friends' tests'''))[1],
self.assertEqual(list(smart_split(r'''all friends' tests'''))[1],
"friends'")
self.assertEquals(list(smart_split(u'url search_page words="something else"')),
self.assertEqual(list(smart_split(u'url search_page words="something else"')),
[u'url', u'search_page', u'words="something else"'])
self.assertEquals(list(smart_split(u"url search_page words='something else'")),
self.assertEqual(list(smart_split(u"url search_page words='something else'")),
[u'url', u'search_page', u"words='something else'"])
self.assertEquals(list(smart_split(u'url search_page words "something else"')),
self.assertEqual(list(smart_split(u'url search_page words "something else"')),
[u'url', u'search_page', u'words', u'"something else"'])
self.assertEquals(list(smart_split(u'url search_page words-"something else"')),
self.assertEqual(list(smart_split(u'url search_page words-"something else"')),
[u'url', u'search_page', u'words-"something else"'])
self.assertEquals(list(smart_split(u'url search_page words=hello')),
self.assertEqual(list(smart_split(u'url search_page words=hello')),
[u'url', u'search_page', u'words=hello'])
self.assertEquals(list(smart_split(u'url search_page words="something else')),
self.assertEqual(list(smart_split(u'url search_page words="something else')),
[u'url', u'search_page', u'words="something', u'else'])
self.assertEquals(list(smart_split("cut:','|cut:' '")),
self.assertEqual(list(smart_split("cut:','|cut:' '")),
[u"cut:','|cut:' '"])
def test_urlquote(self):
self.assertEquals(urlquote(u'Paris & Orl\xe9ans'),
self.assertEqual(urlquote(u'Paris & Orl\xe9ans'),
u'Paris%20%26%20Orl%C3%A9ans')
self.assertEquals(urlquote(u'Paris & Orl\xe9ans', safe="&"),
self.assertEqual(urlquote(u'Paris & Orl\xe9ans', safe="&"),
u'Paris%20&%20Orl%C3%A9ans')
self.assertEquals(urlquote_plus(u'Paris & Orl\xe9ans'),
self.assertEqual(urlquote_plus(u'Paris & Orl\xe9ans'),
u'Paris+%26+Orl%C3%A9ans')
self.assertEquals(urlquote_plus(u'Paris & Orl\xe9ans', safe="&"),
self.assertEqual(urlquote_plus(u'Paris & Orl\xe9ans', safe="&"),
u'Paris+&+Orl%C3%A9ans')
def test_cookie_date(self):
t = 1167616461.0
self.assertEquals(cookie_date(t), 'Mon, 01-Jan-2007 01:54:21 GMT')
self.assertEqual(cookie_date(t), 'Mon, 01-Jan-2007 01:54:21 GMT')
def test_http_date(self):
t = 1167616461.0
self.assertEquals(http_date(t), 'Mon, 01 Jan 2007 01:54:21 GMT')
self.assertEqual(http_date(t), 'Mon, 01 Jan 2007 01:54:21 GMT')
def test_iri_to_uri(self):
self.assertEquals(iri_to_uri(u'red%09ros\xe9#red'),
self.assertEqual(iri_to_uri(u'red%09ros\xe9#red'),
'red%09ros%C3%A9#red')
self.assertEquals(iri_to_uri(u'/blog/for/J\xfcrgen M\xfcnster/'),
self.assertEqual(iri_to_uri(u'/blog/for/J\xfcrgen M\xfcnster/'),
'/blog/for/J%C3%BCrgen%20M%C3%BCnster/')
self.assertEquals(iri_to_uri(u'locations/%s' % urlquote_plus(u'Paris & Orl\xe9ans')),
self.assertEqual(iri_to_uri(u'locations/%s' % urlquote_plus(u'Paris & Orl\xe9ans')),
'locations/Paris+%26+Orl%C3%A9ans')
def test_iri_to_uri_idempotent(self):
self.assertEquals(iri_to_uri(iri_to_uri(u'red%09ros\xe9#red')),
self.assertEqual(iri_to_uri(iri_to_uri(u'red%09ros\xe9#red')),
'red%09ros%C3%A9#red')

View File

@ -122,7 +122,7 @@ class TestTransactionClosing(TransactionTestCase):
try:
# Check that the record is in the DB
obj = Mod.objects.get(pk=1)
self.assertEquals(obj.fld, 2)
self.assertEqual(obj.fld, 2)
except Mod.DoesNotExist:
self.fail("After ending a transaction, cursor use no longer sets dirty")

View File

@ -161,7 +161,7 @@ class URLPatternReverse(TestCase):
except NoReverseMatch, e:
self.assertEqual(expected, NoReverseMatch)
else:
self.assertEquals(got, expected)
self.assertEqual(got, expected)
def test_reverse_none(self):
# Reversing None should raise an error, not return the last un-named view.
@ -228,11 +228,11 @@ class ReverseShortcutTests(TestCase):
return "/hi-there/"
res = redirect(FakeObj())
self.assert_(isinstance(res, HttpResponseRedirect))
self.assertTrue(isinstance(res, HttpResponseRedirect))
self.assertEqual(res['Location'], '/hi-there/')
res = redirect(FakeObj(), permanent=True)
self.assert_(isinstance(res, HttpResponsePermanentRedirect))
self.assertTrue(isinstance(res, HttpResponsePermanentRedirect))
self.assertEqual(res['Location'], '/hi-there/')
def test_redirect_to_view_name(self):
@ -279,67 +279,67 @@ class NamespaceTests(TestCase):
def test_normal_name(self):
"Normal lookups work as expected"
self.assertEquals('/normal/', reverse('normal-view'))
self.assertEquals('/normal/37/42/', reverse('normal-view', args=[37,42]))
self.assertEquals('/normal/42/37/', reverse('normal-view', kwargs={'arg1':42, 'arg2':37}))
self.assertEqual('/normal/', reverse('normal-view'))
self.assertEqual('/normal/37/42/', reverse('normal-view', args=[37,42]))
self.assertEqual('/normal/42/37/', reverse('normal-view', kwargs={'arg1':42, 'arg2':37}))
def test_simple_included_name(self):
"Normal lookups work on names included from other patterns"
self.assertEquals('/included/normal/', reverse('inc-normal-view'))
self.assertEquals('/included/normal/37/42/', reverse('inc-normal-view', args=[37,42]))
self.assertEquals('/included/normal/42/37/', reverse('inc-normal-view', kwargs={'arg1':42, 'arg2':37}))
self.assertEqual('/included/normal/', reverse('inc-normal-view'))
self.assertEqual('/included/normal/37/42/', reverse('inc-normal-view', args=[37,42]))
self.assertEqual('/included/normal/42/37/', reverse('inc-normal-view', kwargs={'arg1':42, 'arg2':37}))
def test_namespace_object(self):
"Dynamic URL objects can be found using a namespace"
self.assertEquals('/test1/inner/', reverse('test-ns1:urlobject-view'))
self.assertEquals('/test1/inner/37/42/', reverse('test-ns1:urlobject-view', args=[37,42]))
self.assertEquals('/test1/inner/42/37/', reverse('test-ns1:urlobject-view', kwargs={'arg1':42, 'arg2':37}))
self.assertEqual('/test1/inner/', reverse('test-ns1:urlobject-view'))
self.assertEqual('/test1/inner/37/42/', reverse('test-ns1:urlobject-view', args=[37,42]))
self.assertEqual('/test1/inner/42/37/', reverse('test-ns1:urlobject-view', kwargs={'arg1':42, 'arg2':37}))
def test_embedded_namespace_object(self):
"Namespaces can be installed anywhere in the URL pattern tree"
self.assertEquals('/included/test3/inner/', reverse('test-ns3:urlobject-view'))
self.assertEquals('/included/test3/inner/37/42/', reverse('test-ns3:urlobject-view', args=[37,42]))
self.assertEquals('/included/test3/inner/42/37/', reverse('test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37}))
self.assertEqual('/included/test3/inner/', reverse('test-ns3:urlobject-view'))
self.assertEqual('/included/test3/inner/37/42/', reverse('test-ns3:urlobject-view', args=[37,42]))
self.assertEqual('/included/test3/inner/42/37/', reverse('test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37}))
def test_namespace_pattern(self):
"Namespaces can be applied to include()'d urlpatterns"
self.assertEquals('/ns-included1/normal/', reverse('inc-ns1:inc-normal-view'))
self.assertEquals('/ns-included1/normal/37/42/', reverse('inc-ns1:inc-normal-view', args=[37,42]))
self.assertEquals('/ns-included1/normal/42/37/', reverse('inc-ns1:inc-normal-view', kwargs={'arg1':42, 'arg2':37}))
self.assertEqual('/ns-included1/normal/', reverse('inc-ns1:inc-normal-view'))
self.assertEqual('/ns-included1/normal/37/42/', reverse('inc-ns1:inc-normal-view', args=[37,42]))
self.assertEqual('/ns-included1/normal/42/37/', reverse('inc-ns1:inc-normal-view', kwargs={'arg1':42, 'arg2':37}))
def test_multiple_namespace_pattern(self):
"Namespaces can be embedded"
self.assertEquals('/ns-included1/test3/inner/', reverse('inc-ns1:test-ns3:urlobject-view'))
self.assertEquals('/ns-included1/test3/inner/37/42/', reverse('inc-ns1:test-ns3:urlobject-view', args=[37,42]))
self.assertEquals('/ns-included1/test3/inner/42/37/', reverse('inc-ns1:test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37}))
self.assertEqual('/ns-included1/test3/inner/', reverse('inc-ns1:test-ns3:urlobject-view'))
self.assertEqual('/ns-included1/test3/inner/37/42/', reverse('inc-ns1:test-ns3:urlobject-view', args=[37,42]))
self.assertEqual('/ns-included1/test3/inner/42/37/', reverse('inc-ns1:test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37}))
def test_nested_namespace_pattern(self):
"Namespaces can be nested"
self.assertEquals('/ns-included1/ns-included4/ns-included1/test3/inner/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view'))
self.assertEquals('/ns-included1/ns-included4/ns-included1/test3/inner/37/42/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', args=[37,42]))
self.assertEquals('/ns-included1/ns-included4/ns-included1/test3/inner/42/37/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37}))
self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view'))
self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/37/42/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', args=[37,42]))
self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/42/37/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37}))
def test_app_lookup_object(self):
"A default application namespace can be used for lookup"
self.assertEquals('/default/inner/', reverse('testapp:urlobject-view'))
self.assertEquals('/default/inner/37/42/', reverse('testapp:urlobject-view', args=[37,42]))
self.assertEquals('/default/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1':42, 'arg2':37}))
self.assertEqual('/default/inner/', reverse('testapp:urlobject-view'))
self.assertEqual('/default/inner/37/42/', reverse('testapp:urlobject-view', args=[37,42]))
self.assertEqual('/default/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1':42, 'arg2':37}))
def test_app_lookup_object_with_default(self):
"A default application namespace is sensitive to the 'current' app can be used for lookup"
self.assertEquals('/included/test3/inner/', reverse('testapp:urlobject-view', current_app='test-ns3'))
self.assertEquals('/included/test3/inner/37/42/', reverse('testapp:urlobject-view', args=[37,42], current_app='test-ns3'))
self.assertEquals('/included/test3/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1':42, 'arg2':37}, current_app='test-ns3'))
self.assertEqual('/included/test3/inner/', reverse('testapp:urlobject-view', current_app='test-ns3'))
self.assertEqual('/included/test3/inner/37/42/', reverse('testapp:urlobject-view', args=[37,42], current_app='test-ns3'))
self.assertEqual('/included/test3/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1':42, 'arg2':37}, current_app='test-ns3'))
def test_app_lookup_object_without_default(self):
"An application namespace without a default is sensitive to the 'current' app can be used for lookup"
self.assertEquals('/other2/inner/', reverse('nodefault:urlobject-view'))
self.assertEquals('/other2/inner/37/42/', reverse('nodefault:urlobject-view', args=[37,42]))
self.assertEquals('/other2/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1':42, 'arg2':37}))
self.assertEqual('/other2/inner/', reverse('nodefault:urlobject-view'))
self.assertEqual('/other2/inner/37/42/', reverse('nodefault:urlobject-view', args=[37,42]))
self.assertEqual('/other2/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1':42, 'arg2':37}))
self.assertEquals('/other1/inner/', reverse('nodefault:urlobject-view', current_app='other-ns1'))
self.assertEquals('/other1/inner/37/42/', reverse('nodefault:urlobject-view', args=[37,42], current_app='other-ns1'))
self.assertEquals('/other1/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1':42, 'arg2':37}, current_app='other-ns1'))
self.assertEqual('/other1/inner/', reverse('nodefault:urlobject-view', current_app='other-ns1'))
self.assertEqual('/other1/inner/37/42/', reverse('nodefault:urlobject-view', args=[37,42], current_app='other-ns1'))
self.assertEqual('/other1/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1':42, 'arg2':37}, current_app='other-ns1'))
class RequestURLconfTests(TestCase):
def setUp(self):
@ -408,7 +408,7 @@ class DefaultErrorHandlerTests(TestCase):
"If the urls.py doesn't specify handlers, the defaults are used"
try:
response = self.client.get('/test/')
self.assertEquals(response.status_code, 404)
self.assertEqual(response.status_code, 404)
except AttributeError:
self.fail("Shouldn't get an AttributeError due to undefined 404 handler")
@ -446,6 +446,6 @@ class ResolverMatchTests(TestCase):
self.assertEqual(match.func, func)
# ... and for legacy purposes:
self.assertEquals(match[0], func)
self.assertEquals(match[1], args)
self.assertEquals(match[2], kwargs)
self.assertEqual(match[0], func)
self.assertEqual(match[1], args)
self.assertEqual(match[2], kwargs)

View File

@ -32,19 +32,19 @@ class SortedDictTests(DatastructuresTestCase):
self.d2[7] = 'seven'
def test_basic_methods(self):
self.assertEquals(self.d1.keys(), [7, 1, 9])
self.assertEquals(self.d1.values(), ['seven', 'one', 'nine'])
self.assertEquals(self.d1.items(), [(7, 'seven'), (1, 'one'), (9, 'nine')])
self.assertEqual(self.d1.keys(), [7, 1, 9])
self.assertEqual(self.d1.values(), ['seven', 'one', 'nine'])
self.assertEqual(self.d1.items(), [(7, 'seven'), (1, 'one'), (9, 'nine')])
def test_overwrite_ordering(self):
""" Overwriting an item keeps it's place. """
self.d1[1] = 'ONE'
self.assertEquals(self.d1.values(), ['seven', 'ONE', 'nine'])
self.assertEqual(self.d1.values(), ['seven', 'ONE', 'nine'])
def test_append_items(self):
""" New items go to the end. """
self.d1[0] = 'nil'
self.assertEquals(self.d1.keys(), [7, 1, 9, 0])
self.assertEqual(self.d1.keys(), [7, 1, 9, 0])
def test_delete_and_insert(self):
"""
@ -52,9 +52,9 @@ class SortedDictTests(DatastructuresTestCase):
at the end.
"""
del self.d2[7]
self.assertEquals(self.d2.keys(), [1, 9, 0])
self.assertEqual(self.d2.keys(), [1, 9, 0])
self.d2[7] = 'lucky number 7'
self.assertEquals(self.d2.keys(), [1, 9, 0, 7])
self.assertEqual(self.d2.keys(), [1, 9, 0, 7])
def test_change_keys(self):
"""
@ -63,7 +63,7 @@ class SortedDictTests(DatastructuresTestCase):
"""
k = self.d2.keys()
k.remove(9)
self.assertEquals(self.d2.keys(), [1, 9, 0, 7])
self.assertEqual(self.d2.keys(), [1, 9, 0, 7])
def test_init_keys(self):
"""
@ -75,13 +75,13 @@ class SortedDictTests(DatastructuresTestCase):
tuples = ((2, 'two'), (1, 'one'), (2, 'second-two'))
d = SortedDict(tuples)
self.assertEquals(d.keys(), [2, 1])
self.assertEqual(d.keys(), [2, 1])
real_dict = dict(tuples)
self.assertEquals(sorted(real_dict.values()), ['one', 'second-two'])
self.assertEqual(sorted(real_dict.values()), ['one', 'second-two'])
# Here the order of SortedDict values *is* what we are testing
self.assertEquals(d.values(), ['second-two', 'one'])
self.assertEqual(d.values(), ['second-two', 'one'])
def test_overwrite(self):
self.d1[1] = 'not one'
@ -90,39 +90,39 @@ class SortedDictTests(DatastructuresTestCase):
def test_append(self):
self.d1[13] = 'thirteen'
self.assertEquals(
self.assertEqual(
repr(self.d1),
"{7: 'seven', 1: 'one', 9: 'nine', 13: 'thirteen'}"
)
def test_pop(self):
self.assertEquals(self.d1.pop(1, 'missing'), 'one')
self.assertEquals(self.d1.pop(1, 'missing'), 'missing')
self.assertEqual(self.d1.pop(1, 'missing'), 'one')
self.assertEqual(self.d1.pop(1, 'missing'), 'missing')
# We don't know which item will be popped in popitem(), so we'll
# just check that the number of keys has decreased.
l = len(self.d1)
self.d1.popitem()
self.assertEquals(l - len(self.d1), 1)
self.assertEqual(l - len(self.d1), 1)
def test_dict_equality(self):
d = SortedDict((i, i) for i in xrange(3))
self.assertEquals(d, {0: 0, 1: 1, 2: 2})
self.assertEqual(d, {0: 0, 1: 1, 2: 2})
def test_tuple_init(self):
d = SortedDict(((1, "one"), (0, "zero"), (2, "two")))
self.assertEquals(repr(d), "{1: 'one', 0: 'zero', 2: 'two'}")
self.assertEqual(repr(d), "{1: 'one', 0: 'zero', 2: 'two'}")
def test_pickle(self):
self.assertEquals(
self.assertEqual(
pickle.loads(pickle.dumps(self.d1, 2)),
{7: 'seven', 1: 'one', 9: 'nine'}
)
def test_clear(self):
self.d1.clear()
self.assertEquals(self.d1, {})
self.assertEquals(self.d1.keyOrder, [])
self.assertEqual(self.d1, {})
self.assertEqual(self.d1.keyOrder, [])
class MergeDictTests(DatastructuresTestCase):
@ -140,12 +140,12 @@ class MergeDictTests(DatastructuresTestCase):
md = MergeDict(d1, d2, d3)
self.assertEquals(md['chris'], 'cool')
self.assertEquals(md['camri'], 'cute')
self.assertEquals(md['twoofme'], 'firstone')
self.assertEqual(md['chris'], 'cool')
self.assertEqual(md['camri'], 'cute')
self.assertEqual(md['twoofme'], 'firstone')
md2 = md.copy()
self.assertEquals(md2['chris'], 'cool')
self.assertEqual(md2['chris'], 'cool')
def test_mergedict_merges_multivaluedict(self):
""" MergeDict can merge MultiValueDicts """
@ -160,20 +160,20 @@ class MergeDictTests(DatastructuresTestCase):
# Although 'key2' appears in both dictionaries,
# only the first value is used.
self.assertEquals(mm.getlist('key2'), ['value2', 'value3'])
self.assertEquals(mm.getlist('key4'), ['value5', 'value6'])
self.assertEquals(mm.getlist('undefined'), [])
self.assertEqual(mm.getlist('key2'), ['value2', 'value3'])
self.assertEqual(mm.getlist('key4'), ['value5', 'value6'])
self.assertEqual(mm.getlist('undefined'), [])
self.assertEquals(sorted(mm.keys()), ['key1', 'key2', 'key4'])
self.assertEquals(len(mm.values()), 3)
self.assertEqual(sorted(mm.keys()), ['key1', 'key2', 'key4'])
self.assertEqual(len(mm.values()), 3)
self.assertTrue('value1' in mm.values())
self.assertEquals(sorted(mm.items(), key=lambda k: k[0]),
self.assertEqual(sorted(mm.items(), key=lambda k: k[0]),
[('key1', 'value1'), ('key2', 'value3'),
('key4', 'value6')])
self.assertEquals([(k,mm.getlist(k)) for k in sorted(mm)],
self.assertEqual([(k,mm.getlist(k)) for k in sorted(mm)],
[('key1', ['value1']),
('key2', ['value2', 'value3']),
('key4', ['value5', 'value6'])])
@ -184,13 +184,13 @@ class MultiValueDictTests(DatastructuresTestCase):
d = MultiValueDict({'name': ['Adrian', 'Simon'],
'position': ['Developer']})
self.assertEquals(d['name'], 'Simon')
self.assertEquals(d.get('name'), 'Simon')
self.assertEquals(d.getlist('name'), ['Adrian', 'Simon'])
self.assertEquals(list(d.iteritems()),
self.assertEqual(d['name'], 'Simon')
self.assertEqual(d.get('name'), 'Simon')
self.assertEqual(d.getlist('name'), ['Adrian', 'Simon'])
self.assertEqual(list(d.iteritems()),
[('position', 'Developer'), ('name', 'Simon')])
self.assertEquals(list(d.iterlists()),
self.assertEqual(list(d.iterlists()),
[('position', ['Developer']),
('name', ['Adrian', 'Simon'])])
@ -202,14 +202,14 @@ class MultiValueDictTests(DatastructuresTestCase):
' [\'Developer\'], \'name\': [\'Adrian\', \'Simon\']}>"',
d.__getitem__, 'lastname')
self.assertEquals(d.get('lastname'), None)
self.assertEquals(d.get('lastname', 'nonexistent'), 'nonexistent')
self.assertEquals(d.getlist('lastname'), [])
self.assertEqual(d.get('lastname'), None)
self.assertEqual(d.get('lastname', 'nonexistent'), 'nonexistent')
self.assertEqual(d.getlist('lastname'), [])
d.setlist('lastname', ['Holovaty', 'Willison'])
self.assertEquals(d.getlist('lastname'), ['Holovaty', 'Willison'])
self.assertEquals(d.values(), ['Developer', 'Simon', 'Willison'])
self.assertEquals(list(d.itervalues()),
self.assertEqual(d.getlist('lastname'), ['Holovaty', 'Willison'])
self.assertEqual(d.values(), ['Developer', 'Simon', 'Willison'])
self.assertEqual(list(d.itervalues()),
['Developer', 'Simon', 'Willison'])
def test_copy(self):
@ -242,9 +242,9 @@ class DotExpandedDictTests(DatastructuresTestCase):
'person.2.firstname': ['Adrian'],
'person.2.lastname': ['Holovaty']})
self.assertEquals(d['person']['1']['lastname'], ['Willison'])
self.assertEquals(d['person']['2']['lastname'], ['Holovaty'])
self.assertEquals(d['person']['2']['firstname'], ['Adrian'])
self.assertEqual(d['person']['1']['lastname'], ['Willison'])
self.assertEqual(d['person']['2']['lastname'], ['Holovaty'])
self.assertEqual(d['person']['2']['firstname'], ['Adrian'])
class ImmutableListTests(DatastructuresTestCase):
@ -256,12 +256,12 @@ class ImmutableListTests(DatastructuresTestCase):
self.assertRaisesErrorWithMessage(AttributeError,
'ImmutableList object is immutable.', d.sort)
self.assertEquals(repr(d), '(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)')
self.assertEqual(repr(d), '(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)')
def test_custom_warning(self):
d = ImmutableList(range(10), warning="Object is immutable!")
self.assertEquals(d[1], 1)
self.assertEqual(d[1], 1)
# AttributeError: Object is immutable!
self.assertRaisesErrorWithMessage(AttributeError,
@ -273,5 +273,5 @@ class DictWrapperTests(DatastructuresTestCase):
def test_dictwrapper(self):
f = lambda x: "*%s" % x
d = DictWrapper({'a': 'a'}, f, 'xx_')
self.assertEquals("Normal: %(a)s. Modified: %(xx_a)s" % d,
self.assertEqual("Normal: %(a)s. Modified: %(xx_a)s" % d,
'Normal: a. Modified: *a')

View File

@ -33,82 +33,82 @@ class DateFormatTests(unittest.TestCase):
def test_date(self):
d = date(2009, 5, 16)
self.assertEquals(date.fromtimestamp(int(format(d, 'U'))), d)
self.assertEqual(date.fromtimestamp(int(format(d, 'U'))), d)
def test_naive_datetime(self):
dt = datetime(2009, 5, 16, 5, 30, 30)
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U'))), dt)
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U'))), dt)
def test_datetime_with_local_tzinfo(self):
ltz = LocalTimezone(datetime.now())
dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=ltz)
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U'))), dt.replace(tzinfo=None))
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U'))), dt.replace(tzinfo=None))
def test_datetime_with_tzinfo(self):
tz = FixedOffset(-510)
ltz = LocalTimezone(datetime.now())
dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=tz)
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U')), tz), dt)
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U'))), dt.astimezone(ltz).replace(tzinfo=None))
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U')), tz).utctimetuple(), dt.utctimetuple())
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U')), ltz).utctimetuple(), dt.utctimetuple())
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), tz), dt)
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U'))), dt.astimezone(ltz).replace(tzinfo=None))
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), tz).utctimetuple(), dt.utctimetuple())
self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz).utctimetuple(), dt.utctimetuple())
def test_epoch(self):
utc = FixedOffset(0)
udt = datetime(1970, 1, 1, tzinfo=utc)
self.assertEquals(format(udt, 'U'), u'0')
self.assertEqual(format(udt, 'U'), u'0')
def test_empty_format(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
self.assertEquals(dateformat.format(my_birthday, ''), u'')
self.assertEqual(dateformat.format(my_birthday, ''), u'')
def test_am_pm(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
self.assertEquals(dateformat.format(my_birthday, 'a'), u'p.m.')
self.assertEqual(dateformat.format(my_birthday, 'a'), u'p.m.')
def test_date_formats(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456)
self.assertEquals(dateformat.format(my_birthday, 'A'), u'PM')
self.assertEquals(dateformat.format(timestamp, 'c'), u'2008-05-19T11:45:23.123456')
self.assertEquals(dateformat.format(my_birthday, 'd'), u'08')
self.assertEquals(dateformat.format(my_birthday, 'j'), u'8')
self.assertEquals(dateformat.format(my_birthday, 'l'), u'Sunday')
self.assertEquals(dateformat.format(my_birthday, 'L'), u'False')
self.assertEquals(dateformat.format(my_birthday, 'm'), u'07')
self.assertEquals(dateformat.format(my_birthday, 'M'), u'Jul')
self.assertEquals(dateformat.format(my_birthday, 'b'), u'jul')
self.assertEquals(dateformat.format(my_birthday, 'n'), u'7')
self.assertEquals(dateformat.format(my_birthday, 'N'), u'July')
self.assertEqual(dateformat.format(my_birthday, 'A'), u'PM')
self.assertEqual(dateformat.format(timestamp, 'c'), u'2008-05-19T11:45:23.123456')
self.assertEqual(dateformat.format(my_birthday, 'd'), u'08')
self.assertEqual(dateformat.format(my_birthday, 'j'), u'8')
self.assertEqual(dateformat.format(my_birthday, 'l'), u'Sunday')
self.assertEqual(dateformat.format(my_birthday, 'L'), u'False')
self.assertEqual(dateformat.format(my_birthday, 'm'), u'07')
self.assertEqual(dateformat.format(my_birthday, 'M'), u'Jul')
self.assertEqual(dateformat.format(my_birthday, 'b'), u'jul')
self.assertEqual(dateformat.format(my_birthday, 'n'), u'7')
self.assertEqual(dateformat.format(my_birthday, 'N'), u'July')
def test_time_formats(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
self.assertEquals(dateformat.format(my_birthday, 'P'), u'10 p.m.')
self.assertEquals(dateformat.format(my_birthday, 's'), u'00')
self.assertEquals(dateformat.format(my_birthday, 'S'), u'th')
self.assertEquals(dateformat.format(my_birthday, 't'), u'31')
self.assertEquals(dateformat.format(my_birthday, 'w'), u'0')
self.assertEquals(dateformat.format(my_birthday, 'W'), u'27')
self.assertEquals(dateformat.format(my_birthday, 'y'), u'79')
self.assertEquals(dateformat.format(my_birthday, 'Y'), u'1979')
self.assertEquals(dateformat.format(my_birthday, 'z'), u'189')
self.assertEqual(dateformat.format(my_birthday, 'P'), u'10 p.m.')
self.assertEqual(dateformat.format(my_birthday, 's'), u'00')
self.assertEqual(dateformat.format(my_birthday, 'S'), u'th')
self.assertEqual(dateformat.format(my_birthday, 't'), u'31')
self.assertEqual(dateformat.format(my_birthday, 'w'), u'0')
self.assertEqual(dateformat.format(my_birthday, 'W'), u'27')
self.assertEqual(dateformat.format(my_birthday, 'y'), u'79')
self.assertEqual(dateformat.format(my_birthday, 'Y'), u'1979')
self.assertEqual(dateformat.format(my_birthday, 'z'), u'189')
def test_dateformat(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
self.assertEquals(dateformat.format(my_birthday, r'Y z \C\E\T'), u'1979 189 CET')
self.assertEqual(dateformat.format(my_birthday, r'Y z \C\E\T'), u'1979 189 CET')
self.assertEquals(dateformat.format(my_birthday, r'jS o\f F'), u'8th of July')
self.assertEqual(dateformat.format(my_birthday, r'jS o\f F'), u'8th of July')
def test_futuredates(self):
the_future = datetime(2100, 10, 25, 0, 00)
self.assertEquals(dateformat.format(the_future, r'Y'), u'2100')
self.assertEqual(dateformat.format(the_future, r'Y'), u'2100')
def test_timezones(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
@ -117,13 +117,13 @@ class DateFormatTests(unittest.TestCase):
timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456)
if self.tz_tests:
self.assertEquals(dateformat.format(my_birthday, 'O'), u'+0100')
self.assertEquals(dateformat.format(my_birthday, 'r'), u'Sun, 8 Jul 1979 22:00:00 +0100')
self.assertEquals(dateformat.format(my_birthday, 'T'), u'CET')
self.assertEquals(dateformat.format(my_birthday, 'U'), u'300315600')
self.assertEquals(dateformat.format(timestamp, 'u'), u'123456')
self.assertEquals(dateformat.format(my_birthday, 'Z'), u'3600')
self.assertEquals(dateformat.format(summertime, 'I'), u'1')
self.assertEquals(dateformat.format(summertime, 'O'), u'+0200')
self.assertEquals(dateformat.format(wintertime, 'I'), u'0')
self.assertEquals(dateformat.format(wintertime, 'O'), u'+0100')
self.assertEqual(dateformat.format(my_birthday, 'O'), u'+0100')
self.assertEqual(dateformat.format(my_birthday, 'r'), u'Sun, 8 Jul 1979 22:00:00 +0100')
self.assertEqual(dateformat.format(my_birthday, 'T'), u'CET')
self.assertEqual(dateformat.format(my_birthday, 'U'), u'300315600')
self.assertEqual(dateformat.format(timestamp, 'u'), u'123456')
self.assertEqual(dateformat.format(my_birthday, 'Z'), u'3600')
self.assertEqual(dateformat.format(summertime, 'I'), u'1')
self.assertEqual(dateformat.format(summertime, 'O'), u'+0200')
self.assertEqual(dateformat.format(wintertime, 'I'), u'0')
self.assertEqual(dateformat.format(wintertime, 'O'), u'+0100')

View File

@ -21,17 +21,17 @@ class DatetimeTests(unittest.TestCase):
self.assertEqual(original_datetime(*self.just_safe).strftime('%Y-%m-%d'), datetime(*self.just_safe).strftime('%Y-%m-%d'))
def test_safe_strftime(self):
self.assertEquals(date(*self.just_unsafe[:3]).strftime('%Y-%m-%d (weekday %w)'), '1899-12-31 (weekday 0)')
self.assertEquals(date(*self.just_safe).strftime('%Y-%m-%d (weekday %w)'), '1900-01-01 (weekday 1)')
self.assertEqual(date(*self.just_unsafe[:3]).strftime('%Y-%m-%d (weekday %w)'), '1899-12-31 (weekday 0)')
self.assertEqual(date(*self.just_safe).strftime('%Y-%m-%d (weekday %w)'), '1900-01-01 (weekday 1)')
self.assertEquals(datetime(*self.just_unsafe).strftime('%Y-%m-%d %H:%M:%S (weekday %w)'), '1899-12-31 23:59:59 (weekday 0)')
self.assertEquals(datetime(*self.just_safe).strftime('%Y-%m-%d %H:%M:%S (weekday %w)'), '1900-01-01 00:00:00 (weekday 1)')
self.assertEqual(datetime(*self.just_unsafe).strftime('%Y-%m-%d %H:%M:%S (weekday %w)'), '1899-12-31 23:59:59 (weekday 0)')
self.assertEqual(datetime(*self.just_safe).strftime('%Y-%m-%d %H:%M:%S (weekday %w)'), '1900-01-01 00:00:00 (weekday 1)')
# %y will error before this date
self.assertEquals(date(*self.just_safe).strftime('%y'), '00')
self.assertEquals(datetime(*self.just_safe).strftime('%y'), '00')
self.assertEqual(date(*self.just_safe).strftime('%y'), '00')
self.assertEqual(datetime(*self.just_safe).strftime('%y'), '00')
self.assertEquals(date(1850, 8, 2).strftime("%Y/%m/%d was a %A"), '1850/08/02 was a Friday')
self.assertEqual(date(1850, 8, 2).strftime("%Y/%m/%d was a %A"), '1850/08/02 was a Friday')
def test_zero_padding(self):
"""
@ -39,4 +39,4 @@ class DatetimeTests(unittest.TestCase):
Check that pre-1000AD dates are padded with zeros if necessary
"""
self.assertEquals(date(1, 1, 1).strftime("%Y/%m/%d was a %A"), '0001/01/01 was a Monday')
self.assertEqual(date(1, 1, 1).strftime("%Y/%m/%d was a %A"), '0001/01/01 was a Monday')

View File

@ -46,7 +46,7 @@ class TestUtilsSimpleLazyObject(unittest.TestCase):
# For debugging, it will really confuse things if there is no clue that
# SimpleLazyObject is actually a proxy object. So we don't
# proxy __repr__
self.assert_("SimpleLazyObject" in repr(SimpleLazyObject(complex_object)))
self.assertTrue("SimpleLazyObject" in repr(SimpleLazyObject(complex_object)))
def test_str(self):
self.assertEqual("I am _ComplexObject('joe')", str(SimpleLazyObject(complex_object)))

Some files were not shown because too many files have changed in this diff Show More