Fixed #23620 -- Used more specific assertions in the Django test suite.

This commit is contained in:
Berker Peksag 2014-10-28 12:02:56 +02:00 committed by Tim Graham
parent c0c78f1b70
commit f7969b0920
83 changed files with 419 additions and 429 deletions

View File

@ -45,10 +45,10 @@ class PermWrapperTests(TestCase):
"""
perms = PermWrapper(MockUser())
# Works for modules and full permissions.
self.assertTrue('mockapp' in perms)
self.assertFalse('nonexisting' in perms)
self.assertTrue('mockapp.someperm' in perms)
self.assertFalse('mockapp.nonexisting' in perms)
self.assertIn('mockapp', perms)
self.assertNotIn('nonexisting', perms)
self.assertIn('mockapp.someperm', perms)
self.assertNotIn('mockapp.nonexisting', perms)
def test_permlookupdict_in(self):
"""

View File

@ -42,7 +42,7 @@ class LoginRequiredTestCase(AuthViewsTestCase):
login_url = settings.LOGIN_URL
response = self.client.get(view_url)
self.assertEqual(response.status_code, 302)
self.assertTrue(login_url in response.url)
self.assertIn(login_url, response.url)
self.login()
response = self.client.get(view_url)
self.assertEqual(response.status_code, 200)

View File

@ -29,7 +29,7 @@ class ModWsgiHandlerTestCase(TransactionTestCase):
User.objects.create_user('test', 'test@example.com', 'test')
# User not in database
self.assertTrue(check_password({}, 'unknown', '') is None)
self.assertIsNone(check_password({}, 'unknown', ''))
# Valid user with correct password
self.assertTrue(check_password({}, 'test', 'test'))
@ -53,7 +53,7 @@ class ModWsgiHandlerTestCase(TransactionTestCase):
CustomUser._default_manager.create_user('test@example.com', '1990-01-01', 'test')
# User not in database
self.assertTrue(check_password({}, 'unknown', '') is None)
self.assertIsNone(check_password({}, 'unknown', ''))
# Valid user with correct password'
self.assertTrue(check_password({}, 'test@example.com', 'test'))

View File

@ -44,7 +44,7 @@ class SignalTestCase(TestCase):
self.assertEqual(len(self.login_failed), 1)
self.assertEqual(self.login_failed[0]['username'], 'testclient')
# verify the password is cleansed
self.assertTrue('***' in self.login_failed[0]['password'])
self.assertIn('***', self.login_failed[0]['password'])
# Like this:
self.client.login(username='testclient', password='password')

View File

@ -55,13 +55,13 @@ class AuthViewsTestCase(TestCase):
'username': username,
'password': password,
})
self.assertTrue(SESSION_KEY in self.client.session)
self.assertIn(SESSION_KEY, self.client.session)
return response
def logout(self):
response = self.client.get('/admin/logout/')
self.assertEqual(response.status_code, 200)
self.assertTrue(SESSION_KEY not in self.client.session)
self.assertNotIn(SESSION_KEY, self.client.session)
def assertFormError(self, response, error):
"""Assert that error is found in response.context['form'] errors"""
@ -129,7 +129,7 @@ class PasswordResetTest(AuthViewsTestCase):
response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
self.assertTrue("http://" in mail.outbox[0].body)
self.assertIn("http://", mail.outbox[0].body)
self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email)
# optional multipart text/html email has been added. Make sure original,
# default functionality is 100% the same
@ -148,8 +148,8 @@ class PasswordResetTest(AuthViewsTestCase):
self.assertTrue(message.is_multipart())
self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain')
self.assertEqual(message.get_payload(1).get_content_type(), 'text/html')
self.assertTrue('<html>' not in message.get_payload(0).get_payload())
self.assertTrue('<html>' in message.get_payload(1).get_payload())
self.assertNotIn('<html>', message.get_payload(0).get_payload())
self.assertIn('<html>', message.get_payload(1).get_payload())
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."
@ -169,7 +169,7 @@ class PasswordResetTest(AuthViewsTestCase):
)
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
self.assertTrue("http://adminsite.com" in mail.outbox[0].body)
self.assertIn("http://adminsite.com", mail.outbox[0].body)
self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email)
# Skip any 500 handler action (like sending more mail...)
@ -215,7 +215,7 @@ class PasswordResetTest(AuthViewsTestCase):
def _read_signup_email(self, email):
urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
self.assertTrue(urlmatch is not None, "No URL found in sent email")
self.assertIsNotNone(urlmatch, "No URL found in sent email")
return urlmatch.group(), urlmatch.groups()[0]
def test_confirm_valid(self):
@ -346,7 +346,7 @@ class CustomUserPasswordResetTest(AuthViewsTestCase):
def _read_signup_email(self, email):
urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
self.assertTrue(urlmatch is not None, "No URL found in sent email")
self.assertIsNotNone(urlmatch, "No URL found in sent email")
return urlmatch.group(), urlmatch.groups()[0]
def test_confirm_valid_custom_user(self):
@ -502,7 +502,7 @@ class LoginTest(AuthViewsTestCase):
'password': password,
})
self.assertEqual(response.status_code, 302)
self.assertFalse(bad_url in response.url,
self.assertNotIn(bad_url, response.url,
"%s should be blocked" % bad_url)
# These URLs *should* still pass the security check
@ -524,8 +524,7 @@ class LoginTest(AuthViewsTestCase):
'password': password,
})
self.assertEqual(response.status_code, 302)
self.assertTrue(good_url in response.url,
"%s should be allowed" % good_url)
self.assertIn(good_url, response.url, "%s should be allowed" % good_url)
def test_login_form_contains_request(self):
# 15198
@ -683,7 +682,7 @@ class LoginRedirectUrlTest(AuthViewsTestCase):
class LogoutTest(AuthViewsTestCase):
def confirm_logged_out(self):
self.assertTrue(SESSION_KEY not in self.client.session)
self.assertNotIn(SESSION_KEY, self.client.session)
def test_logout_default(self):
"Logout without next_page option renders the default template"
@ -696,7 +695,7 @@ class LogoutTest(AuthViewsTestCase):
# Bug 14377
self.login()
response = self.client.get('/logout/')
self.assertTrue('site' in response.context)
self.assertIn('site', response.context)
def test_logout_with_overridden_redirect_url(self):
# Bug 11223
@ -762,7 +761,7 @@ class LogoutTest(AuthViewsTestCase):
self.login()
response = self.client.get(nasty_url)
self.assertEqual(response.status_code, 302)
self.assertFalse(bad_url in response.url,
self.assertNotIn(bad_url, response.url,
"%s should be blocked" % bad_url)
self.confirm_logged_out()
@ -783,8 +782,7 @@ class LogoutTest(AuthViewsTestCase):
self.login()
response = self.client.get(safe_url)
self.assertEqual(response.status_code, 302)
self.assertTrue(good_url in response.url,
"%s should be allowed" % good_url)
self.assertIn(good_url, response.url, "%s should be allowed" % good_url)
self.confirm_logged_out()
def test_logout_preserve_language(self):

View File

@ -436,17 +436,13 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
def test_polygon_comparison(self):
p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0)))
self.assertTrue(p1 > p2)
self.assertFalse(p1 < p2)
self.assertFalse(p2 > p1)
self.assertTrue(p2 < p1)
self.assertGreater(p1, p2)
self.assertLess(p2, p1)
p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0)))
p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0)))
self.assertFalse(p4 < p3)
self.assertTrue(p3 < p4)
self.assertTrue(p4 > p3)
self.assertFalse(p3 > p4)
self.assertGreater(p4, p3)
self.assertLess(p3, p4)
def test_multipolygons(self):
"Testing MultiPolygon objects."
@ -911,7 +907,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
g1 = g.transform(4326, clone=True)
self.assertEqual(g1.tuple, g.tuple)
self.assertEqual(g1.srid, 4326)
self.assertTrue(g1 is not g, "Clone didn't happen")
self.assertIsNot(g1, g, "Clone didn't happen")
old_has_gdal = gdal.HAS_GDAL
try:
@ -927,7 +923,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
g1 = g.transform(4326, clone=True)
self.assertEqual(g1.tuple, g.tuple)
self.assertEqual(g1.srid, 4326)
self.assertTrue(g1 is not g, "Clone didn't happen")
self.assertIsNot(g1, g, "Clone didn't happen")
finally:
gdal.HAS_GDAL = old_has_gdal

View File

@ -391,35 +391,34 @@ class ListMixinTest(unittest.TestCase):
pl, ul = self.lists_of_len()
self.assertEqual(pl, ul, 'cmp for equal')
self.assertFalse(ul == pl + [2], 'cmp for not equal')
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.assertNotEqual(ul, pl + [2], 'cmp for not equal')
self.assertGreaterEqual(pl, ul, 'cmp for gte self')
self.assertLessEqual(pl, ul, 'cmp for lte self')
self.assertGreaterEqual(ul, pl, 'cmp for self gte')
self.assertLessEqual(ul, pl, 'cmp for self lte')
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')
self.assertGreater(pl + [5], ul, 'cmp')
self.assertGreaterEqual(pl + [5], ul, 'cmp')
self.assertLess(pl, ul + [2], 'cmp')
self.assertLessEqual(pl, ul + [2], 'cmp')
self.assertGreater(ul + [5], pl, 'cmp')
self.assertGreaterEqual(ul + [5], pl, 'cmp')
self.assertLess(ul, pl + [2], 'cmp')
self.assertLessEqual(ul, pl + [2], 'cmp')
# Also works with a custom IndexError
ul_longer = ul + [2]
ul_longer._IndexError = TypeError
ul._IndexError = TypeError
self.assertFalse(ul_longer == pl)
self.assertFalse(ul == ul_longer)
self.assertTrue(ul_longer > ul)
self.assertNotEqual(ul_longer, pl)
self.assertGreater(ul_longer, ul)
pl[1] = 20
self.assertTrue(pl > ul, 'cmp for gt self')
self.assertTrue(ul < pl, 'cmp for self lt')
self.assertGreater(pl, ul, 'cmp for gt self')
self.assertLess(ul, pl, 'cmp for self lt')
pl[1] = -20
self.assertTrue(pl < ul, 'cmp for lt self')
self.assertTrue(pl < ul, 'cmp for lt self')
self.assertLess(pl, ul, 'cmp for lt self')
self.assertGreater(ul, pl, 'cmp for gt self')
class ListMixinTestSingle(ListMixinTest):

View File

@ -228,8 +228,8 @@ class RelatedGeoModelTest(TestCase):
combined = qs1 | qs2
names = [c.name for c in combined]
self.assertEqual(2, len(names))
self.assertTrue('Aurora' in names)
self.assertTrue('Kecksburg' in names)
self.assertIn('Aurora', names)
self.assertIn('Kecksburg', names)
def test11_geoquery_pickle(self):
"Ensuring GeoQuery objects are unpickled correctly. See #10839."

View File

@ -174,7 +174,7 @@ class SpecializedFieldTest(SimpleTestCase):
self.assertFalse(PointForm().is_valid())
invalid = PointForm(data={'p': 'some invalid geom'})
self.assertFalse(invalid.is_valid())
self.assertTrue('Invalid geometry value' in str(invalid.errors))
self.assertIn('Invalid geometry value', str(invalid.errors))
for invalid in [geo for key, geo in self.geometries.items() if key != 'point']:
self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid())

View File

@ -122,9 +122,9 @@ class DistanceTest(unittest.TestCase):
d2 = D(km=1)
d3 = D(km=0)
self.assertTrue(d2 > d1)
self.assertTrue(d1 == d1)
self.assertTrue(d1 < d2)
self.assertGreater(d2, d1)
self.assertEqual(d1, d1)
self.assertLess(d1, d2)
self.assertFalse(d3)
def testUnitsStr(self):
@ -249,9 +249,9 @@ class AreaTest(unittest.TestCase):
a2 = A(sq_km=1)
a3 = A(sq_km=0)
self.assertTrue(a2 > a1)
self.assertTrue(a1 == a1)
self.assertTrue(a1 < a2)
self.assertGreater(a2, a1)
self.assertEqual(a1, a1)
self.assertLess(a1, a2)
self.assertFalse(a3)
def testUnitsStr(self):

View File

@ -163,7 +163,7 @@ class BaseTests(object):
add_url = reverse('add_message', args=(level,))
response = self.client.post(add_url, data, follow=True)
self.assertRedirects(response, show_url)
self.assertTrue('messages' in response.context)
self.assertIn('messages', response.context)
messages = [Message(self.levels[level], msg) for msg in data['messages']]
self.assertEqual(list(response.context['messages']), messages)
for msg in data['messages']:
@ -179,7 +179,7 @@ class BaseTests(object):
add_url = reverse('add_template_response', args=(level,))
response = self.client.post(add_url, data, follow=True)
self.assertRedirects(response, show_url)
self.assertTrue('messages' in response.context)
self.assertIn('messages', response.context)
for msg in data['messages']:
self.assertContains(response, msg)
@ -192,7 +192,7 @@ class BaseTests(object):
show_url = reverse('show_template_response')
response = self.client.get(show_url)
self.assertTrue('DEFAULT_MESSAGE_LEVELS' in response.context)
self.assertIn('DEFAULT_MESSAGE_LEVELS', response.context)
self.assertEqual(response.context['DEFAULT_MESSAGE_LEVELS'], DEFAULT_LEVELS)
@override_settings(MESSAGE_LEVEL=constants.DEBUG)
@ -211,7 +211,7 @@ class BaseTests(object):
add_url = reverse('add_message', args=(level,))
self.client.post(add_url, data)
response = self.client.get(show_url)
self.assertTrue('messages' in response.context)
self.assertIn('messages', response.context)
self.assertEqual(list(response.context['messages']), messages)
for msg in data['messages']:
self.assertContains(response, msg)
@ -255,7 +255,7 @@ class BaseTests(object):
add_url = reverse('add_message', args=(level,))
response = self.client.post(add_url, data, follow=True)
self.assertRedirects(response, show_url)
self.assertFalse('messages' in response.context)
self.assertNotIn('messages', response.context)
def stored_messages_count(self, storage, response):
"""

View File

@ -65,7 +65,7 @@ class CookieTest(BaseTests, TestCase):
response = self.get_response()
storage.add(constants.INFO, 'test')
storage.update(response)
self.assertTrue('test' in response.cookies['messages'].value)
self.assertIn('test', response.cookies['messages'].value)
self.assertEqual(response.cookies['messages']['domain'], '.example.com')
self.assertEqual(response.cookies['messages']['expires'], '')
self.assertEqual(response.cookies['messages']['secure'], True)
@ -114,7 +114,7 @@ class CookieTest(BaseTests, TestCase):
self.assertEqual(cookie_storing, 4)
self.assertEqual(len(unstored_messages), 1)
self.assertTrue(unstored_messages[0].message == '0' * msg_size)
self.assertEqual(unstored_messages[0].message, '0' * msg_size)
def test_json_encoder_decoder(self):
"""

View File

@ -286,7 +286,7 @@ class SessionTestsMixin(object):
self.assertEqual({}, self.session.decode(bad_encode))
# check that the failed decode is logged
self.assertEqual(len(calls), 1)
self.assertTrue('corrupted' in calls[0])
self.assertIn('corrupted', calls[0])
def test_actual_expiry(self):
# this doesn't work with JSONSerializer (serializing timedelta)

View File

@ -93,7 +93,7 @@ class ChangeListTests(TestCase):
table_output = template.render(context)
link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
row_html = '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th><td class="field-parent nowrap">(None)</td></tr></tbody>' % link
self.assertFalse(table_output.find(row_html) == -1,
self.assertNotEqual(table_output.find(row_html), -1,
'Failed to find expected row element: %s' % table_output)
def test_result_list_html(self):
@ -116,7 +116,7 @@ class ChangeListTests(TestCase):
table_output = template.render(context)
link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
row_html = '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th><td class="field-parent nowrap">Parent object</td></tr></tbody>' % link
self.assertFalse(table_output.find(row_html) == -1,
self.assertNotEqual(table_output.find(row_html), -1,
'Failed to find expected row element: %s' % table_output)
def test_result_list_editable_html(self):

View File

@ -130,38 +130,38 @@ class XViewMiddlewareTest(AdminDocsTestCase):
def test_xview_func(self):
user = User.objects.get(username='super')
response = self.client.head('/xview/func/')
self.assertFalse('X-View' in response)
self.assertNotIn('X-View', response)
self.client.login(username='super', password='secret')
response = self.client.head('/xview/func/')
self.assertTrue('X-View' in response)
self.assertIn('X-View', response)
self.assertEqual(response['X-View'], 'admin_docs.views.xview')
user.is_staff = False
user.save()
response = self.client.head('/xview/func/')
self.assertFalse('X-View' in response)
self.assertNotIn('X-View', response)
user.is_staff = True
user.is_active = False
user.save()
response = self.client.head('/xview/func/')
self.assertFalse('X-View' in response)
self.assertNotIn('X-View', response)
def test_xview_class(self):
user = User.objects.get(username='super')
response = self.client.head('/xview/class/')
self.assertFalse('X-View' in response)
self.assertNotIn('X-View', response)
self.client.login(username='super', password='secret')
response = self.client.head('/xview/class/')
self.assertTrue('X-View' in response)
self.assertIn('X-View', response)
self.assertEqual(response['X-View'], 'admin_docs.views.XViewClass')
user.is_staff = False
user.save()
response = self.client.head('/xview/class/')
self.assertFalse('X-View' in response)
self.assertNotIn('X-View', response)
user.is_staff = True
user.is_active = False
user.save()
response = self.client.head('/xview/class/')
self.assertFalse('X-View' in response)
self.assertNotIn('X-View', response)
@unittest.skipUnless(utils.docutils_is_available, "no docutils installed.")

View File

@ -190,12 +190,12 @@ class AdminScriptTestCase(unittest.TestCase):
self.assertIsNotNone(re.search(msg, stream),
"'%s' does not match actual output text '%s'" % (msg, stream))
else:
self.assertTrue(msg in stream, "'%s' does not match actual output text '%s'" % (msg, stream))
self.assertIn(msg, stream, "'%s' does not match actual output text '%s'" % (msg, stream))
def assertNotInOutput(self, stream, msg):
"Utility assertion: assert that the given message doesn't exist in the output"
stream = force_text(stream)
self.assertFalse(msg in stream, "'%s' matches actual output text '%s'" % (msg, stream))
self.assertNotIn(msg, stream, "'%s' matches actual output text '%s'" % (msg, stream))
##########################################################################
# DJANGO ADMIN TESTS
@ -904,7 +904,7 @@ class ManageAlternateSettings(AdminScriptTestCase):
out, err = self.run_manage(args)
expected = ('create table %s'
% connection.ops.quote_name('admin_scripts_article'))
self.assertTrue(expected.lower() in out.lower())
self.assertIn(expected.lower(), out.lower())
self.assertNoOutput(err)
def test_builtin_with_environment(self):
@ -913,7 +913,7 @@ class ManageAlternateSettings(AdminScriptTestCase):
out, err = self.run_manage(args, 'alternate_settings')
expected = ('create table %s'
% connection.ops.quote_name('admin_scripts_article'))
self.assertTrue(expected.lower() in out.lower())
self.assertIn(expected.lower(), out.lower())
self.assertNoOutput(err)
def test_builtin_with_bad_settings(self):

View File

@ -90,7 +90,7 @@ class AdminViewBasicTestCase(TestCase):
content.
"""
self.assertEqual(response.status_code, 200)
self.assertTrue(response.content.index(force_bytes(text1)) < response.content.index(force_bytes(text2)),
self.assertLess(response.content.index(force_bytes(text1)), response.content.index(force_bytes(text2)),
failing_msg)
@ -866,7 +866,7 @@ class AdminViewFormUrlTest(TestCase):
Tests whether change_view has form_url in response.context
"""
response = self.client.get('/test_admin/%s/admin_views/section/1/' % self.urlbit)
self.assertTrue('form_url' in response.context, msg='form_url not present in response.context')
self.assertIn('form_url', response.context, msg='form_url not present in response.context')
self.assertEqual(response.context['form_url'], 'pony')
def test_initial_data_can_be_overridden(self):
@ -4123,7 +4123,7 @@ class UserAdminTest(TestCase):
})
self.assertEqual(response.status_code, 200)
adminform = response.context['adminform']
self.assertTrue('password' not in adminform.form.errors)
self.assertNotIn('password', adminform.form.errors)
self.assertEqual(adminform.form.errors['password2'],
["The two password fields didn't match."])
@ -5040,7 +5040,7 @@ class AdminViewOnSiteTests(TestCase):
# just verifying the parent form failed validation, as expected --
# this isn't the regression test
self.assertTrue('some_required_info' in response.context['adminform'].form.errors)
self.assertIn('some_required_info', response.context['adminform'].form.errors)
# actual regression test
for error_set in response.context['inline_admin_formset'].formset.errors:
@ -5070,7 +5070,7 @@ class AdminViewOnSiteTests(TestCase):
# just verifying the parent form failed validation, as expected --
# this isn't the regression test
self.assertTrue('some_required_info' in response.context['adminform'].form.errors)
self.assertIn('some_required_info', response.context['adminform'].form.errors)
# actual regression test
for error_set in response.context['inline_admin_formset'].formset.errors:

View File

@ -1046,7 +1046,7 @@ class AdminRawIdWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
self.selenium.switch_to.window('id_main_band')
self.wait_page_loaded()
link = self.selenium.find_element_by_link_text('Bogey Blues')
self.assertTrue('/band/42/' in link.get_attribute('href'))
self.assertIn('/band/42/', link.get_attribute('href'))
link.click()
# The field now contains the selected band's id
@ -1058,7 +1058,7 @@ class AdminRawIdWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
self.selenium.switch_to.window('id_main_band')
self.wait_page_loaded()
link = self.selenium.find_element_by_link_text('Green Potatoes')
self.assertTrue('/band/98/' in link.get_attribute('href'))
self.assertIn('/band/98/', link.get_attribute('href'))
link.click()
# The field now contains the other selected band's id
@ -1081,7 +1081,7 @@ class AdminRawIdWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
self.selenium.switch_to.window('id_supporting_bands')
self.wait_page_loaded()
link = self.selenium.find_element_by_link_text('Bogey Blues')
self.assertTrue('/band/42/' in link.get_attribute('href'))
self.assertIn('/band/42/', link.get_attribute('href'))
link.click()
# The field now contains the selected band's id
@ -1093,7 +1093,7 @@ class AdminRawIdWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
self.selenium.switch_to.window('id_supporting_bands')
self.wait_page_loaded()
link = self.selenium.find_element_by_link_text('Green Potatoes')
self.assertTrue('/band/98/' in link.get_attribute('href'))
self.assertIn('/band/98/', link.get_attribute('href'))
link.click()
# The field now contains the two selected bands' ids

View File

@ -133,7 +133,7 @@ class AggregationTests(TestCase):
rating=3.0
)
# Different DB backends return different types for the extra select computation
self.assertTrue(obj.manufacture_cost == 11.545 or obj.manufacture_cost == Decimal('11.545'))
self.assertIn(obj.manufacture_cost, (11.545, Decimal('11.545')))
# Order of the annotate/extra in the query doesn't matter
obj = Book.objects.extra(select={'manufacture_cost': 'price * .5'}).annotate(mean_auth_age=Avg('authors__age')).get(pk=2)
@ -150,12 +150,12 @@ class AggregationTests(TestCase):
rating=3.0
)
# Different DB backends return different types for the extra select computation
self.assertTrue(obj.manufacture_cost == 11.545 or obj.manufacture_cost == Decimal('11.545'))
self.assertIn(obj.manufacture_cost, (11.545, Decimal('11.545')))
# Values queries can be combined with annotate and extra
obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost': 'price * .5'}).values().get(pk=2)
manufacture_cost = obj['manufacture_cost']
self.assertTrue(manufacture_cost == 11.545 or manufacture_cost == Decimal('11.545'))
self.assertIn(manufacture_cost, (11.545, Decimal('11.545')))
del obj['manufacture_cost']
self.assertEqual(obj, {
"contact_id": 3,
@ -174,7 +174,7 @@ class AggregationTests(TestCase):
# matter
obj = Book.objects.values().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost': 'price * .5'}).get(pk=2)
manufacture_cost = obj['manufacture_cost']
self.assertTrue(manufacture_cost == 11.545 or manufacture_cost == Decimal('11.545'))
self.assertIn(manufacture_cost, (11.545, Decimal('11.545')))
del obj['manufacture_cost']
self.assertEqual(obj, {
'contact_id': 3,
@ -1156,15 +1156,15 @@ class JoinPromotionTests(TestCase):
def test_existing_join_not_promoted(self):
# No promotion for existing joins
qs = Charlie.objects.filter(alfa__name__isnull=False).annotate(Count('alfa__name'))
self.assertTrue(' INNER JOIN ' in str(qs.query))
self.assertIn(' INNER JOIN ', str(qs.query))
# Also, the existing join is unpromoted when doing filtering for already
# promoted join.
qs = Charlie.objects.annotate(Count('alfa__name')).filter(alfa__name__isnull=False)
self.assertTrue(' INNER JOIN ' in str(qs.query))
self.assertIn(' INNER JOIN ', str(qs.query))
# But, as the join is nullable first use by annotate will be LOUTER
qs = Charlie.objects.annotate(Count('alfa__name'))
self.assertTrue(' LEFT OUTER JOIN ' in str(qs.query))
self.assertIn(' LEFT OUTER JOIN ', str(qs.query))
def test_non_nullable_fk_not_promoted(self):
qs = Book.objects.annotate(Count('contact__name'))
self.assertTrue(' INNER JOIN ' in str(qs.query))
self.assertIn(' INNER JOIN ', str(qs.query))

View File

@ -392,7 +392,7 @@ class SequenceResetTest(TestCase):
# If we create a new object now, it should have a PK greater
# than the PK we specified manually.
obj = models.Post.objects.create(name='New post', text='goodbye world')
self.assertTrue(obj.pk > 10)
self.assertGreater(obj.pk, 10)
# This test needs to run outside of a transaction, otherwise closing the
@ -413,12 +413,12 @@ class ConnectionCreatedSignalTest(TransactionTestCase):
connection_created.connect(receiver)
connection.close()
connection.cursor()
self.assertTrue(data["connection"].connection is connection.connection)
self.assertIs(data["connection"].connection, connection.connection)
connection_created.disconnect(receiver)
data.clear()
connection.cursor()
self.assertTrue(data == {})
self.assertEqual(data, {})
class EscapingChecks(TestCase):

View File

@ -134,7 +134,7 @@ class ModelInstanceCreationTests(TestCase):
a.save()
# You can use 'in' to test for membership...
self.assertTrue(a in Article.objects.all())
self.assertIn(a, Article.objects.all())
# ... but there will often be more efficient ways if that is all you need:
self.assertTrue(Article.objects.filter(id=a.id).exists())
@ -171,12 +171,10 @@ class ModelTest(TestCase):
some_pub_date = datetime(2014, 5, 16, 12, 1)
a1 = Article.objects.create(headline='First', pub_date=some_pub_date)
a2 = Article.objects.create(headline='Second', pub_date=some_pub_date)
self.assertTrue(a1 != a2)
self.assertFalse(a1 == a2)
self.assertTrue(a1 == Article.objects.get(id__exact=a1.id))
self.assertNotEqual(a1, a2)
self.assertEqual(a1, Article.objects.get(id__exact=a1.id))
self.assertTrue(Article.objects.get(id__exact=a1.id) != Article.objects.get(id__exact=a2.id))
self.assertFalse(Article.objects.get(id__exact=a2.id) == Article.objects.get(id__exact=a1.id))
self.assertNotEqual(Article.objects.get(id__exact=a1.id), Article.objects.get(id__exact=a2.id))
def test_multiple_objects_max_num_fetched(self):
"""
@ -286,7 +284,7 @@ class ModelTest(TestCase):
)
s = {a10, a11, a12}
self.assertTrue(Article.objects.get(headline='Article 11') in s)
self.assertIn(Article.objects.get(headline='Article 11'), s)
def test_field_ordering(self):
"""
@ -299,10 +297,10 @@ class ModelTest(TestCase):
f1 = Field()
f2 = Field(auto_created=True)
f3 = Field()
self.assertTrue(f2 < f1)
self.assertTrue(f3 > f1)
self.assertFalse(f1 is None)
self.assertFalse(f2 in (None, 1, ''))
self.assertLess(f2, f1)
self.assertGreater(f3, f1)
self.assertIsNotNone(f1)
self.assertNotIn(f2, (None, 1, ''))
def test_extra_method_select_argument_with_dashes_and_values(self):
# The 'select' argument to extra() supports names with dashes in

View File

@ -116,7 +116,7 @@ class BulkCreateTests(TestCase):
TwoFields.objects.bulk_create([
TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)
])
self.assertTrue(len(connection.queries) < 10)
self.assertLess(len(connection.queries), 10)
def test_large_batch_mixed(self):
"""
@ -146,7 +146,7 @@ class BulkCreateTests(TestCase):
TwoFields.objects.bulk_create([
TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1)
for i in range(100000, 101000)])
self.assertTrue(len(connection.queries) < 10)
self.assertLess(len(connection.queries), 10)
def test_explicit_batch_size(self):
objs = [TwoFields(f1=i, f2=i) for i in range(0, 4)]

View File

@ -2084,7 +2084,7 @@ class CacheHandlerTest(TestCase):
cache1 = caches['default']
cache2 = caches['default']
self.assertTrue(cache1 is cache2)
self.assertIs(cache1, cache2)
def test_per_thread(self):
"""
@ -2101,4 +2101,4 @@ class CacheHandlerTest(TestCase):
t.start()
t.join()
self.assertFalse(c[0] is c[1])
self.assertIsNot(c[0], c[1])

View File

@ -119,7 +119,7 @@ class CsrfViewMiddlewareTest(TestCase):
self.assertEqual(csrf_cookie['secure'], True)
self.assertEqual(csrf_cookie['httponly'], True)
self.assertEqual(csrf_cookie['path'], '/test/')
self.assertTrue('Cookie' in resp2.get('Vary', ''))
self.assertIn('Cookie', resp2.get('Vary', ''))
def test_process_response_get_token_not_used(self):
"""
@ -340,7 +340,7 @@ class CsrfViewMiddlewareTest(TestCase):
req = self._get_GET_no_csrf_cookie_request()
resp = view(req)
self.assertTrue(resp.cookies.get(settings.CSRF_COOKIE_NAME, False))
self.assertTrue('Cookie' in resp.get('Vary', ''))
self.assertIn('Cookie', resp.get('Vary', ''))
def test_ensures_csrf_cookie_with_middleware(self):
"""
@ -357,7 +357,7 @@ class CsrfViewMiddlewareTest(TestCase):
resp = view(req)
resp2 = CsrfViewMiddleware().process_response(req, resp)
self.assertTrue(resp2.cookies.get(settings.CSRF_COOKIE_NAME, False))
self.assertTrue('Cookie' in resp2.get('Vary', ''))
self.assertIn('Cookie', resp2.get('Vary', ''))
def test_ensures_csrf_cookie_no_logging(self):
"""

View File

@ -14,7 +14,7 @@ class DataTypesTestCase(TestCase):
def test_boolean_type(self):
d = Donut(name='Apple Fritter')
self.assertFalse(d.is_frosted)
self.assertTrue(d.has_sprinkles is None)
self.assertIsNone(d.has_sprinkles)
d.has_sprinkles = True
self.assertTrue(d.has_sprinkles)

View File

@ -6,10 +6,10 @@ from .models import Empty
class EmptyModelTests(TestCase):
def test_empty(self):
m = Empty()
self.assertEqual(m.id, None)
self.assertIsNone(m.id)
m.save()
Empty.objects.create()
self.assertEqual(len(Empty.objects.all()), 2)
self.assertTrue(m.id is not None)
self.assertIsNotNone(m.id)
existing = Empty(m.id)
existing.save()

View File

@ -210,7 +210,7 @@ class ExpressionsTests(TestCase):
# keys, or attributes which involve joins.
test_gmbh.point_of_contact = None
test_gmbh.save()
self.assertTrue(test_gmbh.point_of_contact is None)
self.assertIsNone(test_gmbh.point_of_contact)
def test():
test_gmbh.point_of_contact = F("ceo")

View File

@ -14,4 +14,4 @@ class DefaultTests(TestCase):
self.assertIsInstance(a.id, six.integer_types)
self.assertEqual(a.headline, "Default headline")
self.assertTrue((now - a.pub_date).seconds < 5)
self.assertLess((now - a.pub_date).seconds, 5)

View File

@ -138,7 +138,7 @@ class FileStorageTests(unittest.TestCase):
self.assertEqual(atime, datetime.fromtimestamp(
os.path.getatime(self.storage.path(f_name))))
self.assertTrue(datetime.now() - self.storage.accessed_time(f_name) < timedelta(seconds=2))
self.assertLess(datetime.now() - self.storage.accessed_time(f_name), timedelta(seconds=2))
self.storage.delete(f_name)
def test_file_created_time(self):
@ -154,7 +154,7 @@ class FileStorageTests(unittest.TestCase):
self.assertEqual(ctime, datetime.fromtimestamp(
os.path.getctime(self.storage.path(f_name))))
self.assertTrue(datetime.now() - self.storage.created_time(f_name) < timedelta(seconds=2))
self.assertLess(datetime.now() - self.storage.created_time(f_name), timedelta(seconds=2))
self.storage.delete(f_name)
@ -171,7 +171,7 @@ class FileStorageTests(unittest.TestCase):
self.assertEqual(mtime, datetime.fromtimestamp(
os.path.getmtime(self.storage.path(f_name))))
self.assertTrue(datetime.now() - self.storage.modified_time(f_name) < timedelta(seconds=2))
self.assertLess(datetime.now() - self.storage.modified_time(f_name), timedelta(seconds=2))
self.storage.delete(f_name)
@ -459,7 +459,7 @@ class FileFieldStorageTests(unittest.TestCase):
obj1.normal = SimpleUploadedFile("assignment.txt", b"content")
dirs, files = temp_storage.listdir("tests")
self.assertEqual(dirs, [])
self.assertFalse("assignment.txt" in files)
self.assertNotIn("assignment.txt", files)
obj1.save()
dirs, files = temp_storage.listdir("tests")

View File

@ -257,7 +257,7 @@ class FileUploadTests(TestCase):
for name, _, expected in cases:
got = result[name]
self.assertEqual(expected, got, 'Mismatch for {0}'.format(name))
self.assertTrue(len(got) < 256,
self.assertLess(len(got), 256,
"Got a long file name (%s characters)." % len(got))
def test_content_type_extra(self):
@ -336,12 +336,12 @@ class FileUploadTests(TestCase):
# Small file posting should work.
response = self.client.post('/quota/', {'f': smallfile})
got = json.loads(response.content.decode('utf-8'))
self.assertTrue('f' in got)
self.assertIn('f', got)
# Large files don't go through.
response = self.client.post("/quota/", {'f': bigfile})
got = json.loads(response.content.decode('utf-8'))
self.assertTrue('f' not in got)
self.assertNotIn('f', got)
def test_broken_custom_upload_handler(self):
with tempfile.NamedTemporaryFile() as file:

View File

@ -123,7 +123,6 @@ class InitialSQLTests(TestCase):
out = StringIO()
management.call_command("sqlcustom", "fixtures_model_package", stdout=out)
output = out.getvalue()
self.assertTrue("INSERT INTO fixtures_model_package_book (name) "
"VALUES ('My Book')" in output)
self.assertIn("INSERT INTO fixtures_model_package_book (name) VALUES ('My Book')", output)
# value from deprecated search path models/sql (remove in Django 1.9)
self.assertTrue("Deprecated Book" in output)
self.assertIn("Deprecated Book", output)

View File

@ -319,7 +319,7 @@ class MultiColumnFKTests(TestCase):
with self.assertNumQueries(1):
fetched = Article.objects.select_related('active_translation').get(
active_translation__title='Otsikko')
self.assertTrue(fetched.active_translation.title == 'Otsikko')
self.assertEqual(fetched.active_translation.title, 'Otsikko')
a2 = Article.objects.create(pub_date=datetime.date.today())
at2_fi = ArticleTranslation(article=a2, lang='fi', title='Atsikko', body='Diipadaapa',
abstract='dipad')

View File

@ -318,7 +318,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
# label tag is correctly associated with month dropdown
d = GetDate({'mydate_month': '1', 'mydate_day': '1', 'mydate_year': '2010'})
self.assertTrue('<label for="id_mydate_month">' in d.as_p())
self.assertIn('<label for="id_mydate_month">', d.as_p())
def test_selectdate_empty_label(self):
w = SelectDateWidget(years=('2014',), empty_label='empty_label')
@ -865,4 +865,4 @@ class FormsExtraL10NTestCase(TestCase):
def test_form_label_association(self):
# label tag is correctly associated with first rendered dropdown
a = GetDate({'mydate_month': '1', 'mydate_day': '1', 'mydate_year': '2010'})
self.assertTrue('<label for="id_mydate_day">' in a.as_p())
self.assertIn('<label for="id_mydate_day">', a.as_p())

View File

@ -955,7 +955,7 @@ class FormsTestCase(TestCase):
f2 = MyForm()
f1.fields['myfield'].validators[0] = MaxValueValidator(12)
self.assertFalse(f1.fields['myfield'].validators[0] == f2.fields['myfield'].validators[0])
self.assertNotEqual(f1.fields['myfield'].validators[0], f2.fields['myfield'].validators[0])
def test_hidden_widget(self):
# HiddenInput widgets are displayed differently in the as_table(), as_ul())
@ -2003,9 +2003,8 @@ class FormsTestCase(TestCase):
field = ChoicesField()
field2 = copy.deepcopy(field)
self.assertIsInstance(field2, ChoicesField)
self.assertFalse(id(field2.fields) == id(field.fields))
self.assertFalse(id(field2.fields[0].choices) ==
id(field.fields[0].choices))
self.assertIsNot(field2.fields, field.fields)
self.assertIsNot(field2.fields[0].choices, field.fields[0].choices)
def test_multivalue_optional_subfields(self):
class PhoneField(MultiValueField):

View File

@ -1194,12 +1194,12 @@ class ClearableFileInputTests(TestCase):
widget = ClearableFileInput()
field = StrangeFieldFile()
output = widget.render('my<div>file', field)
self.assertFalse(field.url in output)
self.assertTrue('href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en"' in output)
self.assertFalse(six.text_type(field) in output)
self.assertTrue('something&lt;div onclick=&quot;alert(&#39;oops&#39;)&quot;&gt;.jpg' in output)
self.assertTrue('my&lt;div&gt;file' in output)
self.assertFalse('my<div>file' in output)
self.assertNotIn(field.url, output)
self.assertIn('href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en"', output)
self.assertNotIn(six.text_type(field), output)
self.assertIn('something&lt;div onclick=&quot;alert(&#39;oops&#39;)&quot;&gt;.jpg', output)
self.assertIn('my&lt;div&gt;file', output)
self.assertNotIn('my<div>file', output)
def test_clear_input_renders_only_if_not_required(self):
"""

View File

@ -157,7 +157,7 @@ class FormsModelTestCase(TestCase):
# FileModel with unicode filename and data #########################
f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False)
self.assertTrue(f.is_valid())
self.assertTrue('file1' in f.cleaned_data)
self.assertIn('file1', f.cleaned_data)
m = FileModel.objects.create(file=f.cleaned_data['file1'])
self.assertEqual(m.file.name, 'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt')
m.delete()

View File

@ -72,12 +72,12 @@ class GenericRelationTests(TestCase):
# search with a non-matching note and a matching org name
qs = Contact.objects.filter(Q(notes__note__icontains=r'other note') |
Q(organizations__name__icontains=r'org name'))
self.assertTrue(org_contact in qs)
self.assertIn(org_contact, qs)
# search again, with the same query parameters, in reverse order
qs = Contact.objects.filter(
Q(organizations__name__icontains=r'org name') |
Q(notes__note__icontains=r'other note'))
self.assertTrue(org_contact in qs)
self.assertIn(org_contact, qs)
def test_join_reuse(self):
qs = Person.objects.filter(

View File

@ -447,7 +447,7 @@ class GetContextDataTest(unittest.TestCase):
context = test_view.get_context_data(kwarg_test='kwarg_value')
# the test_name key is inserted by the test classes parent
self.assertTrue('test_name' in context)
self.assertIn('test_name', context)
self.assertEqual(context['kwarg_test'], 'kwarg_value')
self.assertEqual(context['custom_key'], 'custom_value')

View File

@ -35,7 +35,7 @@ class ArchiveIndexViewTests(TestCase):
self.assertEqual(res.status_code, 200)
self.assertEqual(list(res.context['date_list']), list(Book.objects.dates('pubdate', 'year', 'DESC')))
self.assertEqual(list(res.context['thingies']), list(Book.objects.all()))
self.assertFalse('latest' in res.context)
self.assertNotIn('latest', res.context)
self.assertTemplateUsed(res, 'generic_views/book_archive.html')
def test_empty_archive_view(self):

View File

@ -114,14 +114,14 @@ class DetailViewTest(TestCase):
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertEqual(res.context['thingy'], Author.objects.get(pk=1))
self.assertFalse('author' in res.context)
self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_duplicated_context_object_name(self):
res = self.client.get('/detail/author/1/dupe_context_object_name/')
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertFalse('author' in res.context)
self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_invalid_url(self):

View File

@ -108,8 +108,8 @@ class CreateViewTests(TestCase):
self.assertEqual(res.status_code, 200)
self.assertIsInstance(res.context['form'], forms.ModelForm)
self.assertIsInstance(res.context['view'], View)
self.assertFalse('object' in res.context)
self.assertFalse('author' in res.context)
self.assertNotIn('object', res.context)
self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/author_form.html')
res = self.client.post('/edit/authors/create/',
@ -153,8 +153,8 @@ class CreateViewTests(TestCase):
res = self.client.get('/edit/authors/create/special/')
self.assertEqual(res.status_code, 200)
self.assertIsInstance(res.context['form'], views.AuthorForm)
self.assertFalse('object' in res.context)
self.assertFalse('author' in res.context)
self.assertNotIn('object', res.context)
self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/form.html')
res = self.client.post('/edit/authors/create/special/',
@ -302,7 +302,7 @@ class UpdateViewTests(TestCase):
self.assertIsInstance(res.context['form'], views.AuthorForm)
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk))
self.assertFalse('author' in res.context)
self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/form.html')
res = self.client.post('/edit/author/%d/update/special/' % a.pk,
@ -389,7 +389,7 @@ class DeleteViewTests(TestCase):
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk))
self.assertFalse('author' in res.context)
self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/confirm_delete.html')
res = self.client.post('/edit/author/%d/delete/special/' % a.pk)

View File

@ -78,10 +78,10 @@ class QueryDictTests(unittest.TestCase):
if six.PY2:
self.assertTrue(q.has_key('foo'))
self.assertTrue('foo' in q)
self.assertIn('foo', q)
if six.PY2:
self.assertFalse(q.has_key('bar'))
self.assertFalse('bar' in q)
self.assertNotIn('bar', q)
self.assertEqual(list(six.iteritems(q)), [('foo', 'bar')])
self.assertEqual(list(six.iterlists(q)), [('foo', ['bar'])])
@ -118,7 +118,7 @@ class QueryDictTests(unittest.TestCase):
q = QueryDict(mutable=True)
q['name'] = 'john'
del q['name']
self.assertFalse('name' in q)
self.assertNotIn('name', q)
def test_basic_mutable_operations(self):
q = QueryDict(mutable=True)
@ -137,7 +137,7 @@ class QueryDictTests(unittest.TestCase):
self.assertEqual(q['foo'], 'another')
if six.PY2:
self.assertTrue(q.has_key('foo'))
self.assertTrue('foo' in q)
self.assertIn('foo', q)
self.assertListEqual(sorted(list(six.iteritems(q))),
[('foo', 'another'), ('name', 'john')])
@ -609,8 +609,8 @@ class CookieTests(unittest.TestCase):
"""
c = SimpleCookie()
c['test'] = "An,awkward;value"
self.assertTrue(";" not in c.output().rstrip(';')) # IE compat
self.assertTrue("," not in c.output().rstrip(';')) # Safari compat
self.assertNotIn(";", c.output().rstrip(';')) # IE compat
self.assertNotIn(",", c.output().rstrip(';')) # Safari compat
def test_decode(self):
"""
@ -636,13 +636,13 @@ class CookieTests(unittest.TestCase):
"""
Test that a single non-standard cookie name doesn't affect all cookies. Ticket #13007.
"""
self.assertTrue('good_cookie' in parse_cookie('good_cookie=yes;bad:cookie=yes').keys())
self.assertIn('good_cookie', parse_cookie('good_cookie=yes;bad:cookie=yes').keys())
def test_repeated_nonstandard_keys(self):
"""
Test that a repeated non-standard name doesn't affect all cookies. Ticket #15852
"""
self.assertTrue('good_cookie' in parse_cookie('a:=b; a:=c; good_cookie=yes').keys())
self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys())
def test_httponly_after_load(self):
"""

View File

@ -96,9 +96,9 @@ class ExtractorTests(SimpleTestCase):
parts.append(':%d' % line_number)
needle = ''.join(parts)
if assert_presence:
return self.assertTrue(needle in po_contents, '"%s" not found in final .po file.' % needle)
return self.assertIn(needle, po_contents, '"%s" not found in final .po file.' % needle)
else:
return self.assertFalse(needle in po_contents, '"%s" shouldn\'t be in final .po file.' % needle)
return self.assertNotIn(needle, po_contents, '"%s" shouldn\'t be in final .po file.' % needle)
def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts):
"""
@ -141,26 +141,26 @@ class BasicExtractorTests(ExtractorTests):
self.assertTrue(os.path.exists(self.PO_FILE))
with io.open(self.PO_FILE, 'r', encoding='utf-8') as fp:
po_contents = fp.read()
self.assertTrue('#. Translators: This comment should be extracted' in po_contents)
self.assertTrue('This comment should not be extracted' not in po_contents)
self.assertIn('#. Translators: This comment should be extracted', po_contents)
self.assertNotIn('This comment should not be extracted', po_contents)
# Comments in templates
self.assertTrue('#. Translators: Django template comment for translators' in po_contents)
self.assertTrue("#. Translators: Django comment block for translators\n#. string's meaning unveiled" in po_contents)
self.assertIn('#. Translators: Django template comment for translators', po_contents)
self.assertIn("#. Translators: Django comment block for translators\n#. string's meaning unveiled", po_contents)
self.assertTrue('#. Translators: One-line translator comment #1' in po_contents)
self.assertTrue('#. Translators: Two-line translator comment #1\n#. continued here.' in po_contents)
self.assertIn('#. Translators: One-line translator comment #1', po_contents)
self.assertIn('#. Translators: Two-line translator comment #1\n#. continued here.', po_contents)
self.assertTrue('#. Translators: One-line translator comment #2' in po_contents)
self.assertTrue('#. Translators: Two-line translator comment #2\n#. continued here.' in po_contents)
self.assertIn('#. Translators: One-line translator comment #2', po_contents)
self.assertIn('#. Translators: Two-line translator comment #2\n#. continued here.', po_contents)
self.assertTrue('#. Translators: One-line translator comment #3' in po_contents)
self.assertTrue('#. Translators: Two-line translator comment #3\n#. continued here.' in po_contents)
self.assertIn('#. Translators: One-line translator comment #3', po_contents)
self.assertIn('#. Translators: Two-line translator comment #3\n#. continued here.', po_contents)
self.assertTrue('#. Translators: One-line translator comment #4' in po_contents)
self.assertTrue('#. Translators: Two-line translator comment #4\n#. continued here.' in po_contents)
self.assertIn('#. Translators: One-line translator comment #4', po_contents)
self.assertIn('#. Translators: Two-line translator comment #4\n#. continued here.', po_contents)
self.assertTrue('#. Translators: One-line translator comment #5 -- with non ASCII characters: áéíóúö' in po_contents)
self.assertTrue('#. Translators: Two-line translator comment #5 -- with non ASCII characters: áéíóúö\n#. continued here.' in po_contents)
self.assertIn('#. Translators: One-line translator comment #5 -- with non ASCII characters: áéíóúö', po_contents)
self.assertIn('#. Translators: Two-line translator comment #5 -- with non ASCII characters: áéíóúö\n#. continued here.', po_contents)
def test_templatize_trans_tag(self):
# ticket #11240
@ -250,23 +250,23 @@ class BasicExtractorTests(ExtractorTests):
with open(self.PO_FILE, 'r') as fp:
po_contents = force_text(fp.read())
# {% trans %}
self.assertTrue('msgctxt "Special trans context #1"' in po_contents)
self.assertIn('msgctxt "Special trans context #1"', po_contents)
self.assertMsgId("Translatable literal #7a", po_contents)
self.assertTrue('msgctxt "Special trans context #2"' in po_contents)
self.assertIn('msgctxt "Special trans context #2"', po_contents)
self.assertMsgId("Translatable literal #7b", po_contents)
self.assertTrue('msgctxt "Special trans context #3"' in po_contents)
self.assertIn('msgctxt "Special trans context #3"', po_contents)
self.assertMsgId("Translatable literal #7c", po_contents)
# {% blocktrans %}
self.assertTrue('msgctxt "Special blocktrans context #1"' in po_contents)
self.assertIn('msgctxt "Special blocktrans context #1"', po_contents)
self.assertMsgId("Translatable literal #8a", po_contents)
self.assertTrue('msgctxt "Special blocktrans context #2"' in po_contents)
self.assertIn('msgctxt "Special blocktrans context #2"', po_contents)
self.assertMsgId("Translatable literal #8b-singular", po_contents)
self.assertTrue("Translatable literal #8b-plural" in po_contents)
self.assertTrue('msgctxt "Special blocktrans context #3"' in po_contents)
self.assertIn("Translatable literal #8b-plural", po_contents)
self.assertIn('msgctxt "Special blocktrans context #3"', po_contents)
self.assertMsgId("Translatable literal #8c-singular", po_contents)
self.assertTrue("Translatable literal #8c-plural" in po_contents)
self.assertTrue('msgctxt "Special blocktrans context #4"' in po_contents)
self.assertIn("Translatable literal #8c-plural", po_contents)
self.assertIn('msgctxt "Special blocktrans context #4"', po_contents)
self.assertMsgId("Translatable literal #8d %(a)s", po_contents)
def test_context_in_single_quotes(self):
@ -276,12 +276,12 @@ class BasicExtractorTests(ExtractorTests):
with open(self.PO_FILE, 'r') as fp:
po_contents = force_text(fp.read())
# {% trans %}
self.assertTrue('msgctxt "Context wrapped in double quotes"' in po_contents)
self.assertTrue('msgctxt "Context wrapped in single quotes"' in po_contents)
self.assertIn('msgctxt "Context wrapped in double quotes"', po_contents)
self.assertIn('msgctxt "Context wrapped in single quotes"', po_contents)
# {% blocktrans %}
self.assertTrue('msgctxt "Special blocktrans context wrapped in double quotes"' in po_contents)
self.assertTrue('msgctxt "Special blocktrans context wrapped in single quotes"' in po_contents)
self.assertIn('msgctxt "Special blocktrans context wrapped in double quotes"', po_contents)
self.assertIn('msgctxt "Special blocktrans context wrapped in single quotes"', po_contents)
def test_template_comments(self):
"""Template comment tags on the same line of other constructs (#19552)"""
@ -312,31 +312,31 @@ class BasicExtractorTests(ExtractorTests):
po_contents = force_text(fp.read())
self.assertMsgId('Translatable literal #9a', po_contents)
self.assertFalse('ignored comment #1' in po_contents)
self.assertNotIn('ignored comment #1', po_contents)
self.assertFalse('Translators: ignored i18n comment #1' in po_contents)
self.assertNotIn('Translators: ignored i18n comment #1', po_contents)
self.assertMsgId("Translatable literal #9b", po_contents)
self.assertFalse('ignored i18n comment #2' in po_contents)
self.assertFalse('ignored comment #2' in po_contents)
self.assertNotIn('ignored i18n comment #2', po_contents)
self.assertNotIn('ignored comment #2', po_contents)
self.assertMsgId('Translatable literal #9c', po_contents)
self.assertFalse('ignored comment #3' in po_contents)
self.assertFalse('ignored i18n comment #3' in po_contents)
self.assertNotIn('ignored comment #3', po_contents)
self.assertNotIn('ignored i18n comment #3', po_contents)
self.assertMsgId('Translatable literal #9d', po_contents)
self.assertFalse('ignored comment #4' in po_contents)
self.assertNotIn('ignored comment #4', po_contents)
self.assertMsgId('Translatable literal #9e', po_contents)
self.assertFalse('ignored comment #5' in po_contents)
self.assertNotIn('ignored comment #5', po_contents)
self.assertFalse('ignored i18n comment #4' in po_contents)
self.assertNotIn('ignored i18n comment #4', po_contents)
self.assertMsgId('Translatable literal #9f', po_contents)
self.assertTrue('#. Translators: valid i18n comment #5' in po_contents)
self.assertIn('#. Translators: valid i18n comment #5', po_contents)
self.assertMsgId('Translatable literal #9g', po_contents)
self.assertTrue('#. Translators: valid i18n comment #6' in po_contents)
self.assertIn('#. Translators: valid i18n comment #6', po_contents)
self.assertMsgId('Translatable literal #9h', po_contents)
self.assertTrue('#. Translators: valid i18n comment #7' in po_contents)
self.assertIn('#. Translators: valid i18n comment #7', po_contents)
self.assertMsgId('Translatable literal #9i', po_contents)
six.assertRegex(self, po_contents, r'#\..+Translators: valid i18n comment #8')
@ -391,7 +391,7 @@ class IgnoredExtractorTests(ExtractorTests):
out, po_contents = self._run_makemessages(ignore_patterns=[
os.path.join('ignore_dir', '*'),
])
self.assertTrue("ignoring directory ignore_dir" in out)
self.assertIn("ignoring directory ignore_dir", out)
self.assertMsgId('This literal should be included.', po_contents)
self.assertNotMsgId('This should be ignored.', po_contents)
@ -400,14 +400,14 @@ class IgnoredExtractorTests(ExtractorTests):
'templates/*/ignore.html',
'templates/subdir/*',
])
self.assertTrue("ignoring directory subdir" in out)
self.assertIn("ignoring directory subdir", out)
self.assertNotMsgId('This subdir should be ignored too.', po_contents)
def test_ignore_file_patterns(self):
out, po_contents = self._run_makemessages(ignore_patterns=[
'xxx_*',
])
self.assertTrue("ignoring file xxx_ignored.html" in out)
self.assertIn("ignoring file xxx_ignored.html", out)
self.assertNotMsgId('This should be ignored too.', po_contents)
@override_settings(
@ -455,7 +455,7 @@ class SymlinkExtractorTests(ExtractorTests):
with open(self.PO_FILE, 'r') as fp:
po_contents = force_text(fp.read())
self.assertMsgId('This literal should be included.', po_contents)
self.assertTrue('templates_symlinked/test.html' in po_contents)
self.assertIn('templates_symlinked/test.html', po_contents)
class CopyPluralFormsExtractorTests(ExtractorTests):
@ -477,7 +477,7 @@ class CopyPluralFormsExtractorTests(ExtractorTests):
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE, 'r') as fp:
po_contents = force_text(fp.read())
self.assertTrue('Plural-Forms: nplurals=2; plural=(n != 1)' in po_contents)
self.assertIn('Plural-Forms: nplurals=2; plural=(n != 1)', po_contents)
def test_override_plural_forms(self):
"""Ticket #20311."""

View File

@ -1153,7 +1153,7 @@ class ResolutionOrderI18NTests(TestCase):
def assertUgettext(self, msgid, msgstr):
result = ugettext(msgid)
self.assertTrue(msgstr in result, ("The string '%s' isn't in the "
self.assertIn(msgstr, result, ("The string '%s' isn't in the "
"translation of '%s'; the actual result is '%s'." % (msgstr, msgid, result)))

View File

@ -11,9 +11,9 @@ class IntrospectionTests(TestCase):
def test_table_names(self):
tl = connection.introspection.table_names()
self.assertEqual(tl, sorted(tl))
self.assertTrue(Reporter._meta.db_table in tl,
self.assertIn(Reporter._meta.db_table, tl,
"'%s' isn't in table_list()." % Reporter._meta.db_table)
self.assertTrue(Article._meta.db_table in tl,
self.assertIn(Article._meta.db_table, tl,
"'%s' isn't in table_list()." % Article._meta.db_table)
def test_django_table_names(self):
@ -60,7 +60,7 @@ class IntrospectionTests(TestCase):
def test_sequence_list(self):
sequences = connection.introspection.sequence_list()
expected = {'table': Reporter._meta.db_table, 'column': 'id'}
self.assertTrue(expected in sequences,
self.assertIn(expected, sequences,
'Reporter sequence not found in sequence_list()')
def test_get_table_description_names(self):

View File

@ -123,12 +123,12 @@ class WarningLoggerTests(TestCase):
def test_warnings_capture(self):
warnings.warn('Foo Deprecated', RemovedInNextVersionWarning)
output = force_text(self.outputs[0].getvalue())
self.assertTrue('Foo Deprecated' in output)
self.assertIn('Foo Deprecated', output)
def test_warnings_capture_debug_false(self):
warnings.warn('Foo Deprecated', RemovedInNextVersionWarning)
output = force_text(self.outputs[0].getvalue())
self.assertFalse('Foo Deprecated' in output)
self.assertNotIn('Foo Deprecated', output)
@override_settings(DEBUG=True)
def test_error_filter_still_raises(self):
@ -263,8 +263,8 @@ class AdminEmailHandlerTest(TestCase):
self.logger.error(message)
self.assertEqual(len(mail.outbox), 1)
self.assertFalse('\n' in mail.outbox[0].subject)
self.assertFalse('\r' in mail.outbox[0].subject)
self.assertNotIn('\n', mail.outbox[0].subject)
self.assertNotIn('\r', mail.outbox[0].subject)
self.assertEqual(mail.outbox[0].subject, expected_subject)
@override_settings(

View File

@ -85,12 +85,12 @@ class M2MRegressionTests(TestCase):
t2 = Tag.objects.create()
# Get same manager twice in a row:
self.assertTrue(t1.entry_set.__class__ is t1.entry_set.__class__)
self.assertTrue(e1.topics.__class__ is e1.topics.__class__)
self.assertIs(t1.entry_set.__class__, t1.entry_set.__class__)
self.assertIs(e1.topics.__class__, e1.topics.__class__)
# Get same manager for different instances
self.assertTrue(e1.topics.__class__ is e2.topics.__class__)
self.assertTrue(t1.entry_set.__class__ is t2.entry_set.__class__)
self.assertIs(e1.topics.__class__, e2.topics.__class__)
self.assertIs(t1.entry_set.__class__, t2.entry_set.__class__)
def test_m2m_abstract_split(self):
# Regression for #19236 - an abstract class with a 'split' method

View File

@ -346,31 +346,31 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
# Regression for #13433 - Make sure that EmailMessage doesn't mangle
# 'From ' in message body.
email = EmailMessage('Subject', 'From the future', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
self.assertFalse(b'>From the future' in email.message().as_bytes())
self.assertNotIn(b'>From the future', email.message().as_bytes())
def test_dont_base64_encode(self):
# Ticket #3472
# Shouldn't use Base64 encoding at all
msg = EmailMessage('Subject', 'UTF-8 encoded body', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
self.assertFalse(b'Content-Transfer-Encoding: base64' in msg.message().as_bytes())
self.assertNotIn(b'Content-Transfer-Encoding: base64', msg.message().as_bytes())
# Ticket #11212
# Shouldn't use quoted printable, should detect it can represent content with 7 bit data
msg = EmailMessage('Subject', 'Body with only ASCII characters.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
s = msg.message().as_bytes()
self.assertFalse(b'Content-Transfer-Encoding: quoted-printable' in s)
self.assertTrue(b'Content-Transfer-Encoding: 7bit' in s)
self.assertNotIn(b'Content-Transfer-Encoding: quoted-printable', s)
self.assertIn(b'Content-Transfer-Encoding: 7bit', s)
# Shouldn't use quoted printable, should detect it can represent content with 8 bit data
msg = EmailMessage('Subject', 'Body with latin characters: àáä.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
s = msg.message().as_bytes()
self.assertFalse(b'Content-Transfer-Encoding: quoted-printable' in s)
self.assertTrue(b'Content-Transfer-Encoding: 8bit' in s)
self.assertNotIn(b'Content-Transfer-Encoding: quoted-printable', s)
self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
msg = EmailMessage('Subject', 'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
s = msg.message().as_bytes()
self.assertFalse(b'Content-Transfer-Encoding: quoted-printable' in s)
self.assertTrue(b'Content-Transfer-Encoding: 8bit' in s)
self.assertNotIn(b'Content-Transfer-Encoding: quoted-printable', s)
self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
def test_dont_base64_encode_message_rfc822(self):
# Ticket #18967
@ -387,7 +387,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
parent_s = parent_msg.message().as_string()
# Verify that the child message header is not base64 encoded
self.assertTrue(str('Child Subject') in parent_s)
self.assertIn(str('Child Subject'), parent_s)
# Feature test: try attaching email.Message object directly to the mail.
parent_msg = EmailMessage('Parent Subject', 'Some parent body', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
@ -395,7 +395,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
parent_s = parent_msg.message().as_string()
# Verify that the child message header is not base64 encoded
self.assertTrue(str('Child Subject') in parent_s)
self.assertIn(str('Child Subject'), parent_s)
# Feature test: try attaching Django's EmailMessage object directly to the mail.
parent_msg = EmailMessage('Parent Subject', 'Some parent body', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
@ -403,7 +403,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
parent_s = parent_msg.message().as_string()
# Verify that the child message header is not base64 encoded
self.assertTrue(str('Child Subject') in parent_s)
self.assertIn(str('Child Subject'), parent_s)
class PythonGlobalState(SimpleTestCase):
@ -415,19 +415,19 @@ class PythonGlobalState(SimpleTestCase):
def test_utf8(self):
txt = MIMEText('UTF-8 encoded body', 'plain', 'utf-8')
self.assertTrue('Content-Transfer-Encoding: base64' in txt.as_string())
self.assertIn('Content-Transfer-Encoding: base64', txt.as_string())
def test_7bit(self):
txt = MIMEText('Body with only ASCII characters.', 'plain', 'utf-8')
self.assertTrue('Content-Transfer-Encoding: base64' in txt.as_string())
self.assertIn('Content-Transfer-Encoding: base64', txt.as_string())
def test_8bit_latin(self):
txt = MIMEText('Body with latin characters: àáä.', 'plain', 'utf-8')
self.assertTrue(str('Content-Transfer-Encoding: base64') in txt.as_string())
self.assertIn(str('Content-Transfer-Encoding: base64'), txt.as_string())
def test_8bit_non_latin(self):
txt = MIMEText('Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'plain', 'utf-8')
self.assertTrue(str('Content-Transfer-Encoding: base64') in txt.as_string())
self.assertIn(str('Content-Transfer-Encoding: base64'), txt.as_string())
class BaseEmailBackendTests(HeadersCheckMixin, object):

View File

@ -417,10 +417,10 @@ class ManyToOneTests(TestCase):
r2 = Reporter.objects.create(first_name='John')
# Same twice
self.assertTrue(r1.article_set.__class__ is r1.article_set.__class__)
self.assertIs(r1.article_set.__class__, r1.article_set.__class__)
# Same as each other
self.assertTrue(r1.article_set.__class__ is r2.article_set.__class__)
self.assertIs(r1.article_set.__class__, r2.article_set.__class__)
def test_create_relation_with_ugettext_lazy(self):
reporter = Reporter.objects.create(first_name='John',
@ -456,28 +456,28 @@ class ManyToOneTests(TestCase):
p = c.parent
# Accessing the related object again returns the exactly same object.
self.assertTrue(c.parent is p)
self.assertIs(c.parent, p)
# But if we kill the cache, we get a new object.
del c._parent_cache
self.assertFalse(c.parent is p)
self.assertIsNot(c.parent, p)
# Assigning a new object results in that object getting cached immediately.
p2 = Parent.objects.create(name="Parent 2")
c.parent = p2
self.assertTrue(c.parent is p2)
self.assertIs(c.parent, p2)
# Assigning None succeeds if field is null=True.
p.bestchild = None
self.assertTrue(p.bestchild is None)
self.assertIsNone(p.bestchild)
# bestchild should still be None after saving.
p.save()
self.assertTrue(p.bestchild is None)
self.assertIsNone(p.bestchild)
# bestchild should still be None after fetching the object again.
p = Parent.objects.get(name="Parent")
self.assertTrue(p.bestchild is None)
self.assertIsNone(p.bestchild)
# Assigning None fails: Child.parent is null=False.
self.assertRaises(ValueError, setattr, c, "parent", None)
@ -493,7 +493,7 @@ class ManyToOneTests(TestCase):
# Creation using keyword argument should cache the related object.
p = Parent.objects.get(name="Parent")
c = Child(parent=p)
self.assertTrue(c.parent is p)
self.assertIs(c.parent, p)
# Creation using keyword argument and unsaved related instance (#8070).
p = Parent()
@ -511,7 +511,7 @@ class ManyToOneTests(TestCase):
# related object to be fetched.
p = Parent.objects.get(name="Parent")
c = Child(parent_id=p.id)
self.assertFalse(c.parent is p)
self.assertIsNot(c.parent, p)
self.assertEqual(c.parent, p)
def test_multiple_foreignkeys(self):

View File

@ -152,7 +152,7 @@ class SecurityMiddlewareTest(TestCase):
With BROWSER_XSS_FILTER set to False, the middleware does not add an
"x-xss-protection" header to the response.
"""
self.assertFalse("x-xss-protection" in self.process_response())
self.assertNotIn("x-xss-protection", self.process_response())
@override_settings(SECURE_SSL_REDIRECT=True)
def test_ssl_redirect_on(self):

View File

@ -162,7 +162,7 @@ class CommonMiddlewareTest(TestCase):
request = self._get_request('customurlconf/slash')
request.urlconf = 'middleware.extra_urls'
r = CommonMiddleware().process_request(request)
self.assertFalse(r is None,
self.assertIsNotNone(r,
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, 'http://testserver/customurlconf/slash/')
@ -198,7 +198,7 @@ class CommonMiddlewareTest(TestCase):
request = self._get_request('customurlconf/needsquoting#')
request.urlconf = 'middleware.extra_urls'
r = CommonMiddleware().process_request(request)
self.assertFalse(r is None,
self.assertIsNotNone(r,
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
self.assertEqual(r.status_code, 301)
self.assertEqual(
@ -318,24 +318,24 @@ class ConditionalGetMiddlewareTest(TestCase):
# Tests for the Date header
def test_date_header_added(self):
self.assertFalse('Date' in self.resp)
self.assertNotIn('Date', self.resp)
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
self.assertTrue('Date' in self.resp)
self.assertIn('Date', self.resp)
# Tests for the Content-Length header
def test_content_length_header_added(self):
content_length = len(self.resp.content)
self.assertFalse('Content-Length' in self.resp)
self.assertNotIn('Content-Length', self.resp)
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
self.assertTrue('Content-Length' in self.resp)
self.assertIn('Content-Length', self.resp)
self.assertEqual(int(self.resp['Content-Length']), content_length)
def test_content_length_header_not_added(self):
resp = StreamingHttpResponse('content')
self.assertFalse('Content-Length' in resp)
self.assertNotIn('Content-Length', resp)
resp = ConditionalGetMiddleware().process_response(self.req, resp)
self.assertFalse('Content-Length' in resp)
self.assertNotIn('Content-Length', resp)
def test_content_length_header_not_changed(self):
bad_content_length = len(self.resp.content) + 10

View File

@ -590,8 +590,8 @@ class AutodetectorTests(TestCase):
# Right number/type of migrations?
self.assertNumberMigrations(changes, 'eggs', 1)
self.assertOperationTypes(changes, 'eggs', 0, ["CreateModel", "CreateModel", "AlterUniqueTogether"])
self.assertFalse("unique_together" in changes['eggs'][0].operations[0].options)
self.assertFalse("unique_together" in changes['eggs'][0].operations[1].options)
self.assertNotIn("unique_together", changes['eggs'][0].operations[0].options)
self.assertNotIn("unique_together", changes['eggs'][0].operations[1].options)
# Right dependencies?
self.assertEqual(changes['eggs'][0].dependencies, [])

View File

@ -196,19 +196,19 @@ class MakeMigrationsTests(MigrationTestBase):
with codecs.open(initial_file, 'r', encoding='utf-8') as fp:
content = fp.read()
self.assertTrue('# -*- coding: utf-8 -*-' in content)
self.assertTrue('migrations.CreateModel' in content)
self.assertIn('# -*- coding: utf-8 -*-', content)
self.assertIn('migrations.CreateModel', content)
if six.PY3:
self.assertTrue('úñí©óðé µóðéø' in content) # Meta.verbose_name
self.assertTrue('úñí©óðé µóðéøß' in content) # Meta.verbose_name_plural
self.assertTrue('ÚÑÍ¢ÓÐÉ' in content) # title.verbose_name
self.assertTrue('“Ðjáñgó”' in content) # title.default
self.assertIn('úñí©óðé µóðéø', content) # Meta.verbose_name
self.assertIn('úñí©óðé µóðéøß', content) # Meta.verbose_name_plural
self.assertIn('ÚÑÍ¢ÓÐÉ', content) # title.verbose_name
self.assertIn('“Ðjáñgó”', content) # title.default
else:
self.assertTrue('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8' in content) # Meta.verbose_name
self.assertTrue('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8\\xdf' in content) # Meta.verbose_name_plural
self.assertTrue('\\xda\\xd1\\xcd\\xa2\\xd3\\xd0\\xc9' in content) # title.verbose_name
self.assertTrue('\\u201c\\xd0j\\xe1\\xf1g\\xf3\\u201d' in content) # title.default
self.assertIn('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8', content) # Meta.verbose_name
self.assertIn('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8\\xdf', content) # Meta.verbose_name_plural
self.assertIn('\\xda\\xd1\\xcd\\xa2\\xd3\\xd0\\xc9', content) # title.verbose_name
self.assertIn('\\u201c\\xd0j\\xe1\\xf1g\\xf3\\u201d', content) # title.default
def test_failing_migration(self):
#21280 - If a migration fails to serialize, it shouldn't generate an empty file.
@ -274,7 +274,7 @@ class MakeMigrationsTests(MigrationTestBase):
with codecs.open(initial_file, 'r', encoding='utf-8') as fp:
content = fp.read()
self.assertTrue('# -*- coding: utf-8 -*-' in content)
self.assertIn('# -*- coding: utf-8 -*-', content)
# Remove all whitespace to check for empty dependencies and operations
content = content.replace(' ', '')
@ -529,7 +529,7 @@ class MakeMigrationsTests(MigrationTestBase):
self.assertTrue(os.path.exists(migration_file))
with codecs.open(migration_file, "r", encoding="utf-8") as fp:
content = fp.read()
self.assertTrue("# -*- coding: utf-8 -*-" in content)
self.assertIn("# -*- coding: utf-8 -*-", content)
content = content.replace(" ", "")
return content

View File

@ -223,8 +223,8 @@ class BooleanFieldTests(unittest.TestCase):
self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])
def _test_to_python(self, f):
self.assertTrue(f.to_python(1) is True)
self.assertTrue(f.to_python(0) is False)
self.assertIs(f.to_python(1), True)
self.assertIs(f.to_python(0), False)
def test_booleanfield_get_db_prep_lookup(self):
self._test_get_db_prep_lookup(models.BooleanField())

View File

@ -258,7 +258,7 @@ class ModelFormBaseTest(TestCase):
except FieldError as e:
# Make sure the exception contains some reference to the
# field responsible for the problem.
self.assertTrue('no-field' in e.args[0])
self.assertIn('no-field', e.args[0])
else:
self.fail('Invalid "no-field" field not caught')
@ -1464,8 +1464,8 @@ class ModelChoiceFieldTests(TestCase):
field1 = form1.fields['category']
# To allow the widget to change the queryset of field1.widget.choices correctly,
# without affecting other forms, the following must hold:
self.assertTrue(field1 is not ModelChoiceForm.base_fields['category'])
self.assertTrue(field1.widget.choices.field is field1)
self.assertIsNot(field1, ModelChoiceForm.base_fields['category'])
self.assertIs(field1.widget.choices.field, field1)
def test_modelchoicefield_22745(self):
"""
@ -1764,14 +1764,14 @@ class FileAndImageFieldTests(TestCase):
fields = '__all__'
form = DocumentForm()
self.assertTrue('name="myfile"' in six.text_type(form))
self.assertTrue('myfile-clear' not in six.text_type(form))
self.assertIn('name="myfile"', six.text_type(form))
self.assertNotIn('myfile-clear', six.text_type(form))
form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')})
self.assertTrue(form.is_valid())
doc = form.save(commit=False)
self.assertEqual(doc.myfile.name, 'something.txt')
form = DocumentForm(instance=doc)
self.assertTrue('myfile-clear' in six.text_type(form))
self.assertIn('myfile-clear', six.text_type(form))
form = DocumentForm(instance=doc, data={'myfile-clear': 'true'})
doc = form.save(commit=False)
self.assertEqual(bool(doc.myfile), False)
@ -1797,8 +1797,8 @@ class FileAndImageFieldTests(TestCase):
self.assertEqual(form.errors['myfile'],
['Please either submit a file or check the clear checkbox, not both.'])
rendered = six.text_type(form)
self.assertTrue('something.txt' in rendered)
self.assertTrue('myfile-clear' in rendered)
self.assertIn('something.txt', rendered)
self.assertIn('myfile-clear', rendered)
def test_file_field_data(self):
# Test conditions when files is either not given or empty.
@ -2421,7 +2421,7 @@ class FormFieldCallbackTests(TestCase):
fields = "__all__"
Form = modelform_factory(Person, form=BaseForm)
self.assertTrue(Form.base_fields['name'].widget is widget)
self.assertIs(Form.base_fields['name'].widget, widget)
def test_factory_with_widget_argument(self):
""" Regression for #15315: modelform_factory should accept widgets

View File

@ -449,11 +449,11 @@ class ModelFormsetTest(TestCase):
PostFormSet = modelformset_factory(Post, form=PostForm1)
formset = PostFormSet()
self.assertFalse("subtitle" in formset.forms[0].fields)
self.assertNotIn("subtitle", formset.forms[0].fields)
PostFormSet = modelformset_factory(Post, form=PostForm2)
formset = PostFormSet()
self.assertFalse("subtitle" in formset.forms[0].fields)
self.assertNotIn("subtitle", formset.forms[0].fields)
def test_custom_queryset_init(self):
"""

View File

@ -203,7 +203,7 @@ class InlineFormsetTests(TestCase):
UserFormSet = modelformset_factory(User, fields=())
formset = UserFormSet()
for form in formset.forms:
self.assertTrue('id' in form.fields)
self.assertIn('id', form.fields)
self.assertEqual(len(form.fields), 1)
def test_save_as_new_with_new_inlines(self):
@ -247,7 +247,7 @@ class InlineFormsetTests(TestCase):
formset = FormSet(instance=user, initial=[{'data': 41}, {'data': 42}])
self.assertEqual(formset.forms[0].initial['data'], 7)
self.assertEqual(formset.extra_forms[0].initial['data'], 41)
self.assertTrue('value="42"' in formset.extra_forms[1].as_p())
self.assertIn('value="42"', formset.extra_forms[1].as_p())
class FormsetTests(TestCase):
@ -282,7 +282,7 @@ class FormsetTests(TestCase):
formset = Formset(initial=[{'username': 'apollo11'}, {'username': 'apollo12'}])
self.assertEqual(formset.forms[0].initial['username'], "bibi")
self.assertEqual(formset.extra_forms[0].initial['username'], "apollo11")
self.assertTrue('value="apollo12"' in formset.extra_forms[1].as_p())
self.assertIn('value="apollo12"', formset.extra_forms[1].as_p())
def test_extraneous_query_is_not_run(self):
Formset = modelformset_factory(Network, fields="__all__")

View File

@ -609,13 +609,13 @@ class RelatedM2MTests(OptionsBaseTests):
def test_related_m2m_asymmetrical(self):
m2m = Person._meta.many_to_many
self.assertTrue('following_base' in [f.attname for f in m2m])
self.assertIn('following_base', [f.attname for f in m2m])
related_m2m = Person._meta.get_all_related_many_to_many_objects()
self.assertTrue('followers_base' in [o.field.related_query_name() for o in related_m2m])
self.assertIn('followers_base', [o.field.related_query_name() for o in related_m2m])
def test_related_m2m_symmetrical(self):
m2m = Person._meta.many_to_many
self.assertTrue('friends_base' in [f.attname for f in m2m])
self.assertIn('friends_base', [f.attname for f in m2m])
related_m2m = Person._meta.get_all_related_many_to_many_objects()
self.assertIn('friends_inherited_rel_+', [o.field.related_query_name() for o in related_m2m])

View File

@ -1485,7 +1485,7 @@ class AuthTestCase(TestCase):
new_io = StringIO()
management.call_command('dumpdata', 'auth', format='json', database='other', stdout=new_io)
command_output = new_io.getvalue().strip()
self.assertTrue('"email": "alice@example.com"' in command_output)
self.assertIn('"email": "alice@example.com"', command_output)
class AntiPetRouter(object):

View File

@ -35,7 +35,7 @@ class NullFkTests(TestCase):
)
# Regression test for #7530, #7716.
self.assertTrue(Comment.objects.select_related('post').filter(post__isnull=True)[0].post is None)
self.assertIsNone(Comment.objects.select_related('post').filter(post__isnull=True)[0].post)
self.assertQuerysetEqual(
Comment.objects.select_related('post__forum__system_info__system_details'),

View File

@ -22,7 +22,7 @@ class NullFkOrderingTests(TestCase):
# We can't compare results directly (since different databases sort NULLs to
# different ends of the ordering), but we can check that all results are
# returned.
self.assertTrue(len(list(Article.objects.all())) == 3)
self.assertEqual(len(list(Article.objects.all())), 3)
s = SystemInfo.objects.create(system_name='System Info')
f = Forum.objects.create(system_info=s, forum_name='First forum')
@ -39,4 +39,4 @@ class NullFkOrderingTests(TestCase):
# everything else, some sort them afterwards. So we extract the ordered list
# and check the length. Before the fix, this list was too short (some values
# were omitted).
self.assertTrue(len(list(Comment.objects.all())) == 4)
self.assertEqual(len(list(Comment.objects.all())), 4)

View File

@ -190,23 +190,23 @@ class OneToOneTests(TestCase):
r = p.restaurant
# Accessing the related object again returns the exactly same object
self.assertTrue(p.restaurant is r)
self.assertIs(p.restaurant, r)
# But if we kill the cache, we get a new object
del p._restaurant_cache
self.assertFalse(p.restaurant is r)
self.assertIsNot(p.restaurant, r)
# Reassigning the Restaurant object results in an immediate cache update
# We can't use a new Restaurant because that'll violate one-to-one, but
# with a new *instance* the is test below will fail if #6886 regresses.
r2 = Restaurant.objects.get(pk=r.pk)
p.restaurant = r2
self.assertTrue(p.restaurant is r2)
self.assertIs(p.restaurant, r2)
# Assigning None succeeds if field is null=True.
ug_bar = UndergroundBar.objects.create(place=p, serves_cocktails=False)
ug_bar.place = None
self.assertTrue(ug_bar.place is None)
self.assertIsNone(ug_bar.place)
# Assigning None fails: Place.restaurant is null=False
self.assertRaises(ValueError, setattr, p, 'restaurant', None)
@ -217,13 +217,13 @@ class OneToOneTests(TestCase):
# Creation using keyword argument should cache the related object.
p = Place.objects.get(name="Demon Dogs")
r = Restaurant(place=p)
self.assertTrue(r.place is p)
self.assertIs(r.place, p)
# Creation using attname keyword argument and an id will cause the related
# object to be fetched.
p = Place.objects.get(name="Demon Dogs")
r = Restaurant(place_id=p.id)
self.assertFalse(r.place is p)
self.assertIsNot(r.place, p)
self.assertEqual(r.place, p)
def test_filter_one_to_one_relations(self):

View File

@ -213,8 +213,8 @@ class PaginationTests(unittest.TestCase):
eleven = 'abcdefghijk'
page2 = Paginator(eleven, per_page=5, orphans=1).page(2)
self.assertEqual(len(page2), 6)
self.assertTrue('k' in page2)
self.assertFalse('a' in page2)
self.assertIn('k', page2)
self.assertNotIn('a', page2)
self.assertEqual(''.join(page2), 'fghijk')
self.assertEqual(''.join(reversed(page2)), 'kjihgf')

View File

@ -113,7 +113,7 @@ class PrefetchRelatedTests(TestCase):
70679243d1786e03557c28929f9762a119e3ac14.
"""
qs = Book.objects.prefetch_related('first_time_authors')
self.assertTrue(qs[0] in qs)
self.assertIn(qs[0], qs)
def test_clear(self):
"""
@ -211,15 +211,15 @@ class PrefetchRelatedTests(TestCase):
with self.assertRaises(AttributeError) as cm:
list(qs)
self.assertTrue('prefetch_related' in str(cm.exception))
self.assertIn('prefetch_related', str(cm.exception))
def test_invalid_final_lookup(self):
qs = Book.objects.prefetch_related('authors__name')
with self.assertRaises(ValueError) as cm:
list(qs)
self.assertTrue('prefetch_related' in str(cm.exception))
self.assertTrue("name" in str(cm.exception))
self.assertIn('prefetch_related', str(cm.exception))
self.assertIn("name", str(cm.exception))
class CustomPrefetchTests(TestCase):

View File

@ -272,7 +272,7 @@ class ProxyModelTests(TestCase):
def test_content_type(self):
ctype = ContentType.objects.get_for_model
self.assertTrue(ctype(Person) is ctype(OtherPerson))
self.assertIs(ctype(Person), ctype(OtherPerson))
def test_user_userproxy_userproxyproxy(self):
User.objects.create(name='Bruce')
@ -396,9 +396,9 @@ class ProxyModelAdminTests(TestCase):
with self.assertNumQueries(7):
collector = admin.utils.NestedObjects('default')
collector.collect(ProxyTrackerUser.objects.all())
self.assertTrue(tracker_user in collector.edges.get(None, ()))
self.assertTrue(base_user in collector.edges.get(None, ()))
self.assertTrue(issue in collector.edges.get(tracker_user, ()))
self.assertIn(tracker_user, collector.edges.get(None, ()))
self.assertIn(base_user, collector.edges.get(None, ()))
self.assertIn(issue, collector.edges.get(tracker_user, ()))
def test_delete_str_in_model_admin(self):
"""

View File

@ -127,7 +127,7 @@ class Queries1Tests(BaseQuerysetTest):
def test_ticket2306(self):
# Checking that no join types are "left outer" joins.
query = Item.objects.filter(tags=self.t2).query
self.assertTrue(query.LOUTER not in [x[2] for x in query.alias_map.values()])
self.assertNotIn(query.LOUTER, [x[2] for x in query.alias_map.values()])
self.assertQuerysetEqual(
Item.objects.filter(Q(tags=self.t1)).order_by('name'),
@ -335,7 +335,7 @@ class Queries1Tests(BaseQuerysetTest):
# Excluding from a relation that cannot be NULL should not use outer joins.
query = Item.objects.exclude(creator__in=[self.a1, self.a2]).query
self.assertTrue(query.LOUTER not in [x[2] for x in query.alias_map.values()])
self.assertNotIn(query.LOUTER, [x[2] for x in query.alias_map.values()])
# Similarly, when one of the joins cannot possibly, ever, involve NULL
# values (Author -> ExtraInfo, in the following), it should never be
@ -500,7 +500,7 @@ class Queries1Tests(BaseQuerysetTest):
# actually allow both "foo" and "foo_id".
# The *_id version is returned by default.
self.assertTrue('note_id' in ExtraInfo.objects.values()[0])
self.assertIn('note_id', ExtraInfo.objects.values()[0])
# You can also pass it in explicitly.
self.assertValueQuerysetEqual(
@ -777,14 +777,14 @@ class Queries1Tests(BaseQuerysetTest):
self.assertQuerysetEqual(qs, ['<Author: a1>', '<Author: a2>'])
# The subquery result cache should not be populated
self.assertTrue(subq._result_cache is None)
self.assertIsNone(subq._result_cache)
subq = Author.objects.filter(num__lt=3000)
qs = Author.objects.exclude(pk__in=subq)
self.assertQuerysetEqual(qs, ['<Author: a3>', '<Author: a4>'])
# The subquery result cache should not be populated
self.assertTrue(subq._result_cache is None)
self.assertIsNone(subq._result_cache)
subq = Author.objects.filter(num__lt=3000)
self.assertQuerysetEqual(
@ -793,7 +793,7 @@ class Queries1Tests(BaseQuerysetTest):
)
# The subquery result cache should not be populated
self.assertTrue(subq._result_cache is None)
self.assertIsNone(subq._result_cache)
def test_ticket7076(self):
# Excluding shouldn't eliminate NULL entries.
@ -911,7 +911,7 @@ class Queries1Tests(BaseQuerysetTest):
q = Tag.objects.filter(parent__isnull=True)
self.assertQuerysetEqual(q, ['<Tag: t1>'])
self.assertTrue('JOIN' not in str(q.query))
self.assertNotIn('JOIN', str(q.query))
q = Tag.objects.filter(parent__isnull=False)
@ -919,18 +919,18 @@ class Queries1Tests(BaseQuerysetTest):
q,
['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'],
)
self.assertTrue('JOIN' not in str(q.query))
self.assertNotIn('JOIN', str(q.query))
q = Tag.objects.exclude(parent__isnull=True)
self.assertQuerysetEqual(
q,
['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'],
)
self.assertTrue('JOIN' not in str(q.query))
self.assertNotIn('JOIN', str(q.query))
q = Tag.objects.exclude(parent__isnull=False)
self.assertQuerysetEqual(q, ['<Tag: t1>'])
self.assertTrue('JOIN' not in str(q.query))
self.assertNotIn('JOIN', str(q.query))
q = Tag.objects.exclude(parent__parent__isnull=False)
@ -938,8 +938,8 @@ class Queries1Tests(BaseQuerysetTest):
q,
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'],
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 1)
self.assertTrue('INNER JOIN' not in str(q.query))
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1)
self.assertNotIn('INNER JOIN', str(q.query))
def test_ticket_10790_2(self):
# Querying across several tables should strip only the last outer join,
@ -950,8 +950,8 @@ class Queries1Tests(BaseQuerysetTest):
q,
['<Tag: t4>', '<Tag: t5>'],
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
self.assertTrue(str(q.query).count('INNER JOIN') == 1)
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
self.assertEqual(str(q.query).count('INNER JOIN'), 1)
# Querying without isnull should not convert anything to left outer join.
q = Tag.objects.filter(parent__parent=self.t1)
@ -959,22 +959,22 @@ class Queries1Tests(BaseQuerysetTest):
q,
['<Tag: t4>', '<Tag: t5>'],
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
self.assertTrue(str(q.query).count('INNER JOIN') == 1)
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
self.assertEqual(str(q.query).count('INNER JOIN'), 1)
def test_ticket_10790_3(self):
# Querying via indirect fields should populate the left outer join
q = NamedCategory.objects.filter(tag__isnull=True)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 1)
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1)
# join to dumbcategory ptr_id
self.assertTrue(str(q.query).count('INNER JOIN') == 1)
self.assertEqual(str(q.query).count('INNER JOIN'), 1)
self.assertQuerysetEqual(q, [])
# Querying across several tables should strip only the last join, while
# preserving the preceding left outer joins.
q = NamedCategory.objects.filter(tag__parent__isnull=True)
self.assertTrue(str(q.query).count('INNER JOIN') == 1)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 1)
self.assertEqual(str(q.query).count('INNER JOIN'), 1)
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1)
self.assertQuerysetEqual(q, ['<NamedCategory: Generic>'])
def test_ticket_10790_4(self):
@ -984,16 +984,16 @@ class Queries1Tests(BaseQuerysetTest):
q,
['<Author: a2>', '<Author: a3>'],
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 2)
self.assertTrue('INNER JOIN' not in str(q.query))
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 2)
self.assertNotIn('INNER JOIN', str(q.query))
q = Author.objects.filter(item__tags__parent__isnull=True)
self.assertQuerysetEqual(
q,
['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a3>'],
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 3)
self.assertTrue('INNER JOIN' not in str(q.query))
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 3)
self.assertNotIn('INNER JOIN', str(q.query))
def test_ticket_10790_5(self):
# Querying with isnull=False across m2m field should not create outer joins
@ -1002,24 +1002,24 @@ class Queries1Tests(BaseQuerysetTest):
q,
['<Author: a1>', '<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a4>']
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
self.assertTrue(str(q.query).count('INNER JOIN') == 2)
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
self.assertEqual(str(q.query).count('INNER JOIN'), 2)
q = Author.objects.filter(item__tags__parent__isnull=False)
self.assertQuerysetEqual(
q,
['<Author: a1>', '<Author: a2>', '<Author: a4>']
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
self.assertTrue(str(q.query).count('INNER JOIN') == 3)
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
self.assertEqual(str(q.query).count('INNER JOIN'), 3)
q = Author.objects.filter(item__tags__parent__parent__isnull=False)
self.assertQuerysetEqual(
q,
['<Author: a4>']
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
self.assertTrue(str(q.query).count('INNER JOIN') == 4)
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
self.assertEqual(str(q.query).count('INNER JOIN'), 4)
def test_ticket_10790_6(self):
# Querying with isnull=True across m2m field should not create inner joins
@ -1030,16 +1030,16 @@ class Queries1Tests(BaseQuerysetTest):
['<Author: a1>', '<Author: a1>', '<Author: a2>', '<Author: a2>',
'<Author: a2>', '<Author: a3>']
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 4)
self.assertTrue(str(q.query).count('INNER JOIN') == 0)
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 4)
self.assertEqual(str(q.query).count('INNER JOIN'), 0)
q = Author.objects.filter(item__tags__parent__isnull=True)
self.assertQuerysetEqual(
q,
['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a3>']
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 3)
self.assertTrue(str(q.query).count('INNER JOIN') == 0)
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 3)
self.assertEqual(str(q.query).count('INNER JOIN'), 0)
def test_ticket_10790_7(self):
# Reverse querying with isnull should not strip the join
@ -1048,16 +1048,16 @@ class Queries1Tests(BaseQuerysetTest):
q,
['<Author: a3>']
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 1)
self.assertTrue(str(q.query).count('INNER JOIN') == 0)
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1)
self.assertEqual(str(q.query).count('INNER JOIN'), 0)
q = Author.objects.filter(item__isnull=False)
self.assertQuerysetEqual(
q,
['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a4>']
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
self.assertTrue(str(q.query).count('INNER JOIN') == 1)
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
self.assertEqual(str(q.query).count('INNER JOIN'), 1)
def test_ticket_10790_8(self):
# Querying with combined q-objects should also strip the left outer join
@ -1066,8 +1066,8 @@ class Queries1Tests(BaseQuerysetTest):
q,
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
)
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
self.assertTrue(str(q.query).count('INNER JOIN') == 0)
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
self.assertEqual(str(q.query).count('INNER JOIN'), 0)
def test_ticket_10790_combine(self):
# Combining queries should not re-populate the left outer join
@ -1079,13 +1079,13 @@ class Queries1Tests(BaseQuerysetTest):
q3,
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'],
)
self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 0)
self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0)
self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
q3 = q1 & q2
self.assertQuerysetEqual(q3, [])
self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 0)
self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0)
self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
q2 = Tag.objects.filter(parent=self.t1)
q3 = q1 | q2
@ -1093,16 +1093,16 @@ class Queries1Tests(BaseQuerysetTest):
q3,
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
)
self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 0)
self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0)
self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
q3 = q2 | q1
self.assertQuerysetEqual(
q3,
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
)
self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 0)
self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0)
self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
q1 = Tag.objects.filter(parent__isnull=True)
q2 = Tag.objects.filter(parent__parent__isnull=True)
@ -1112,16 +1112,16 @@ class Queries1Tests(BaseQuerysetTest):
q3,
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
)
self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 1)
self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 1)
self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
q3 = q2 | q1
self.assertQuerysetEqual(
q3,
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
)
self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 1)
self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 1)
self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
def test_ticket19672(self):
self.assertQuerysetEqual(
@ -1135,7 +1135,7 @@ class Queries1Tests(BaseQuerysetTest):
qs = Author.objects.annotate(Count('item'))
qs = qs.filter(~Q(extra__value=0))
self.assertTrue('SELECT' in str(qs.query))
self.assertIn('SELECT', str(qs.query))
self.assertQuerysetEqual(
qs,
['<Author: a1>', '<Author: a2>', '<Author: a3>', '<Author: a4>']
@ -1395,7 +1395,7 @@ class Queries4Tests(BaseQuerysetTest):
# Calling order_by() with no parameters removes any existing ordering on the
# model. But it should still be possible to add new ordering after that.
qs = Author.objects.order_by().order_by('name')
self.assertTrue('ORDER BY' in qs.query.get_compiler(qs.db).as_sql()[0])
self.assertIn('ORDER BY', qs.query.get_compiler(qs.db).as_sql()[0])
def test_order_by_reverse_fk(self):
# It is possible to order by reverse of foreign key, although that can lead
@ -1719,9 +1719,9 @@ class NullableRelOrderingTests(TestCase):
r = RelatedObject.objects.create(single=s, f=1)
Plaything.objects.create(name="p2", others=r)
qs = Plaything.objects.all().filter(others__isnull=False).order_by('pk')
self.assertTrue('JOIN' not in str(qs.query))
self.assertNotIn('JOIN', str(qs.query))
qs = Plaything.objects.all().filter(others__f__isnull=False).order_by('pk')
self.assertTrue('INNER' in str(qs.query))
self.assertIn('INNER', str(qs.query))
qs = qs.order_by('others__single__name')
# The ordering by others__single__pk will add one new join (to single)
# and that join must be LEFT join. The already existing join to related
@ -1915,7 +1915,8 @@ class ExistsSql(TestCase):
self.assertEqual(len(captured_queries), 1)
qstr = captured_queries[0]
id, name = connection.ops.quote_name('id'), connection.ops.quote_name('name')
self.assertTrue(id not in qstr and name not in qstr)
self.assertNotIn(id, qstr)
self.assertNotIn(name, qstr)
def test_ticket_18414(self):
Article.objects.create(name='one', created=datetime.datetime.now())
@ -2961,13 +2962,13 @@ class NullJoinPromotionOrTest(TestCase):
def test_null_join_demotion(self):
qs = ModelA.objects.filter(Q(b__name__isnull=False) & Q(b__name__isnull=True))
self.assertTrue(' INNER JOIN ' in str(qs.query))
self.assertIn(' INNER JOIN ', str(qs.query))
qs = ModelA.objects.filter(Q(b__name__isnull=True) & Q(b__name__isnull=False))
self.assertTrue(' INNER JOIN ' in str(qs.query))
self.assertIn(' INNER JOIN ', str(qs.query))
qs = ModelA.objects.filter(Q(b__name__isnull=False) | Q(b__name__isnull=True))
self.assertTrue(' LEFT OUTER JOIN ' in str(qs.query))
self.assertIn(' LEFT OUTER JOIN ', str(qs.query))
qs = ModelA.objects.filter(Q(b__name__isnull=True) | Q(b__name__isnull=False))
self.assertTrue(' LEFT OUTER JOIN ' in str(qs.query))
self.assertIn(' LEFT OUTER JOIN ', str(qs.query))
def test_ticket_21366(self):
n = Note.objects.create(note='n', misc='m')
@ -3314,9 +3315,9 @@ class Ticket20101Tests(TestCase):
n = Note.objects.create(note='foo', misc='bar')
qs1 = Note.objects.exclude(annotation__in=[a1, a2])
qs2 = Note.objects.filter(annotation__in=[a3])
self.assertTrue(n in qs1)
self.assertFalse(n in qs2)
self.assertTrue(n in (qs1 | qs2))
self.assertIn(n, qs1)
self.assertNotIn(n, qs2)
self.assertIn(n, (qs1 | qs2))
class EmptyStringPromotionTests(TestCase):
@ -3545,16 +3546,16 @@ class Ticket21203Tests(TestCase):
class ValuesJoinPromotionTests(TestCase):
def test_values_no_promotion_for_existing(self):
qs = Node.objects.filter(parent__parent__isnull=False)
self.assertTrue(' INNER JOIN ' in str(qs.query))
self.assertIn(' INNER JOIN ', str(qs.query))
qs = qs.values('parent__parent__id')
self.assertTrue(' INNER JOIN ' in str(qs.query))
self.assertIn(' INNER JOIN ', str(qs.query))
# Make sure there is a left outer join without the filter.
qs = Node.objects.values('parent__parent__id')
self.assertTrue(' LEFT OUTER JOIN ' in str(qs.query))
self.assertIn(' LEFT OUTER JOIN ', str(qs.query))
def test_non_nullable_fk_not_promoted(self):
qs = ObjectB.objects.values('objecta__name')
self.assertTrue(' INNER JOIN ' in str(qs.query))
self.assertIn(' INNER JOIN ', str(qs.query))
def test_ticket_21376(self):
a = ObjectA.objects.create()
@ -3567,7 +3568,7 @@ class ValuesJoinPromotionTests(TestCase):
)
self.assertEqual(qs.count(), 1)
tblname = connection.ops.quote_name(ObjectB._meta.db_table)
self.assertTrue(' LEFT OUTER JOIN %s' % tblname in str(qs.query))
self.assertIn(' LEFT OUTER JOIN %s' % tblname, str(qs.query))
class ForeignKeyToBaseExcludeTests(TestCase):

View File

@ -73,9 +73,9 @@ class RawQueryTests(TestCase):
iterated over.
"""
q = Author.objects.raw('SELECT * FROM raw_query_author')
self.assertTrue(q.query.cursor is None)
self.assertIsNone(q.query.cursor)
list(q)
self.assertTrue(q.query.cursor is not None)
self.assertIsNotNone(q.query.cursor)
def test_FK_raw_query(self):
"""

View File

@ -204,7 +204,7 @@ class RequestsTests(SimpleTestCase):
example_cookie = response.cookies['example']
# A compat cookie may be in use -- check that it has worked
# both as an output string, and using the cookie attributes
self.assertTrue('; httponly' in str(example_cookie))
self.assertIn('; httponly', str(example_cookie))
self.assertTrue(example_cookie['httponly'])
def test_unicode_cookie(self):

View File

@ -152,7 +152,7 @@ class SelectRelatedRegressTests(TestCase):
self.assertEqual(qs[0].state, wa)
# The select_related join wasn't promoted as there was already an
# existing (even if trimmed) inner join to state.
self.assertFalse('LEFT OUTER' in str(qs.query))
self.assertNotIn('LEFT OUTER', str(qs.query))
qs = Client.objects.select_related('state').order_by('name')
with self.assertNumQueries(1):
self.assertEqual(list(qs), [bob, jack])
@ -160,7 +160,7 @@ class SelectRelatedRegressTests(TestCase):
self.assertEqual(qs[1].state, wa)
# The select_related join was promoted as there is already an
# existing join.
self.assertTrue('LEFT OUTER' in str(qs.query))
self.assertIn('LEFT OUTER', str(qs.query))
def test_regression_19870(self):
hen = Hen.objects.create(name='Hen')

View File

@ -281,7 +281,7 @@ class TestComplexSettingOverride(TestCase):
def tearDown(self):
signals.COMPLEX_OVERRIDE_SETTINGS = self.old_warn_override_settings
self.assertFalse('TEST_WARN' in signals.COMPLEX_OVERRIDE_SETTINGS)
self.assertNotIn('TEST_WARN', signals.COMPLEX_OVERRIDE_SETTINGS)
def test_complex_override_warning(self):
"""Regression test for #19031"""

View File

@ -403,7 +403,7 @@ class TemplateRegressionTests(TestCase):
while tb.tb_next is not None:
tb = tb.tb_next
depth += 1
self.assertTrue(depth > 5,
self.assertGreater(depth, 5,
"The traceback context was lost when reraising the traceback. See #19827")
@override_settings(DEBUG=True, TEMPLATE_DEBUG=True)
@ -1852,8 +1852,8 @@ class TemplateTagLoading(TestCase):
try:
template.Template(ttext)
except template.TemplateSyntaxError as e:
self.assertTrue('ImportError' in e.args[0])
self.assertTrue('Xtemplate' in e.args[0])
self.assertIn('ImportError', e.args[0])
self.assertIn('Xtemplate', e.args[0])
def test_load_error_egg(self):
ttext = "{% load broken_egg %}"
@ -1866,8 +1866,8 @@ class TemplateTagLoading(TestCase):
with self.settings(INSTALLED_APPS=['tagsegg']):
template.Template(ttext)
except template.TemplateSyntaxError as e:
self.assertTrue('ImportError' in e.args[0])
self.assertTrue('Xtemplate' in e.args[0])
self.assertIn('ImportError', e.args[0])
self.assertIn('Xtemplate', e.args[0])
def test_load_working_egg(self):
ttext = "{% load working_egg %}"

View File

@ -955,7 +955,7 @@ class ContextTests(TestCase):
"Context variables can be retrieved from a single context"
response = self.client.get("/request_data/", data={'foo': 'whiz'})
self.assertEqual(response.context.__class__, Context)
self.assertTrue('get-foo' in response.context)
self.assertIn('get-foo', response.context)
self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['request-foo'], 'whiz')
self.assertEqual(response.context['data'], 'sausage')
@ -971,7 +971,7 @@ class ContextTests(TestCase):
response = self.client.get("/request_data_extended/", data={'foo': 'whiz'})
self.assertEqual(response.context.__class__, ContextList)
self.assertEqual(len(response.context), 2)
self.assertTrue('get-foo' in response.context)
self.assertIn('get-foo', response.context)
self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['request-foo'], 'whiz')
self.assertEqual(response.context['data'], 'bacon')

View File

@ -399,7 +399,7 @@ class DeprecationDisplayTest(AdminScriptTestCase):
args = ['test', '--settings=test_project.settings', '--verbosity=0', 'test_runner_deprecation_app']
out, err = self.run_django_admin(args)
self.assertIn("Ran 1 test", err)
self.assertFalse("warning from test" in err)
self.assertNotIn("warning from test", err)
class AutoIncrementResetTest(TransactionTestCase):

View File

@ -542,24 +542,24 @@ class HTMLEqualTests(TestCase):
# equal html contains each other
dom1 = parse_html('<p>foo')
dom2 = parse_html('<p>foo</p>')
self.assertTrue(dom1 in dom2)
self.assertTrue(dom2 in dom1)
self.assertIn(dom1, dom2)
self.assertIn(dom2, dom1)
dom2 = parse_html('<div><p>foo</p></div>')
self.assertTrue(dom1 in dom2)
self.assertTrue(dom2 not in dom1)
self.assertIn(dom1, dom2)
self.assertNotIn(dom2, dom1)
self.assertFalse('<p>foo</p>' in dom2)
self.assertTrue('foo' in dom2)
self.assertNotIn('<p>foo</p>', dom2)
self.assertIn('foo', dom2)
# when a root element is used ...
dom1 = parse_html('<p>foo</p><p>bar</p>')
dom2 = parse_html('<p>foo</p><p>bar</p>')
self.assertTrue(dom1 in dom2)
self.assertIn(dom1, dom2)
dom1 = parse_html('<p>foo</p>')
self.assertTrue(dom1 in dom2)
self.assertIn(dom1, dom2)
dom1 = parse_html('<p>bar</p>')
self.assertTrue(dom1 in dom2)
self.assertIn(dom1, dom2)
def test_count(self):
# equal html contains each other one time

View File

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

View File

@ -204,10 +204,10 @@ class UpdateOnlyFieldsTests(TestCase):
p.save(update_fields=['name'])
self.assertEqual(len(pre_save_data), 1)
self.assertEqual(len(pre_save_data[0]), 1)
self.assertTrue('name' in pre_save_data[0])
self.assertIn('name', pre_save_data[0])
self.assertEqual(len(post_save_data), 1)
self.assertEqual(len(post_save_data[0]), 1)
self.assertTrue('name' in post_save_data[0])
self.assertIn('name', post_save_data[0])
pre_save.disconnect(pre_save_receiver)
post_save.disconnect(post_save_receiver)

View File

@ -292,7 +292,7 @@ class ResolverTests(unittest.TestCase):
self.fail('resolve did not raise a 404')
except Resolver404 as e:
# make sure we at least matched the root ('/') url resolver:
self.assertTrue('tried' in e.args[0])
self.assertIn('tried', e.args[0])
tried = e.args[0]['tried']
self.assertEqual(len(e.args[0]['tried']), len(url_types_names), 'Wrong number of tried URLs returned. Expected %s, got %s.' % (len(url_types_names), len(e.args[0]['tried'])))
for tried, expected in zip(e.args[0]['tried'], url_types_names):
@ -300,7 +300,7 @@ class ResolverTests(unittest.TestCase):
self.assertIsInstance(t, e['type']), str('%s is not an instance of %s') % (t, e['type'])
if 'name' in e:
if not e['name']:
self.assertTrue(t.name is None, 'Expected no URL name but found %s.' % t.name)
self.assertIsNone(t.name, 'Expected no URL name but found %s.' % t.name)
else:
self.assertEqual(t.name, e['name'], 'Wrong URL name. Expected "%s", got "%s".' % (e['name'], t.name))

View File

@ -177,7 +177,7 @@ class MergeDictTests(IgnoreDeprecationWarningsMixin, SimpleTestCase):
self.assertEqual(sorted(six.iterkeys(mm)), ['key1', 'key2', 'key4'])
self.assertEqual(len(list(six.itervalues(mm))), 3)
self.assertTrue('value1' in six.itervalues(mm))
self.assertIn('value1', six.itervalues(mm))
self.assertEqual(
sorted(six.iteritems(mm), key=lambda k: k[0]),

View File

@ -20,7 +20,7 @@ class FunctionalTestCase(unittest.TestCase):
pass
t = lazy(lambda: Klazz(), Klazz)()
self.assertTrue('base_method' in dir(t))
self.assertIn('base_method', dir(t))
def test_lazy_property(self):

View File

@ -47,7 +47,7 @@ class TestUtilsHttp(unittest.TestCase):
'c=3&a=1&b=2',
'c=3&b=2&a=1'
]
self.assertTrue(result in acceptable_results)
self.assertIn(result, acceptable_results)
result = http.urlencode({'a': [1, 2]}, doseq=False)
self.assertEqual(result, 'a=%5B%271%27%2C+%272%27%5D')
result = http.urlencode({'a': [1, 2]}, doseq=True)
@ -65,7 +65,7 @@ class TestUtilsHttp(unittest.TestCase):
'name=Adrian&name=Simon&position=Developer',
'position=Developer&name=Adrian&name=Simon'
]
self.assertTrue(result in acceptable_results)
self.assertIn(result, acceptable_results)
def test_base36(self):
# reciprocity works

View File

@ -257,8 +257,8 @@ class SimpleLazyObjectTestCase(LazyObjectTestCase):
self.assertEqual(lazydict['one'], 1)
lazydict['one'] = -1
self.assertEqual(lazydict['one'], -1)
self.assertTrue('one' in lazydict)
self.assertFalse('two' in lazydict)
self.assertIn('one', lazydict)
self.assertNotIn('two', lazydict)
self.assertEqual(len(lazydict), 1)
del lazydict['one']
with self.assertRaises(KeyError):
@ -267,9 +267,9 @@ class SimpleLazyObjectTestCase(LazyObjectTestCase):
def test_list_set(self):
lazy_list = SimpleLazyObject(lambda: [1, 2, 3, 4, 5])
lazy_set = SimpleLazyObject(lambda: {1, 2, 3, 4})
self.assertTrue(1 in lazy_list)
self.assertTrue(1 in lazy_set)
self.assertFalse(6 in lazy_list)
self.assertFalse(6 in lazy_set)
self.assertIn(1, lazy_list)
self.assertIn(1, lazy_set)
self.assertNotIn(6, lazy_list)
self.assertNotIn(6, lazy_set)
self.assertEqual(len(lazy_list), 5)
self.assertEqual(len(lazy_set), 4)

View File

@ -115,7 +115,7 @@ class DebugViewTests(TestCase):
# '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"'
self.assertContains(response, '<div class="context" id="', status_code=500)
match = re.search(b'<div class="context" id="(?P<id>[^"]+)">', response.content)
self.assertFalse(match is None)
self.assertIsNotNone(match)
id_repr = match.group('id')
self.assertFalse(re.search(b'[^c0-9]', id_repr),
"Numeric IDs in debug response HTML page shouldn't be localized (value: %s)." % id_repr)
@ -126,7 +126,7 @@ class DebugViewTests(TestCase):
self.client.get(reverse('template_exception', args=(n,)))
except Exception:
raising_loc = inspect.trace()[-1][-2][0].strip()
self.assertFalse(raising_loc.find('raise BrokenException') == -1,
self.assertNotEqual(raising_loc.find('raise BrokenException'), -1,
"Failed to find 'raise BrokenException' in last frame of traceback, instead found: %s" %
raising_loc)

View File

@ -64,7 +64,7 @@ class GetInternalWSGIApplicationTest(unittest.TestCase):
from .wsgi import application
self.assertTrue(app is application)
self.assertIs(app, application)
@override_settings(WSGI_APPLICATION=None)
def test_default(self):
@ -85,7 +85,7 @@ class GetInternalWSGIApplicationTest(unittest.TestCase):
try:
app = get_internal_wsgi_application()
self.assertTrue(app is fake_app)
self.assertIs(app, fake_app)
finally:
basehttp.get_wsgi_application = _orig_get_wsgi_app