Fixed #23620 -- Used more specific assertions in the Django test suite.
This commit is contained in:
parent
c0c78f1b70
commit
f7969b0920
|
@ -45,10 +45,10 @@ class PermWrapperTests(TestCase):
|
||||||
"""
|
"""
|
||||||
perms = PermWrapper(MockUser())
|
perms = PermWrapper(MockUser())
|
||||||
# Works for modules and full permissions.
|
# Works for modules and full permissions.
|
||||||
self.assertTrue('mockapp' in perms)
|
self.assertIn('mockapp', perms)
|
||||||
self.assertFalse('nonexisting' in perms)
|
self.assertNotIn('nonexisting', perms)
|
||||||
self.assertTrue('mockapp.someperm' in perms)
|
self.assertIn('mockapp.someperm', perms)
|
||||||
self.assertFalse('mockapp.nonexisting' in perms)
|
self.assertNotIn('mockapp.nonexisting', perms)
|
||||||
|
|
||||||
def test_permlookupdict_in(self):
|
def test_permlookupdict_in(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -42,7 +42,7 @@ class LoginRequiredTestCase(AuthViewsTestCase):
|
||||||
login_url = settings.LOGIN_URL
|
login_url = settings.LOGIN_URL
|
||||||
response = self.client.get(view_url)
|
response = self.client.get(view_url)
|
||||||
self.assertEqual(response.status_code, 302)
|
self.assertEqual(response.status_code, 302)
|
||||||
self.assertTrue(login_url in response.url)
|
self.assertIn(login_url, response.url)
|
||||||
self.login()
|
self.login()
|
||||||
response = self.client.get(view_url)
|
response = self.client.get(view_url)
|
||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
|
@ -29,7 +29,7 @@ class ModWsgiHandlerTestCase(TransactionTestCase):
|
||||||
User.objects.create_user('test', 'test@example.com', 'test')
|
User.objects.create_user('test', 'test@example.com', 'test')
|
||||||
|
|
||||||
# User not in database
|
# User not in database
|
||||||
self.assertTrue(check_password({}, 'unknown', '') is None)
|
self.assertIsNone(check_password({}, 'unknown', ''))
|
||||||
|
|
||||||
# Valid user with correct password
|
# Valid user with correct password
|
||||||
self.assertTrue(check_password({}, 'test', 'test'))
|
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')
|
CustomUser._default_manager.create_user('test@example.com', '1990-01-01', 'test')
|
||||||
|
|
||||||
# User not in database
|
# User not in database
|
||||||
self.assertTrue(check_password({}, 'unknown', '') is None)
|
self.assertIsNone(check_password({}, 'unknown', ''))
|
||||||
|
|
||||||
# Valid user with correct password'
|
# Valid user with correct password'
|
||||||
self.assertTrue(check_password({}, 'test@example.com', 'test'))
|
self.assertTrue(check_password({}, 'test@example.com', 'test'))
|
||||||
|
|
|
@ -44,7 +44,7 @@ class SignalTestCase(TestCase):
|
||||||
self.assertEqual(len(self.login_failed), 1)
|
self.assertEqual(len(self.login_failed), 1)
|
||||||
self.assertEqual(self.login_failed[0]['username'], 'testclient')
|
self.assertEqual(self.login_failed[0]['username'], 'testclient')
|
||||||
# verify the password is cleansed
|
# verify the password is cleansed
|
||||||
self.assertTrue('***' in self.login_failed[0]['password'])
|
self.assertIn('***', self.login_failed[0]['password'])
|
||||||
|
|
||||||
# Like this:
|
# Like this:
|
||||||
self.client.login(username='testclient', password='password')
|
self.client.login(username='testclient', password='password')
|
||||||
|
|
|
@ -55,13 +55,13 @@ class AuthViewsTestCase(TestCase):
|
||||||
'username': username,
|
'username': username,
|
||||||
'password': password,
|
'password': password,
|
||||||
})
|
})
|
||||||
self.assertTrue(SESSION_KEY in self.client.session)
|
self.assertIn(SESSION_KEY, self.client.session)
|
||||||
return response
|
return response
|
||||||
|
|
||||||
def logout(self):
|
def logout(self):
|
||||||
response = self.client.get('/admin/logout/')
|
response = self.client.get('/admin/logout/')
|
||||||
self.assertEqual(response.status_code, 200)
|
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):
|
def assertFormError(self, response, error):
|
||||||
"""Assert that error is found in response.context['form'] errors"""
|
"""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'})
|
response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
|
||||||
self.assertEqual(response.status_code, 302)
|
self.assertEqual(response.status_code, 302)
|
||||||
self.assertEqual(len(mail.outbox), 1)
|
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)
|
self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email)
|
||||||
# optional multipart text/html email has been added. Make sure original,
|
# optional multipart text/html email has been added. Make sure original,
|
||||||
# default functionality is 100% the same
|
# default functionality is 100% the same
|
||||||
|
@ -148,8 +148,8 @@ class PasswordResetTest(AuthViewsTestCase):
|
||||||
self.assertTrue(message.is_multipart())
|
self.assertTrue(message.is_multipart())
|
||||||
self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain')
|
self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain')
|
||||||
self.assertEqual(message.get_payload(1).get_content_type(), 'text/html')
|
self.assertEqual(message.get_payload(1).get_content_type(), 'text/html')
|
||||||
self.assertTrue('<html>' not in message.get_payload(0).get_payload())
|
self.assertNotIn('<html>', message.get_payload(0).get_payload())
|
||||||
self.assertTrue('<html>' in message.get_payload(1).get_payload())
|
self.assertIn('<html>', message.get_payload(1).get_payload())
|
||||||
|
|
||||||
def test_email_found_custom_from(self):
|
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."
|
"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(response.status_code, 302)
|
||||||
self.assertEqual(len(mail.outbox), 1)
|
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)
|
self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email)
|
||||||
|
|
||||||
# Skip any 500 handler action (like sending more mail...)
|
# Skip any 500 handler action (like sending more mail...)
|
||||||
|
@ -215,7 +215,7 @@ class PasswordResetTest(AuthViewsTestCase):
|
||||||
|
|
||||||
def _read_signup_email(self, email):
|
def _read_signup_email(self, email):
|
||||||
urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
|
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]
|
return urlmatch.group(), urlmatch.groups()[0]
|
||||||
|
|
||||||
def test_confirm_valid(self):
|
def test_confirm_valid(self):
|
||||||
|
@ -346,7 +346,7 @@ class CustomUserPasswordResetTest(AuthViewsTestCase):
|
||||||
|
|
||||||
def _read_signup_email(self, email):
|
def _read_signup_email(self, email):
|
||||||
urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
|
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]
|
return urlmatch.group(), urlmatch.groups()[0]
|
||||||
|
|
||||||
def test_confirm_valid_custom_user(self):
|
def test_confirm_valid_custom_user(self):
|
||||||
|
@ -502,7 +502,7 @@ class LoginTest(AuthViewsTestCase):
|
||||||
'password': password,
|
'password': password,
|
||||||
})
|
})
|
||||||
self.assertEqual(response.status_code, 302)
|
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)
|
"%s should be blocked" % bad_url)
|
||||||
|
|
||||||
# These URLs *should* still pass the security check
|
# These URLs *should* still pass the security check
|
||||||
|
@ -524,8 +524,7 @@ class LoginTest(AuthViewsTestCase):
|
||||||
'password': password,
|
'password': password,
|
||||||
})
|
})
|
||||||
self.assertEqual(response.status_code, 302)
|
self.assertEqual(response.status_code, 302)
|
||||||
self.assertTrue(good_url in response.url,
|
self.assertIn(good_url, response.url, "%s should be allowed" % good_url)
|
||||||
"%s should be allowed" % good_url)
|
|
||||||
|
|
||||||
def test_login_form_contains_request(self):
|
def test_login_form_contains_request(self):
|
||||||
# 15198
|
# 15198
|
||||||
|
@ -683,7 +682,7 @@ class LoginRedirectUrlTest(AuthViewsTestCase):
|
||||||
class LogoutTest(AuthViewsTestCase):
|
class LogoutTest(AuthViewsTestCase):
|
||||||
|
|
||||||
def confirm_logged_out(self):
|
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):
|
def test_logout_default(self):
|
||||||
"Logout without next_page option renders the default template"
|
"Logout without next_page option renders the default template"
|
||||||
|
@ -696,7 +695,7 @@ class LogoutTest(AuthViewsTestCase):
|
||||||
# Bug 14377
|
# Bug 14377
|
||||||
self.login()
|
self.login()
|
||||||
response = self.client.get('/logout/')
|
response = self.client.get('/logout/')
|
||||||
self.assertTrue('site' in response.context)
|
self.assertIn('site', response.context)
|
||||||
|
|
||||||
def test_logout_with_overridden_redirect_url(self):
|
def test_logout_with_overridden_redirect_url(self):
|
||||||
# Bug 11223
|
# Bug 11223
|
||||||
|
@ -762,7 +761,7 @@ class LogoutTest(AuthViewsTestCase):
|
||||||
self.login()
|
self.login()
|
||||||
response = self.client.get(nasty_url)
|
response = self.client.get(nasty_url)
|
||||||
self.assertEqual(response.status_code, 302)
|
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)
|
"%s should be blocked" % bad_url)
|
||||||
self.confirm_logged_out()
|
self.confirm_logged_out()
|
||||||
|
|
||||||
|
@ -783,8 +782,7 @@ class LogoutTest(AuthViewsTestCase):
|
||||||
self.login()
|
self.login()
|
||||||
response = self.client.get(safe_url)
|
response = self.client.get(safe_url)
|
||||||
self.assertEqual(response.status_code, 302)
|
self.assertEqual(response.status_code, 302)
|
||||||
self.assertTrue(good_url in response.url,
|
self.assertIn(good_url, response.url, "%s should be allowed" % good_url)
|
||||||
"%s should be allowed" % good_url)
|
|
||||||
self.confirm_logged_out()
|
self.confirm_logged_out()
|
||||||
|
|
||||||
def test_logout_preserve_language(self):
|
def test_logout_preserve_language(self):
|
||||||
|
|
|
@ -436,17 +436,13 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
|
||||||
def test_polygon_comparison(self):
|
def test_polygon_comparison(self):
|
||||||
p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
|
p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
|
||||||
p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0)))
|
p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0)))
|
||||||
self.assertTrue(p1 > p2)
|
self.assertGreater(p1, p2)
|
||||||
self.assertFalse(p1 < p2)
|
self.assertLess(p2, p1)
|
||||||
self.assertFalse(p2 > p1)
|
|
||||||
self.assertTrue(p2 < p1)
|
|
||||||
|
|
||||||
p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0)))
|
p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0)))
|
||||||
p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0)))
|
p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0)))
|
||||||
self.assertFalse(p4 < p3)
|
self.assertGreater(p4, p3)
|
||||||
self.assertTrue(p3 < p4)
|
self.assertLess(p3, p4)
|
||||||
self.assertTrue(p4 > p3)
|
|
||||||
self.assertFalse(p3 > p4)
|
|
||||||
|
|
||||||
def test_multipolygons(self):
|
def test_multipolygons(self):
|
||||||
"Testing MultiPolygon objects."
|
"Testing MultiPolygon objects."
|
||||||
|
@ -911,7 +907,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
|
||||||
g1 = g.transform(4326, clone=True)
|
g1 = g.transform(4326, clone=True)
|
||||||
self.assertEqual(g1.tuple, g.tuple)
|
self.assertEqual(g1.tuple, g.tuple)
|
||||||
self.assertEqual(g1.srid, 4326)
|
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
|
old_has_gdal = gdal.HAS_GDAL
|
||||||
try:
|
try:
|
||||||
|
@ -927,7 +923,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
|
||||||
g1 = g.transform(4326, clone=True)
|
g1 = g.transform(4326, clone=True)
|
||||||
self.assertEqual(g1.tuple, g.tuple)
|
self.assertEqual(g1.tuple, g.tuple)
|
||||||
self.assertEqual(g1.srid, 4326)
|
self.assertEqual(g1.srid, 4326)
|
||||||
self.assertTrue(g1 is not g, "Clone didn't happen")
|
self.assertIsNot(g1, g, "Clone didn't happen")
|
||||||
finally:
|
finally:
|
||||||
gdal.HAS_GDAL = old_has_gdal
|
gdal.HAS_GDAL = old_has_gdal
|
||||||
|
|
||||||
|
|
|
@ -391,35 +391,34 @@ class ListMixinTest(unittest.TestCase):
|
||||||
|
|
||||||
pl, ul = self.lists_of_len()
|
pl, ul = self.lists_of_len()
|
||||||
self.assertEqual(pl, ul, 'cmp for equal')
|
self.assertEqual(pl, ul, 'cmp for equal')
|
||||||
self.assertFalse(ul == pl + [2], 'cmp for not equal')
|
self.assertNotEqual(ul, pl + [2], 'cmp for not equal')
|
||||||
self.assertTrue(pl >= ul, 'cmp for gte self')
|
self.assertGreaterEqual(pl, ul, 'cmp for gte self')
|
||||||
self.assertTrue(pl <= ul, 'cmp for lte self')
|
self.assertLessEqual(pl, ul, 'cmp for lte self')
|
||||||
self.assertTrue(ul >= pl, 'cmp for self gte')
|
self.assertGreaterEqual(ul, pl, 'cmp for self gte')
|
||||||
self.assertTrue(ul <= pl, 'cmp for self lte')
|
self.assertLessEqual(ul, pl, 'cmp for self lte')
|
||||||
|
|
||||||
self.assertTrue(pl + [5] > ul, 'cmp')
|
self.assertGreater(pl + [5], ul, 'cmp')
|
||||||
self.assertTrue(pl + [5] >= ul, 'cmp')
|
self.assertGreaterEqual(pl + [5], ul, 'cmp')
|
||||||
self.assertTrue(pl < ul + [2], 'cmp')
|
self.assertLess(pl, ul + [2], 'cmp')
|
||||||
self.assertTrue(pl <= ul + [2], 'cmp')
|
self.assertLessEqual(pl, ul + [2], 'cmp')
|
||||||
self.assertTrue(ul + [5] > pl, 'cmp')
|
self.assertGreater(ul + [5], pl, 'cmp')
|
||||||
self.assertTrue(ul + [5] >= pl, 'cmp')
|
self.assertGreaterEqual(ul + [5], pl, 'cmp')
|
||||||
self.assertTrue(ul < pl + [2], 'cmp')
|
self.assertLess(ul, pl + [2], 'cmp')
|
||||||
self.assertTrue(ul <= pl + [2], 'cmp')
|
self.assertLessEqual(ul, pl + [2], 'cmp')
|
||||||
|
|
||||||
# Also works with a custom IndexError
|
# Also works with a custom IndexError
|
||||||
ul_longer = ul + [2]
|
ul_longer = ul + [2]
|
||||||
ul_longer._IndexError = TypeError
|
ul_longer._IndexError = TypeError
|
||||||
ul._IndexError = TypeError
|
ul._IndexError = TypeError
|
||||||
self.assertFalse(ul_longer == pl)
|
self.assertNotEqual(ul_longer, pl)
|
||||||
self.assertFalse(ul == ul_longer)
|
self.assertGreater(ul_longer, ul)
|
||||||
self.assertTrue(ul_longer > ul)
|
|
||||||
|
|
||||||
pl[1] = 20
|
pl[1] = 20
|
||||||
self.assertTrue(pl > ul, 'cmp for gt self')
|
self.assertGreater(pl, ul, 'cmp for gt self')
|
||||||
self.assertTrue(ul < pl, 'cmp for self lt')
|
self.assertLess(ul, pl, 'cmp for self lt')
|
||||||
pl[1] = -20
|
pl[1] = -20
|
||||||
self.assertTrue(pl < ul, 'cmp for lt self')
|
self.assertLess(pl, ul, 'cmp for lt self')
|
||||||
self.assertTrue(pl < ul, 'cmp for lt self')
|
self.assertGreater(ul, pl, 'cmp for gt self')
|
||||||
|
|
||||||
|
|
||||||
class ListMixinTestSingle(ListMixinTest):
|
class ListMixinTestSingle(ListMixinTest):
|
||||||
|
|
|
@ -228,8 +228,8 @@ class RelatedGeoModelTest(TestCase):
|
||||||
combined = qs1 | qs2
|
combined = qs1 | qs2
|
||||||
names = [c.name for c in combined]
|
names = [c.name for c in combined]
|
||||||
self.assertEqual(2, len(names))
|
self.assertEqual(2, len(names))
|
||||||
self.assertTrue('Aurora' in names)
|
self.assertIn('Aurora', names)
|
||||||
self.assertTrue('Kecksburg' in names)
|
self.assertIn('Kecksburg', names)
|
||||||
|
|
||||||
def test11_geoquery_pickle(self):
|
def test11_geoquery_pickle(self):
|
||||||
"Ensuring GeoQuery objects are unpickled correctly. See #10839."
|
"Ensuring GeoQuery objects are unpickled correctly. See #10839."
|
||||||
|
|
|
@ -174,7 +174,7 @@ class SpecializedFieldTest(SimpleTestCase):
|
||||||
self.assertFalse(PointForm().is_valid())
|
self.assertFalse(PointForm().is_valid())
|
||||||
invalid = PointForm(data={'p': 'some invalid geom'})
|
invalid = PointForm(data={'p': 'some invalid geom'})
|
||||||
self.assertFalse(invalid.is_valid())
|
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']:
|
for invalid in [geo for key, geo in self.geometries.items() if key != 'point']:
|
||||||
self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid())
|
self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid())
|
||||||
|
|
|
@ -122,9 +122,9 @@ class DistanceTest(unittest.TestCase):
|
||||||
d2 = D(km=1)
|
d2 = D(km=1)
|
||||||
d3 = D(km=0)
|
d3 = D(km=0)
|
||||||
|
|
||||||
self.assertTrue(d2 > d1)
|
self.assertGreater(d2, d1)
|
||||||
self.assertTrue(d1 == d1)
|
self.assertEqual(d1, d1)
|
||||||
self.assertTrue(d1 < d2)
|
self.assertLess(d1, d2)
|
||||||
self.assertFalse(d3)
|
self.assertFalse(d3)
|
||||||
|
|
||||||
def testUnitsStr(self):
|
def testUnitsStr(self):
|
||||||
|
@ -249,9 +249,9 @@ class AreaTest(unittest.TestCase):
|
||||||
a2 = A(sq_km=1)
|
a2 = A(sq_km=1)
|
||||||
a3 = A(sq_km=0)
|
a3 = A(sq_km=0)
|
||||||
|
|
||||||
self.assertTrue(a2 > a1)
|
self.assertGreater(a2, a1)
|
||||||
self.assertTrue(a1 == a1)
|
self.assertEqual(a1, a1)
|
||||||
self.assertTrue(a1 < a2)
|
self.assertLess(a1, a2)
|
||||||
self.assertFalse(a3)
|
self.assertFalse(a3)
|
||||||
|
|
||||||
def testUnitsStr(self):
|
def testUnitsStr(self):
|
||||||
|
|
|
@ -163,7 +163,7 @@ class BaseTests(object):
|
||||||
add_url = reverse('add_message', args=(level,))
|
add_url = reverse('add_message', args=(level,))
|
||||||
response = self.client.post(add_url, data, follow=True)
|
response = self.client.post(add_url, data, follow=True)
|
||||||
self.assertRedirects(response, show_url)
|
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']]
|
messages = [Message(self.levels[level], msg) for msg in data['messages']]
|
||||||
self.assertEqual(list(response.context['messages']), messages)
|
self.assertEqual(list(response.context['messages']), messages)
|
||||||
for msg in data['messages']:
|
for msg in data['messages']:
|
||||||
|
@ -179,7 +179,7 @@ class BaseTests(object):
|
||||||
add_url = reverse('add_template_response', args=(level,))
|
add_url = reverse('add_template_response', args=(level,))
|
||||||
response = self.client.post(add_url, data, follow=True)
|
response = self.client.post(add_url, data, follow=True)
|
||||||
self.assertRedirects(response, show_url)
|
self.assertRedirects(response, show_url)
|
||||||
self.assertTrue('messages' in response.context)
|
self.assertIn('messages', response.context)
|
||||||
for msg in data['messages']:
|
for msg in data['messages']:
|
||||||
self.assertContains(response, msg)
|
self.assertContains(response, msg)
|
||||||
|
|
||||||
|
@ -192,7 +192,7 @@ class BaseTests(object):
|
||||||
show_url = reverse('show_template_response')
|
show_url = reverse('show_template_response')
|
||||||
response = self.client.get(show_url)
|
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)
|
self.assertEqual(response.context['DEFAULT_MESSAGE_LEVELS'], DEFAULT_LEVELS)
|
||||||
|
|
||||||
@override_settings(MESSAGE_LEVEL=constants.DEBUG)
|
@override_settings(MESSAGE_LEVEL=constants.DEBUG)
|
||||||
|
@ -211,7 +211,7 @@ class BaseTests(object):
|
||||||
add_url = reverse('add_message', args=(level,))
|
add_url = reverse('add_message', args=(level,))
|
||||||
self.client.post(add_url, data)
|
self.client.post(add_url, data)
|
||||||
response = self.client.get(show_url)
|
response = self.client.get(show_url)
|
||||||
self.assertTrue('messages' in response.context)
|
self.assertIn('messages', response.context)
|
||||||
self.assertEqual(list(response.context['messages']), messages)
|
self.assertEqual(list(response.context['messages']), messages)
|
||||||
for msg in data['messages']:
|
for msg in data['messages']:
|
||||||
self.assertContains(response, msg)
|
self.assertContains(response, msg)
|
||||||
|
@ -255,7 +255,7 @@ class BaseTests(object):
|
||||||
add_url = reverse('add_message', args=(level,))
|
add_url = reverse('add_message', args=(level,))
|
||||||
response = self.client.post(add_url, data, follow=True)
|
response = self.client.post(add_url, data, follow=True)
|
||||||
self.assertRedirects(response, show_url)
|
self.assertRedirects(response, show_url)
|
||||||
self.assertFalse('messages' in response.context)
|
self.assertNotIn('messages', response.context)
|
||||||
|
|
||||||
def stored_messages_count(self, storage, response):
|
def stored_messages_count(self, storage, response):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -65,7 +65,7 @@ class CookieTest(BaseTests, TestCase):
|
||||||
response = self.get_response()
|
response = self.get_response()
|
||||||
storage.add(constants.INFO, 'test')
|
storage.add(constants.INFO, 'test')
|
||||||
storage.update(response)
|
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']['domain'], '.example.com')
|
||||||
self.assertEqual(response.cookies['messages']['expires'], '')
|
self.assertEqual(response.cookies['messages']['expires'], '')
|
||||||
self.assertEqual(response.cookies['messages']['secure'], True)
|
self.assertEqual(response.cookies['messages']['secure'], True)
|
||||||
|
@ -114,7 +114,7 @@ class CookieTest(BaseTests, TestCase):
|
||||||
self.assertEqual(cookie_storing, 4)
|
self.assertEqual(cookie_storing, 4)
|
||||||
|
|
||||||
self.assertEqual(len(unstored_messages), 1)
|
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):
|
def test_json_encoder_decoder(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -286,7 +286,7 @@ class SessionTestsMixin(object):
|
||||||
self.assertEqual({}, self.session.decode(bad_encode))
|
self.assertEqual({}, self.session.decode(bad_encode))
|
||||||
# check that the failed decode is logged
|
# check that the failed decode is logged
|
||||||
self.assertEqual(len(calls), 1)
|
self.assertEqual(len(calls), 1)
|
||||||
self.assertTrue('corrupted' in calls[0])
|
self.assertIn('corrupted', calls[0])
|
||||||
|
|
||||||
def test_actual_expiry(self):
|
def test_actual_expiry(self):
|
||||||
# this doesn't work with JSONSerializer (serializing timedelta)
|
# this doesn't work with JSONSerializer (serializing timedelta)
|
||||||
|
|
|
@ -93,7 +93,7 @@ class ChangeListTests(TestCase):
|
||||||
table_output = template.render(context)
|
table_output = template.render(context)
|
||||||
link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
|
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
|
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)
|
'Failed to find expected row element: %s' % table_output)
|
||||||
|
|
||||||
def test_result_list_html(self):
|
def test_result_list_html(self):
|
||||||
|
@ -116,7 +116,7 @@ class ChangeListTests(TestCase):
|
||||||
table_output = template.render(context)
|
table_output = template.render(context)
|
||||||
link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
|
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
|
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)
|
'Failed to find expected row element: %s' % table_output)
|
||||||
|
|
||||||
def test_result_list_editable_html(self):
|
def test_result_list_editable_html(self):
|
||||||
|
|
|
@ -130,38 +130,38 @@ class XViewMiddlewareTest(AdminDocsTestCase):
|
||||||
def test_xview_func(self):
|
def test_xview_func(self):
|
||||||
user = User.objects.get(username='super')
|
user = User.objects.get(username='super')
|
||||||
response = self.client.head('/xview/func/')
|
response = self.client.head('/xview/func/')
|
||||||
self.assertFalse('X-View' in response)
|
self.assertNotIn('X-View', response)
|
||||||
self.client.login(username='super', password='secret')
|
self.client.login(username='super', password='secret')
|
||||||
response = self.client.head('/xview/func/')
|
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')
|
self.assertEqual(response['X-View'], 'admin_docs.views.xview')
|
||||||
user.is_staff = False
|
user.is_staff = False
|
||||||
user.save()
|
user.save()
|
||||||
response = self.client.head('/xview/func/')
|
response = self.client.head('/xview/func/')
|
||||||
self.assertFalse('X-View' in response)
|
self.assertNotIn('X-View', response)
|
||||||
user.is_staff = True
|
user.is_staff = True
|
||||||
user.is_active = False
|
user.is_active = False
|
||||||
user.save()
|
user.save()
|
||||||
response = self.client.head('/xview/func/')
|
response = self.client.head('/xview/func/')
|
||||||
self.assertFalse('X-View' in response)
|
self.assertNotIn('X-View', response)
|
||||||
|
|
||||||
def test_xview_class(self):
|
def test_xview_class(self):
|
||||||
user = User.objects.get(username='super')
|
user = User.objects.get(username='super')
|
||||||
response = self.client.head('/xview/class/')
|
response = self.client.head('/xview/class/')
|
||||||
self.assertFalse('X-View' in response)
|
self.assertNotIn('X-View', response)
|
||||||
self.client.login(username='super', password='secret')
|
self.client.login(username='super', password='secret')
|
||||||
response = self.client.head('/xview/class/')
|
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')
|
self.assertEqual(response['X-View'], 'admin_docs.views.XViewClass')
|
||||||
user.is_staff = False
|
user.is_staff = False
|
||||||
user.save()
|
user.save()
|
||||||
response = self.client.head('/xview/class/')
|
response = self.client.head('/xview/class/')
|
||||||
self.assertFalse('X-View' in response)
|
self.assertNotIn('X-View', response)
|
||||||
user.is_staff = True
|
user.is_staff = True
|
||||||
user.is_active = False
|
user.is_active = False
|
||||||
user.save()
|
user.save()
|
||||||
response = self.client.head('/xview/class/')
|
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.")
|
@unittest.skipUnless(utils.docutils_is_available, "no docutils installed.")
|
||||||
|
|
|
@ -190,12 +190,12 @@ class AdminScriptTestCase(unittest.TestCase):
|
||||||
self.assertIsNotNone(re.search(msg, stream),
|
self.assertIsNotNone(re.search(msg, stream),
|
||||||
"'%s' does not match actual output text '%s'" % (msg, stream))
|
"'%s' does not match actual output text '%s'" % (msg, stream))
|
||||||
else:
|
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):
|
def assertNotInOutput(self, stream, msg):
|
||||||
"Utility assertion: assert that the given message doesn't exist in the output"
|
"Utility assertion: assert that the given message doesn't exist in the output"
|
||||||
stream = force_text(stream)
|
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
|
# DJANGO ADMIN TESTS
|
||||||
|
@ -904,7 +904,7 @@ class ManageAlternateSettings(AdminScriptTestCase):
|
||||||
out, err = self.run_manage(args)
|
out, err = self.run_manage(args)
|
||||||
expected = ('create table %s'
|
expected = ('create table %s'
|
||||||
% connection.ops.quote_name('admin_scripts_article'))
|
% connection.ops.quote_name('admin_scripts_article'))
|
||||||
self.assertTrue(expected.lower() in out.lower())
|
self.assertIn(expected.lower(), out.lower())
|
||||||
self.assertNoOutput(err)
|
self.assertNoOutput(err)
|
||||||
|
|
||||||
def test_builtin_with_environment(self):
|
def test_builtin_with_environment(self):
|
||||||
|
@ -913,7 +913,7 @@ class ManageAlternateSettings(AdminScriptTestCase):
|
||||||
out, err = self.run_manage(args, 'alternate_settings')
|
out, err = self.run_manage(args, 'alternate_settings')
|
||||||
expected = ('create table %s'
|
expected = ('create table %s'
|
||||||
% connection.ops.quote_name('admin_scripts_article'))
|
% connection.ops.quote_name('admin_scripts_article'))
|
||||||
self.assertTrue(expected.lower() in out.lower())
|
self.assertIn(expected.lower(), out.lower())
|
||||||
self.assertNoOutput(err)
|
self.assertNoOutput(err)
|
||||||
|
|
||||||
def test_builtin_with_bad_settings(self):
|
def test_builtin_with_bad_settings(self):
|
||||||
|
|
|
@ -90,7 +90,7 @@ class AdminViewBasicTestCase(TestCase):
|
||||||
content.
|
content.
|
||||||
"""
|
"""
|
||||||
self.assertEqual(response.status_code, 200)
|
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)
|
failing_msg)
|
||||||
|
|
||||||
|
|
||||||
|
@ -866,7 +866,7 @@ class AdminViewFormUrlTest(TestCase):
|
||||||
Tests whether change_view has form_url in response.context
|
Tests whether change_view has form_url in response.context
|
||||||
"""
|
"""
|
||||||
response = self.client.get('/test_admin/%s/admin_views/section/1/' % self.urlbit)
|
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')
|
self.assertEqual(response.context['form_url'], 'pony')
|
||||||
|
|
||||||
def test_initial_data_can_be_overridden(self):
|
def test_initial_data_can_be_overridden(self):
|
||||||
|
@ -4123,7 +4123,7 @@ class UserAdminTest(TestCase):
|
||||||
})
|
})
|
||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
adminform = response.context['adminform']
|
adminform = response.context['adminform']
|
||||||
self.assertTrue('password' not in adminform.form.errors)
|
self.assertNotIn('password', adminform.form.errors)
|
||||||
self.assertEqual(adminform.form.errors['password2'],
|
self.assertEqual(adminform.form.errors['password2'],
|
||||||
["The two password fields didn't match."])
|
["The two password fields didn't match."])
|
||||||
|
|
||||||
|
@ -5040,7 +5040,7 @@ class AdminViewOnSiteTests(TestCase):
|
||||||
|
|
||||||
# just verifying the parent form failed validation, as expected --
|
# just verifying the parent form failed validation, as expected --
|
||||||
# this isn't the regression test
|
# 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
|
# actual regression test
|
||||||
for error_set in response.context['inline_admin_formset'].formset.errors:
|
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 --
|
# just verifying the parent form failed validation, as expected --
|
||||||
# this isn't the regression test
|
# 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
|
# actual regression test
|
||||||
for error_set in response.context['inline_admin_formset'].formset.errors:
|
for error_set in response.context['inline_admin_formset'].formset.errors:
|
||||||
|
|
|
@ -1046,7 +1046,7 @@ class AdminRawIdWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase):
|
||||||
self.selenium.switch_to.window('id_main_band')
|
self.selenium.switch_to.window('id_main_band')
|
||||||
self.wait_page_loaded()
|
self.wait_page_loaded()
|
||||||
link = self.selenium.find_element_by_link_text('Bogey Blues')
|
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()
|
link.click()
|
||||||
|
|
||||||
# The field now contains the selected band's id
|
# 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.selenium.switch_to.window('id_main_band')
|
||||||
self.wait_page_loaded()
|
self.wait_page_loaded()
|
||||||
link = self.selenium.find_element_by_link_text('Green Potatoes')
|
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()
|
link.click()
|
||||||
|
|
||||||
# The field now contains the other selected band's id
|
# 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.selenium.switch_to.window('id_supporting_bands')
|
||||||
self.wait_page_loaded()
|
self.wait_page_loaded()
|
||||||
link = self.selenium.find_element_by_link_text('Bogey Blues')
|
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()
|
link.click()
|
||||||
|
|
||||||
# The field now contains the selected band's id
|
# 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.selenium.switch_to.window('id_supporting_bands')
|
||||||
self.wait_page_loaded()
|
self.wait_page_loaded()
|
||||||
link = self.selenium.find_element_by_link_text('Green Potatoes')
|
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()
|
link.click()
|
||||||
|
|
||||||
# The field now contains the two selected bands' ids
|
# The field now contains the two selected bands' ids
|
||||||
|
|
|
@ -133,7 +133,7 @@ class AggregationTests(TestCase):
|
||||||
rating=3.0
|
rating=3.0
|
||||||
)
|
)
|
||||||
# Different DB backends return different types for the extra select computation
|
# 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
|
# 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)
|
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
|
rating=3.0
|
||||||
)
|
)
|
||||||
# Different DB backends return different types for the extra select computation
|
# 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
|
# 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)
|
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']
|
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']
|
del obj['manufacture_cost']
|
||||||
self.assertEqual(obj, {
|
self.assertEqual(obj, {
|
||||||
"contact_id": 3,
|
"contact_id": 3,
|
||||||
|
@ -174,7 +174,7 @@ class AggregationTests(TestCase):
|
||||||
# matter
|
# matter
|
||||||
obj = Book.objects.values().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost': 'price * .5'}).get(pk=2)
|
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']
|
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']
|
del obj['manufacture_cost']
|
||||||
self.assertEqual(obj, {
|
self.assertEqual(obj, {
|
||||||
'contact_id': 3,
|
'contact_id': 3,
|
||||||
|
@ -1156,15 +1156,15 @@ class JoinPromotionTests(TestCase):
|
||||||
def test_existing_join_not_promoted(self):
|
def test_existing_join_not_promoted(self):
|
||||||
# No promotion for existing joins
|
# No promotion for existing joins
|
||||||
qs = Charlie.objects.filter(alfa__name__isnull=False).annotate(Count('alfa__name'))
|
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
|
# Also, the existing join is unpromoted when doing filtering for already
|
||||||
# promoted join.
|
# promoted join.
|
||||||
qs = Charlie.objects.annotate(Count('alfa__name')).filter(alfa__name__isnull=False)
|
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
|
# But, as the join is nullable first use by annotate will be LOUTER
|
||||||
qs = Charlie.objects.annotate(Count('alfa__name'))
|
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):
|
def test_non_nullable_fk_not_promoted(self):
|
||||||
qs = Book.objects.annotate(Count('contact__name'))
|
qs = Book.objects.annotate(Count('contact__name'))
|
||||||
self.assertTrue(' INNER JOIN ' in str(qs.query))
|
self.assertIn(' INNER JOIN ', str(qs.query))
|
||||||
|
|
|
@ -392,7 +392,7 @@ class SequenceResetTest(TestCase):
|
||||||
# If we create a new object now, it should have a PK greater
|
# If we create a new object now, it should have a PK greater
|
||||||
# than the PK we specified manually.
|
# than the PK we specified manually.
|
||||||
obj = models.Post.objects.create(name='New post', text='goodbye world')
|
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
|
# This test needs to run outside of a transaction, otherwise closing the
|
||||||
|
@ -413,12 +413,12 @@ class ConnectionCreatedSignalTest(TransactionTestCase):
|
||||||
connection_created.connect(receiver)
|
connection_created.connect(receiver)
|
||||||
connection.close()
|
connection.close()
|
||||||
connection.cursor()
|
connection.cursor()
|
||||||
self.assertTrue(data["connection"].connection is connection.connection)
|
self.assertIs(data["connection"].connection, connection.connection)
|
||||||
|
|
||||||
connection_created.disconnect(receiver)
|
connection_created.disconnect(receiver)
|
||||||
data.clear()
|
data.clear()
|
||||||
connection.cursor()
|
connection.cursor()
|
||||||
self.assertTrue(data == {})
|
self.assertEqual(data, {})
|
||||||
|
|
||||||
|
|
||||||
class EscapingChecks(TestCase):
|
class EscapingChecks(TestCase):
|
||||||
|
|
|
@ -134,7 +134,7 @@ class ModelInstanceCreationTests(TestCase):
|
||||||
a.save()
|
a.save()
|
||||||
|
|
||||||
# You can use 'in' to test for membership...
|
# 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:
|
# ... but there will often be more efficient ways if that is all you need:
|
||||||
self.assertTrue(Article.objects.filter(id=a.id).exists())
|
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)
|
some_pub_date = datetime(2014, 5, 16, 12, 1)
|
||||||
a1 = Article.objects.create(headline='First', pub_date=some_pub_date)
|
a1 = Article.objects.create(headline='First', pub_date=some_pub_date)
|
||||||
a2 = Article.objects.create(headline='Second', pub_date=some_pub_date)
|
a2 = Article.objects.create(headline='Second', pub_date=some_pub_date)
|
||||||
self.assertTrue(a1 != a2)
|
self.assertNotEqual(a1, a2)
|
||||||
self.assertFalse(a1 == a2)
|
self.assertEqual(a1, Article.objects.get(id__exact=a1.id))
|
||||||
self.assertTrue(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.assertNotEqual(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))
|
|
||||||
|
|
||||||
def test_multiple_objects_max_num_fetched(self):
|
def test_multiple_objects_max_num_fetched(self):
|
||||||
"""
|
"""
|
||||||
|
@ -286,7 +284,7 @@ class ModelTest(TestCase):
|
||||||
)
|
)
|
||||||
|
|
||||||
s = {a10, a11, a12}
|
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):
|
def test_field_ordering(self):
|
||||||
"""
|
"""
|
||||||
|
@ -299,10 +297,10 @@ class ModelTest(TestCase):
|
||||||
f1 = Field()
|
f1 = Field()
|
||||||
f2 = Field(auto_created=True)
|
f2 = Field(auto_created=True)
|
||||||
f3 = Field()
|
f3 = Field()
|
||||||
self.assertTrue(f2 < f1)
|
self.assertLess(f2, f1)
|
||||||
self.assertTrue(f3 > f1)
|
self.assertGreater(f3, f1)
|
||||||
self.assertFalse(f1 is None)
|
self.assertIsNotNone(f1)
|
||||||
self.assertFalse(f2 in (None, 1, ''))
|
self.assertNotIn(f2, (None, 1, ''))
|
||||||
|
|
||||||
def test_extra_method_select_argument_with_dashes_and_values(self):
|
def test_extra_method_select_argument_with_dashes_and_values(self):
|
||||||
# The 'select' argument to extra() supports names with dashes in
|
# The 'select' argument to extra() supports names with dashes in
|
||||||
|
|
|
@ -116,7 +116,7 @@ class BulkCreateTests(TestCase):
|
||||||
TwoFields.objects.bulk_create([
|
TwoFields.objects.bulk_create([
|
||||||
TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)
|
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):
|
def test_large_batch_mixed(self):
|
||||||
"""
|
"""
|
||||||
|
@ -146,7 +146,7 @@ class BulkCreateTests(TestCase):
|
||||||
TwoFields.objects.bulk_create([
|
TwoFields.objects.bulk_create([
|
||||||
TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1)
|
TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1)
|
||||||
for i in range(100000, 101000)])
|
for i in range(100000, 101000)])
|
||||||
self.assertTrue(len(connection.queries) < 10)
|
self.assertLess(len(connection.queries), 10)
|
||||||
|
|
||||||
def test_explicit_batch_size(self):
|
def test_explicit_batch_size(self):
|
||||||
objs = [TwoFields(f1=i, f2=i) for i in range(0, 4)]
|
objs = [TwoFields(f1=i, f2=i) for i in range(0, 4)]
|
||||||
|
|
|
@ -2084,7 +2084,7 @@ class CacheHandlerTest(TestCase):
|
||||||
cache1 = caches['default']
|
cache1 = caches['default']
|
||||||
cache2 = caches['default']
|
cache2 = caches['default']
|
||||||
|
|
||||||
self.assertTrue(cache1 is cache2)
|
self.assertIs(cache1, cache2)
|
||||||
|
|
||||||
def test_per_thread(self):
|
def test_per_thread(self):
|
||||||
"""
|
"""
|
||||||
|
@ -2101,4 +2101,4 @@ class CacheHandlerTest(TestCase):
|
||||||
t.start()
|
t.start()
|
||||||
t.join()
|
t.join()
|
||||||
|
|
||||||
self.assertFalse(c[0] is c[1])
|
self.assertIsNot(c[0], c[1])
|
||||||
|
|
|
@ -119,7 +119,7 @@ class CsrfViewMiddlewareTest(TestCase):
|
||||||
self.assertEqual(csrf_cookie['secure'], True)
|
self.assertEqual(csrf_cookie['secure'], True)
|
||||||
self.assertEqual(csrf_cookie['httponly'], True)
|
self.assertEqual(csrf_cookie['httponly'], True)
|
||||||
self.assertEqual(csrf_cookie['path'], '/test/')
|
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):
|
def test_process_response_get_token_not_used(self):
|
||||||
"""
|
"""
|
||||||
|
@ -340,7 +340,7 @@ class CsrfViewMiddlewareTest(TestCase):
|
||||||
req = self._get_GET_no_csrf_cookie_request()
|
req = self._get_GET_no_csrf_cookie_request()
|
||||||
resp = view(req)
|
resp = view(req)
|
||||||
self.assertTrue(resp.cookies.get(settings.CSRF_COOKIE_NAME, False))
|
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):
|
def test_ensures_csrf_cookie_with_middleware(self):
|
||||||
"""
|
"""
|
||||||
|
@ -357,7 +357,7 @@ class CsrfViewMiddlewareTest(TestCase):
|
||||||
resp = view(req)
|
resp = view(req)
|
||||||
resp2 = CsrfViewMiddleware().process_response(req, resp)
|
resp2 = CsrfViewMiddleware().process_response(req, resp)
|
||||||
self.assertTrue(resp2.cookies.get(settings.CSRF_COOKIE_NAME, False))
|
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):
|
def test_ensures_csrf_cookie_no_logging(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -14,7 +14,7 @@ class DataTypesTestCase(TestCase):
|
||||||
def test_boolean_type(self):
|
def test_boolean_type(self):
|
||||||
d = Donut(name='Apple Fritter')
|
d = Donut(name='Apple Fritter')
|
||||||
self.assertFalse(d.is_frosted)
|
self.assertFalse(d.is_frosted)
|
||||||
self.assertTrue(d.has_sprinkles is None)
|
self.assertIsNone(d.has_sprinkles)
|
||||||
d.has_sprinkles = True
|
d.has_sprinkles = True
|
||||||
self.assertTrue(d.has_sprinkles)
|
self.assertTrue(d.has_sprinkles)
|
||||||
|
|
||||||
|
|
|
@ -6,10 +6,10 @@ from .models import Empty
|
||||||
class EmptyModelTests(TestCase):
|
class EmptyModelTests(TestCase):
|
||||||
def test_empty(self):
|
def test_empty(self):
|
||||||
m = Empty()
|
m = Empty()
|
||||||
self.assertEqual(m.id, None)
|
self.assertIsNone(m.id)
|
||||||
m.save()
|
m.save()
|
||||||
Empty.objects.create()
|
Empty.objects.create()
|
||||||
self.assertEqual(len(Empty.objects.all()), 2)
|
self.assertEqual(len(Empty.objects.all()), 2)
|
||||||
self.assertTrue(m.id is not None)
|
self.assertIsNotNone(m.id)
|
||||||
existing = Empty(m.id)
|
existing = Empty(m.id)
|
||||||
existing.save()
|
existing.save()
|
||||||
|
|
|
@ -210,7 +210,7 @@ class ExpressionsTests(TestCase):
|
||||||
# keys, or attributes which involve joins.
|
# keys, or attributes which involve joins.
|
||||||
test_gmbh.point_of_contact = None
|
test_gmbh.point_of_contact = None
|
||||||
test_gmbh.save()
|
test_gmbh.save()
|
||||||
self.assertTrue(test_gmbh.point_of_contact is None)
|
self.assertIsNone(test_gmbh.point_of_contact)
|
||||||
|
|
||||||
def test():
|
def test():
|
||||||
test_gmbh.point_of_contact = F("ceo")
|
test_gmbh.point_of_contact = F("ceo")
|
||||||
|
|
|
@ -14,4 +14,4 @@ class DefaultTests(TestCase):
|
||||||
|
|
||||||
self.assertIsInstance(a.id, six.integer_types)
|
self.assertIsInstance(a.id, six.integer_types)
|
||||||
self.assertEqual(a.headline, "Default headline")
|
self.assertEqual(a.headline, "Default headline")
|
||||||
self.assertTrue((now - a.pub_date).seconds < 5)
|
self.assertLess((now - a.pub_date).seconds, 5)
|
||||||
|
|
|
@ -138,7 +138,7 @@ class FileStorageTests(unittest.TestCase):
|
||||||
|
|
||||||
self.assertEqual(atime, datetime.fromtimestamp(
|
self.assertEqual(atime, datetime.fromtimestamp(
|
||||||
os.path.getatime(self.storage.path(f_name))))
|
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)
|
self.storage.delete(f_name)
|
||||||
|
|
||||||
def test_file_created_time(self):
|
def test_file_created_time(self):
|
||||||
|
@ -154,7 +154,7 @@ class FileStorageTests(unittest.TestCase):
|
||||||
|
|
||||||
self.assertEqual(ctime, datetime.fromtimestamp(
|
self.assertEqual(ctime, datetime.fromtimestamp(
|
||||||
os.path.getctime(self.storage.path(f_name))))
|
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)
|
self.storage.delete(f_name)
|
||||||
|
|
||||||
|
@ -171,7 +171,7 @@ class FileStorageTests(unittest.TestCase):
|
||||||
|
|
||||||
self.assertEqual(mtime, datetime.fromtimestamp(
|
self.assertEqual(mtime, datetime.fromtimestamp(
|
||||||
os.path.getmtime(self.storage.path(f_name))))
|
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)
|
self.storage.delete(f_name)
|
||||||
|
|
||||||
|
@ -459,7 +459,7 @@ class FileFieldStorageTests(unittest.TestCase):
|
||||||
obj1.normal = SimpleUploadedFile("assignment.txt", b"content")
|
obj1.normal = SimpleUploadedFile("assignment.txt", b"content")
|
||||||
dirs, files = temp_storage.listdir("tests")
|
dirs, files = temp_storage.listdir("tests")
|
||||||
self.assertEqual(dirs, [])
|
self.assertEqual(dirs, [])
|
||||||
self.assertFalse("assignment.txt" in files)
|
self.assertNotIn("assignment.txt", files)
|
||||||
|
|
||||||
obj1.save()
|
obj1.save()
|
||||||
dirs, files = temp_storage.listdir("tests")
|
dirs, files = temp_storage.listdir("tests")
|
||||||
|
|
|
@ -257,7 +257,7 @@ class FileUploadTests(TestCase):
|
||||||
for name, _, expected in cases:
|
for name, _, expected in cases:
|
||||||
got = result[name]
|
got = result[name]
|
||||||
self.assertEqual(expected, got, 'Mismatch for {0}'.format(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))
|
"Got a long file name (%s characters)." % len(got))
|
||||||
|
|
||||||
def test_content_type_extra(self):
|
def test_content_type_extra(self):
|
||||||
|
@ -336,12 +336,12 @@ class FileUploadTests(TestCase):
|
||||||
# Small file posting should work.
|
# Small file posting should work.
|
||||||
response = self.client.post('/quota/', {'f': smallfile})
|
response = self.client.post('/quota/', {'f': smallfile})
|
||||||
got = json.loads(response.content.decode('utf-8'))
|
got = json.loads(response.content.decode('utf-8'))
|
||||||
self.assertTrue('f' in got)
|
self.assertIn('f', got)
|
||||||
|
|
||||||
# Large files don't go through.
|
# Large files don't go through.
|
||||||
response = self.client.post("/quota/", {'f': bigfile})
|
response = self.client.post("/quota/", {'f': bigfile})
|
||||||
got = json.loads(response.content.decode('utf-8'))
|
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):
|
def test_broken_custom_upload_handler(self):
|
||||||
with tempfile.NamedTemporaryFile() as file:
|
with tempfile.NamedTemporaryFile() as file:
|
||||||
|
|
|
@ -123,7 +123,6 @@ class InitialSQLTests(TestCase):
|
||||||
out = StringIO()
|
out = StringIO()
|
||||||
management.call_command("sqlcustom", "fixtures_model_package", stdout=out)
|
management.call_command("sqlcustom", "fixtures_model_package", stdout=out)
|
||||||
output = out.getvalue()
|
output = out.getvalue()
|
||||||
self.assertTrue("INSERT INTO fixtures_model_package_book (name) "
|
self.assertIn("INSERT INTO fixtures_model_package_book (name) VALUES ('My Book')", output)
|
||||||
"VALUES ('My Book')" in output)
|
|
||||||
# value from deprecated search path models/sql (remove in Django 1.9)
|
# value from deprecated search path models/sql (remove in Django 1.9)
|
||||||
self.assertTrue("Deprecated Book" in output)
|
self.assertIn("Deprecated Book", output)
|
||||||
|
|
|
@ -319,7 +319,7 @@ class MultiColumnFKTests(TestCase):
|
||||||
with self.assertNumQueries(1):
|
with self.assertNumQueries(1):
|
||||||
fetched = Article.objects.select_related('active_translation').get(
|
fetched = Article.objects.select_related('active_translation').get(
|
||||||
active_translation__title='Otsikko')
|
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())
|
a2 = Article.objects.create(pub_date=datetime.date.today())
|
||||||
at2_fi = ArticleTranslation(article=a2, lang='fi', title='Atsikko', body='Diipadaapa',
|
at2_fi = ArticleTranslation(article=a2, lang='fi', title='Atsikko', body='Diipadaapa',
|
||||||
abstract='dipad')
|
abstract='dipad')
|
||||||
|
|
|
@ -318,7 +318,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
|
||||||
|
|
||||||
# label tag is correctly associated with month dropdown
|
# label tag is correctly associated with month dropdown
|
||||||
d = GetDate({'mydate_month': '1', 'mydate_day': '1', 'mydate_year': '2010'})
|
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):
|
def test_selectdate_empty_label(self):
|
||||||
w = SelectDateWidget(years=('2014',), empty_label='empty_label')
|
w = SelectDateWidget(years=('2014',), empty_label='empty_label')
|
||||||
|
@ -865,4 +865,4 @@ class FormsExtraL10NTestCase(TestCase):
|
||||||
def test_form_label_association(self):
|
def test_form_label_association(self):
|
||||||
# label tag is correctly associated with first rendered dropdown
|
# label tag is correctly associated with first rendered dropdown
|
||||||
a = GetDate({'mydate_month': '1', 'mydate_day': '1', 'mydate_year': '2010'})
|
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())
|
||||||
|
|
|
@ -955,7 +955,7 @@ class FormsTestCase(TestCase):
|
||||||
f2 = MyForm()
|
f2 = MyForm()
|
||||||
|
|
||||||
f1.fields['myfield'].validators[0] = MaxValueValidator(12)
|
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):
|
def test_hidden_widget(self):
|
||||||
# HiddenInput widgets are displayed differently in the as_table(), as_ul())
|
# HiddenInput widgets are displayed differently in the as_table(), as_ul())
|
||||||
|
@ -2003,9 +2003,8 @@ class FormsTestCase(TestCase):
|
||||||
field = ChoicesField()
|
field = ChoicesField()
|
||||||
field2 = copy.deepcopy(field)
|
field2 = copy.deepcopy(field)
|
||||||
self.assertIsInstance(field2, ChoicesField)
|
self.assertIsInstance(field2, ChoicesField)
|
||||||
self.assertFalse(id(field2.fields) == id(field.fields))
|
self.assertIsNot(field2.fields, field.fields)
|
||||||
self.assertFalse(id(field2.fields[0].choices) ==
|
self.assertIsNot(field2.fields[0].choices, field.fields[0].choices)
|
||||||
id(field.fields[0].choices))
|
|
||||||
|
|
||||||
def test_multivalue_optional_subfields(self):
|
def test_multivalue_optional_subfields(self):
|
||||||
class PhoneField(MultiValueField):
|
class PhoneField(MultiValueField):
|
||||||
|
|
|
@ -1194,12 +1194,12 @@ class ClearableFileInputTests(TestCase):
|
||||||
widget = ClearableFileInput()
|
widget = ClearableFileInput()
|
||||||
field = StrangeFieldFile()
|
field = StrangeFieldFile()
|
||||||
output = widget.render('my<div>file', field)
|
output = widget.render('my<div>file', field)
|
||||||
self.assertFalse(field.url in output)
|
self.assertNotIn(field.url, output)
|
||||||
self.assertTrue('href="something?chapter=1&sect=2&copy=3&lang=en"' in output)
|
self.assertIn('href="something?chapter=1&sect=2&copy=3&lang=en"', output)
|
||||||
self.assertFalse(six.text_type(field) in output)
|
self.assertNotIn(six.text_type(field), output)
|
||||||
self.assertTrue('something<div onclick="alert('oops')">.jpg' in output)
|
self.assertIn('something<div onclick="alert('oops')">.jpg', output)
|
||||||
self.assertTrue('my<div>file' in output)
|
self.assertIn('my<div>file', output)
|
||||||
self.assertFalse('my<div>file' in output)
|
self.assertNotIn('my<div>file', output)
|
||||||
|
|
||||||
def test_clear_input_renders_only_if_not_required(self):
|
def test_clear_input_renders_only_if_not_required(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -157,7 +157,7 @@ class FormsModelTestCase(TestCase):
|
||||||
# FileModel with unicode filename and data #########################
|
# FileModel with unicode filename and data #########################
|
||||||
f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False)
|
f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False)
|
||||||
self.assertTrue(f.is_valid())
|
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'])
|
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')
|
self.assertEqual(m.file.name, 'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt')
|
||||||
m.delete()
|
m.delete()
|
||||||
|
|
|
@ -72,12 +72,12 @@ class GenericRelationTests(TestCase):
|
||||||
# search with a non-matching note and a matching org name
|
# search with a non-matching note and a matching org name
|
||||||
qs = Contact.objects.filter(Q(notes__note__icontains=r'other note') |
|
qs = Contact.objects.filter(Q(notes__note__icontains=r'other note') |
|
||||||
Q(organizations__name__icontains=r'org name'))
|
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
|
# search again, with the same query parameters, in reverse order
|
||||||
qs = Contact.objects.filter(
|
qs = Contact.objects.filter(
|
||||||
Q(organizations__name__icontains=r'org name') |
|
Q(organizations__name__icontains=r'org name') |
|
||||||
Q(notes__note__icontains=r'other note'))
|
Q(notes__note__icontains=r'other note'))
|
||||||
self.assertTrue(org_contact in qs)
|
self.assertIn(org_contact, qs)
|
||||||
|
|
||||||
def test_join_reuse(self):
|
def test_join_reuse(self):
|
||||||
qs = Person.objects.filter(
|
qs = Person.objects.filter(
|
||||||
|
|
|
@ -447,7 +447,7 @@ class GetContextDataTest(unittest.TestCase):
|
||||||
context = test_view.get_context_data(kwarg_test='kwarg_value')
|
context = test_view.get_context_data(kwarg_test='kwarg_value')
|
||||||
|
|
||||||
# the test_name key is inserted by the test classes parent
|
# 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['kwarg_test'], 'kwarg_value')
|
||||||
self.assertEqual(context['custom_key'], 'custom_value')
|
self.assertEqual(context['custom_key'], 'custom_value')
|
||||||
|
|
||||||
|
|
|
@ -35,7 +35,7 @@ class ArchiveIndexViewTests(TestCase):
|
||||||
self.assertEqual(res.status_code, 200)
|
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['date_list']), list(Book.objects.dates('pubdate', 'year', 'DESC')))
|
||||||
self.assertEqual(list(res.context['thingies']), list(Book.objects.all()))
|
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')
|
self.assertTemplateUsed(res, 'generic_views/book_archive.html')
|
||||||
|
|
||||||
def test_empty_archive_view(self):
|
def test_empty_archive_view(self):
|
||||||
|
|
|
@ -114,14 +114,14 @@ class DetailViewTest(TestCase):
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
|
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
|
||||||
self.assertEqual(res.context['thingy'], 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')
|
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
|
||||||
|
|
||||||
def test_duplicated_context_object_name(self):
|
def test_duplicated_context_object_name(self):
|
||||||
res = self.client.get('/detail/author/1/dupe_context_object_name/')
|
res = self.client.get('/detail/author/1/dupe_context_object_name/')
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
|
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')
|
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
|
||||||
|
|
||||||
def test_invalid_url(self):
|
def test_invalid_url(self):
|
||||||
|
|
|
@ -108,8 +108,8 @@ class CreateViewTests(TestCase):
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertIsInstance(res.context['form'], forms.ModelForm)
|
self.assertIsInstance(res.context['form'], forms.ModelForm)
|
||||||
self.assertIsInstance(res.context['view'], View)
|
self.assertIsInstance(res.context['view'], View)
|
||||||
self.assertFalse('object' in res.context)
|
self.assertNotIn('object', res.context)
|
||||||
self.assertFalse('author' in res.context)
|
self.assertNotIn('author', res.context)
|
||||||
self.assertTemplateUsed(res, 'generic_views/author_form.html')
|
self.assertTemplateUsed(res, 'generic_views/author_form.html')
|
||||||
|
|
||||||
res = self.client.post('/edit/authors/create/',
|
res = self.client.post('/edit/authors/create/',
|
||||||
|
@ -153,8 +153,8 @@ class CreateViewTests(TestCase):
|
||||||
res = self.client.get('/edit/authors/create/special/')
|
res = self.client.get('/edit/authors/create/special/')
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertIsInstance(res.context['form'], views.AuthorForm)
|
self.assertIsInstance(res.context['form'], views.AuthorForm)
|
||||||
self.assertFalse('object' in res.context)
|
self.assertNotIn('object', res.context)
|
||||||
self.assertFalse('author' in res.context)
|
self.assertNotIn('author', res.context)
|
||||||
self.assertTemplateUsed(res, 'generic_views/form.html')
|
self.assertTemplateUsed(res, 'generic_views/form.html')
|
||||||
|
|
||||||
res = self.client.post('/edit/authors/create/special/',
|
res = self.client.post('/edit/authors/create/special/',
|
||||||
|
@ -302,7 +302,7 @@ class UpdateViewTests(TestCase):
|
||||||
self.assertIsInstance(res.context['form'], views.AuthorForm)
|
self.assertIsInstance(res.context['form'], views.AuthorForm)
|
||||||
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
|
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
|
||||||
self.assertEqual(res.context['thingy'], 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')
|
self.assertTemplateUsed(res, 'generic_views/form.html')
|
||||||
|
|
||||||
res = self.client.post('/edit/author/%d/update/special/' % a.pk,
|
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.status_code, 200)
|
||||||
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
|
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
|
||||||
self.assertEqual(res.context['thingy'], 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')
|
self.assertTemplateUsed(res, 'generic_views/confirm_delete.html')
|
||||||
|
|
||||||
res = self.client.post('/edit/author/%d/delete/special/' % a.pk)
|
res = self.client.post('/edit/author/%d/delete/special/' % a.pk)
|
||||||
|
|
|
@ -78,10 +78,10 @@ class QueryDictTests(unittest.TestCase):
|
||||||
|
|
||||||
if six.PY2:
|
if six.PY2:
|
||||||
self.assertTrue(q.has_key('foo'))
|
self.assertTrue(q.has_key('foo'))
|
||||||
self.assertTrue('foo' in q)
|
self.assertIn('foo', q)
|
||||||
if six.PY2:
|
if six.PY2:
|
||||||
self.assertFalse(q.has_key('bar'))
|
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.iteritems(q)), [('foo', 'bar')])
|
||||||
self.assertEqual(list(six.iterlists(q)), [('foo', ['bar'])])
|
self.assertEqual(list(six.iterlists(q)), [('foo', ['bar'])])
|
||||||
|
@ -118,7 +118,7 @@ class QueryDictTests(unittest.TestCase):
|
||||||
q = QueryDict(mutable=True)
|
q = QueryDict(mutable=True)
|
||||||
q['name'] = 'john'
|
q['name'] = 'john'
|
||||||
del q['name']
|
del q['name']
|
||||||
self.assertFalse('name' in q)
|
self.assertNotIn('name', q)
|
||||||
|
|
||||||
def test_basic_mutable_operations(self):
|
def test_basic_mutable_operations(self):
|
||||||
q = QueryDict(mutable=True)
|
q = QueryDict(mutable=True)
|
||||||
|
@ -137,7 +137,7 @@ class QueryDictTests(unittest.TestCase):
|
||||||
self.assertEqual(q['foo'], 'another')
|
self.assertEqual(q['foo'], 'another')
|
||||||
if six.PY2:
|
if six.PY2:
|
||||||
self.assertTrue(q.has_key('foo'))
|
self.assertTrue(q.has_key('foo'))
|
||||||
self.assertTrue('foo' in q)
|
self.assertIn('foo', q)
|
||||||
|
|
||||||
self.assertListEqual(sorted(list(six.iteritems(q))),
|
self.assertListEqual(sorted(list(six.iteritems(q))),
|
||||||
[('foo', 'another'), ('name', 'john')])
|
[('foo', 'another'), ('name', 'john')])
|
||||||
|
@ -609,8 +609,8 @@ class CookieTests(unittest.TestCase):
|
||||||
"""
|
"""
|
||||||
c = SimpleCookie()
|
c = SimpleCookie()
|
||||||
c['test'] = "An,awkward;value"
|
c['test'] = "An,awkward;value"
|
||||||
self.assertTrue(";" not in c.output().rstrip(';')) # IE compat
|
self.assertNotIn(";", c.output().rstrip(';')) # IE compat
|
||||||
self.assertTrue("," not in c.output().rstrip(';')) # Safari compat
|
self.assertNotIn(",", c.output().rstrip(';')) # Safari compat
|
||||||
|
|
||||||
def test_decode(self):
|
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.
|
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):
|
def test_repeated_nonstandard_keys(self):
|
||||||
"""
|
"""
|
||||||
Test that a repeated non-standard name doesn't affect all cookies. Ticket #15852
|
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):
|
def test_httponly_after_load(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -96,9 +96,9 @@ class ExtractorTests(SimpleTestCase):
|
||||||
parts.append(':%d' % line_number)
|
parts.append(':%d' % line_number)
|
||||||
needle = ''.join(parts)
|
needle = ''.join(parts)
|
||||||
if assert_presence:
|
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:
|
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):
|
def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts):
|
||||||
"""
|
"""
|
||||||
|
@ -141,26 +141,26 @@ class BasicExtractorTests(ExtractorTests):
|
||||||
self.assertTrue(os.path.exists(self.PO_FILE))
|
self.assertTrue(os.path.exists(self.PO_FILE))
|
||||||
with io.open(self.PO_FILE, 'r', encoding='utf-8') as fp:
|
with io.open(self.PO_FILE, 'r', encoding='utf-8') as fp:
|
||||||
po_contents = fp.read()
|
po_contents = fp.read()
|
||||||
self.assertTrue('#. Translators: This comment should be extracted' in po_contents)
|
self.assertIn('#. Translators: This comment should be extracted', po_contents)
|
||||||
self.assertTrue('This comment should not be extracted' not in po_contents)
|
self.assertNotIn('This comment should not be extracted', po_contents)
|
||||||
# Comments in templates
|
# Comments in templates
|
||||||
self.assertTrue('#. Translators: Django template comment for translators' in po_contents)
|
self.assertIn('#. Translators: Django template comment for translators', po_contents)
|
||||||
self.assertTrue("#. Translators: Django comment block for translators\n#. string's meaning unveiled" in 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.assertIn('#. Translators: One-line translator comment #1', po_contents)
|
||||||
self.assertTrue('#. Translators: Two-line translator comment #1\n#. continued here.' in 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.assertIn('#. Translators: One-line translator comment #2', po_contents)
|
||||||
self.assertTrue('#. Translators: Two-line translator comment #2\n#. continued here.' in 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.assertIn('#. Translators: One-line translator comment #3', po_contents)
|
||||||
self.assertTrue('#. Translators: Two-line translator comment #3\n#. continued here.' in 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.assertIn('#. Translators: One-line translator comment #4', po_contents)
|
||||||
self.assertTrue('#. Translators: Two-line translator comment #4\n#. continued here.' in 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.assertIn('#. Translators: One-line translator comment #5 -- with non ASCII characters: áéíóúö', po_contents)
|
||||||
self.assertTrue('#. Translators: Two-line translator comment #5 -- with non ASCII characters: áéíóúö\n#. continued here.' in 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):
|
def test_templatize_trans_tag(self):
|
||||||
# ticket #11240
|
# ticket #11240
|
||||||
|
@ -250,23 +250,23 @@ class BasicExtractorTests(ExtractorTests):
|
||||||
with open(self.PO_FILE, 'r') as fp:
|
with open(self.PO_FILE, 'r') as fp:
|
||||||
po_contents = force_text(fp.read())
|
po_contents = force_text(fp.read())
|
||||||
# {% trans %}
|
# {% 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.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.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)
|
self.assertMsgId("Translatable literal #7c", po_contents)
|
||||||
|
|
||||||
# {% blocktrans %}
|
# {% 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.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.assertMsgId("Translatable literal #8b-singular", po_contents)
|
||||||
self.assertTrue("Translatable literal #8b-plural" in po_contents)
|
self.assertIn("Translatable literal #8b-plural", po_contents)
|
||||||
self.assertTrue('msgctxt "Special blocktrans context #3"' in po_contents)
|
self.assertIn('msgctxt "Special blocktrans context #3"', po_contents)
|
||||||
self.assertMsgId("Translatable literal #8c-singular", po_contents)
|
self.assertMsgId("Translatable literal #8c-singular", po_contents)
|
||||||
self.assertTrue("Translatable literal #8c-plural" in po_contents)
|
self.assertIn("Translatable literal #8c-plural", po_contents)
|
||||||
self.assertTrue('msgctxt "Special blocktrans context #4"' in po_contents)
|
self.assertIn('msgctxt "Special blocktrans context #4"', po_contents)
|
||||||
self.assertMsgId("Translatable literal #8d %(a)s", po_contents)
|
self.assertMsgId("Translatable literal #8d %(a)s", po_contents)
|
||||||
|
|
||||||
def test_context_in_single_quotes(self):
|
def test_context_in_single_quotes(self):
|
||||||
|
@ -276,12 +276,12 @@ class BasicExtractorTests(ExtractorTests):
|
||||||
with open(self.PO_FILE, 'r') as fp:
|
with open(self.PO_FILE, 'r') as fp:
|
||||||
po_contents = force_text(fp.read())
|
po_contents = force_text(fp.read())
|
||||||
# {% trans %}
|
# {% trans %}
|
||||||
self.assertTrue('msgctxt "Context wrapped in double quotes"' in po_contents)
|
self.assertIn('msgctxt "Context wrapped in double quotes"', po_contents)
|
||||||
self.assertTrue('msgctxt "Context wrapped in single quotes"' in po_contents)
|
self.assertIn('msgctxt "Context wrapped in single quotes"', po_contents)
|
||||||
|
|
||||||
# {% blocktrans %}
|
# {% blocktrans %}
|
||||||
self.assertTrue('msgctxt "Special blocktrans context wrapped in double quotes"' in po_contents)
|
self.assertIn('msgctxt "Special blocktrans context wrapped in double quotes"', po_contents)
|
||||||
self.assertTrue('msgctxt "Special blocktrans context wrapped in single quotes"' in po_contents)
|
self.assertIn('msgctxt "Special blocktrans context wrapped in single quotes"', po_contents)
|
||||||
|
|
||||||
def test_template_comments(self):
|
def test_template_comments(self):
|
||||||
"""Template comment tags on the same line of other constructs (#19552)"""
|
"""Template comment tags on the same line of other constructs (#19552)"""
|
||||||
|
@ -312,31 +312,31 @@ class BasicExtractorTests(ExtractorTests):
|
||||||
po_contents = force_text(fp.read())
|
po_contents = force_text(fp.read())
|
||||||
|
|
||||||
self.assertMsgId('Translatable literal #9a', po_contents)
|
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.assertMsgId("Translatable literal #9b", po_contents)
|
||||||
|
|
||||||
self.assertFalse('ignored i18n comment #2' in po_contents)
|
self.assertNotIn('ignored i18n comment #2', po_contents)
|
||||||
self.assertFalse('ignored comment #2' in po_contents)
|
self.assertNotIn('ignored comment #2', po_contents)
|
||||||
self.assertMsgId('Translatable literal #9c', po_contents)
|
self.assertMsgId('Translatable literal #9c', po_contents)
|
||||||
|
|
||||||
self.assertFalse('ignored comment #3' in po_contents)
|
self.assertNotIn('ignored comment #3', po_contents)
|
||||||
self.assertFalse('ignored i18n comment #3' in po_contents)
|
self.assertNotIn('ignored i18n comment #3', po_contents)
|
||||||
self.assertMsgId('Translatable literal #9d', 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.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.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.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.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)
|
self.assertMsgId('Translatable literal #9i', po_contents)
|
||||||
|
|
||||||
six.assertRegex(self, po_contents, r'#\..+Translators: valid i18n comment #8')
|
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=[
|
out, po_contents = self._run_makemessages(ignore_patterns=[
|
||||||
os.path.join('ignore_dir', '*'),
|
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.assertMsgId('This literal should be included.', po_contents)
|
||||||
self.assertNotMsgId('This should be ignored.', po_contents)
|
self.assertNotMsgId('This should be ignored.', po_contents)
|
||||||
|
|
||||||
|
@ -400,14 +400,14 @@ class IgnoredExtractorTests(ExtractorTests):
|
||||||
'templates/*/ignore.html',
|
'templates/*/ignore.html',
|
||||||
'templates/subdir/*',
|
'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)
|
self.assertNotMsgId('This subdir should be ignored too.', po_contents)
|
||||||
|
|
||||||
def test_ignore_file_patterns(self):
|
def test_ignore_file_patterns(self):
|
||||||
out, po_contents = self._run_makemessages(ignore_patterns=[
|
out, po_contents = self._run_makemessages(ignore_patterns=[
|
||||||
'xxx_*',
|
'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)
|
self.assertNotMsgId('This should be ignored too.', po_contents)
|
||||||
|
|
||||||
@override_settings(
|
@override_settings(
|
||||||
|
@ -455,7 +455,7 @@ class SymlinkExtractorTests(ExtractorTests):
|
||||||
with open(self.PO_FILE, 'r') as fp:
|
with open(self.PO_FILE, 'r') as fp:
|
||||||
po_contents = force_text(fp.read())
|
po_contents = force_text(fp.read())
|
||||||
self.assertMsgId('This literal should be included.', po_contents)
|
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):
|
class CopyPluralFormsExtractorTests(ExtractorTests):
|
||||||
|
@ -477,7 +477,7 @@ class CopyPluralFormsExtractorTests(ExtractorTests):
|
||||||
self.assertTrue(os.path.exists(self.PO_FILE))
|
self.assertTrue(os.path.exists(self.PO_FILE))
|
||||||
with open(self.PO_FILE, 'r') as fp:
|
with open(self.PO_FILE, 'r') as fp:
|
||||||
po_contents = force_text(fp.read())
|
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):
|
def test_override_plural_forms(self):
|
||||||
"""Ticket #20311."""
|
"""Ticket #20311."""
|
||||||
|
|
|
@ -1153,7 +1153,7 @@ class ResolutionOrderI18NTests(TestCase):
|
||||||
|
|
||||||
def assertUgettext(self, msgid, msgstr):
|
def assertUgettext(self, msgid, msgstr):
|
||||||
result = ugettext(msgid)
|
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)))
|
"translation of '%s'; the actual result is '%s'." % (msgstr, msgid, result)))
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -11,9 +11,9 @@ class IntrospectionTests(TestCase):
|
||||||
def test_table_names(self):
|
def test_table_names(self):
|
||||||
tl = connection.introspection.table_names()
|
tl = connection.introspection.table_names()
|
||||||
self.assertEqual(tl, sorted(tl))
|
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)
|
"'%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)
|
"'%s' isn't in table_list()." % Article._meta.db_table)
|
||||||
|
|
||||||
def test_django_table_names(self):
|
def test_django_table_names(self):
|
||||||
|
@ -60,7 +60,7 @@ class IntrospectionTests(TestCase):
|
||||||
def test_sequence_list(self):
|
def test_sequence_list(self):
|
||||||
sequences = connection.introspection.sequence_list()
|
sequences = connection.introspection.sequence_list()
|
||||||
expected = {'table': Reporter._meta.db_table, 'column': 'id'}
|
expected = {'table': Reporter._meta.db_table, 'column': 'id'}
|
||||||
self.assertTrue(expected in sequences,
|
self.assertIn(expected, sequences,
|
||||||
'Reporter sequence not found in sequence_list()')
|
'Reporter sequence not found in sequence_list()')
|
||||||
|
|
||||||
def test_get_table_description_names(self):
|
def test_get_table_description_names(self):
|
||||||
|
|
|
@ -123,12 +123,12 @@ class WarningLoggerTests(TestCase):
|
||||||
def test_warnings_capture(self):
|
def test_warnings_capture(self):
|
||||||
warnings.warn('Foo Deprecated', RemovedInNextVersionWarning)
|
warnings.warn('Foo Deprecated', RemovedInNextVersionWarning)
|
||||||
output = force_text(self.outputs[0].getvalue())
|
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):
|
def test_warnings_capture_debug_false(self):
|
||||||
warnings.warn('Foo Deprecated', RemovedInNextVersionWarning)
|
warnings.warn('Foo Deprecated', RemovedInNextVersionWarning)
|
||||||
output = force_text(self.outputs[0].getvalue())
|
output = force_text(self.outputs[0].getvalue())
|
||||||
self.assertFalse('Foo Deprecated' in output)
|
self.assertNotIn('Foo Deprecated', output)
|
||||||
|
|
||||||
@override_settings(DEBUG=True)
|
@override_settings(DEBUG=True)
|
||||||
def test_error_filter_still_raises(self):
|
def test_error_filter_still_raises(self):
|
||||||
|
@ -263,8 +263,8 @@ class AdminEmailHandlerTest(TestCase):
|
||||||
self.logger.error(message)
|
self.logger.error(message)
|
||||||
|
|
||||||
self.assertEqual(len(mail.outbox), 1)
|
self.assertEqual(len(mail.outbox), 1)
|
||||||
self.assertFalse('\n' in mail.outbox[0].subject)
|
self.assertNotIn('\n', mail.outbox[0].subject)
|
||||||
self.assertFalse('\r' in mail.outbox[0].subject)
|
self.assertNotIn('\r', mail.outbox[0].subject)
|
||||||
self.assertEqual(mail.outbox[0].subject, expected_subject)
|
self.assertEqual(mail.outbox[0].subject, expected_subject)
|
||||||
|
|
||||||
@override_settings(
|
@override_settings(
|
||||||
|
|
|
@ -85,12 +85,12 @@ class M2MRegressionTests(TestCase):
|
||||||
t2 = Tag.objects.create()
|
t2 = Tag.objects.create()
|
||||||
|
|
||||||
# Get same manager twice in a row:
|
# Get same manager twice in a row:
|
||||||
self.assertTrue(t1.entry_set.__class__ is t1.entry_set.__class__)
|
self.assertIs(t1.entry_set.__class__, t1.entry_set.__class__)
|
||||||
self.assertTrue(e1.topics.__class__ is e1.topics.__class__)
|
self.assertIs(e1.topics.__class__, e1.topics.__class__)
|
||||||
|
|
||||||
# Get same manager for different instances
|
# Get same manager for different instances
|
||||||
self.assertTrue(e1.topics.__class__ is e2.topics.__class__)
|
self.assertIs(e1.topics.__class__, e2.topics.__class__)
|
||||||
self.assertTrue(t1.entry_set.__class__ is t2.entry_set.__class__)
|
self.assertIs(t1.entry_set.__class__, t2.entry_set.__class__)
|
||||||
|
|
||||||
def test_m2m_abstract_split(self):
|
def test_m2m_abstract_split(self):
|
||||||
# Regression for #19236 - an abstract class with a 'split' method
|
# Regression for #19236 - an abstract class with a 'split' method
|
||||||
|
|
|
@ -346,31 +346,31 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
|
||||||
# Regression for #13433 - Make sure that EmailMessage doesn't mangle
|
# Regression for #13433 - Make sure that EmailMessage doesn't mangle
|
||||||
# 'From ' in message body.
|
# 'From ' in message body.
|
||||||
email = EmailMessage('Subject', 'From the future', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
|
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):
|
def test_dont_base64_encode(self):
|
||||||
# Ticket #3472
|
# Ticket #3472
|
||||||
# Shouldn't use Base64 encoding at all
|
# 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'})
|
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
|
# Ticket #11212
|
||||||
# Shouldn't use quoted printable, should detect it can represent content with 7 bit data
|
# 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'})
|
msg = EmailMessage('Subject', 'Body with only ASCII characters.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
|
||||||
s = msg.message().as_bytes()
|
s = msg.message().as_bytes()
|
||||||
self.assertFalse(b'Content-Transfer-Encoding: quoted-printable' in s)
|
self.assertNotIn(b'Content-Transfer-Encoding: quoted-printable', s)
|
||||||
self.assertTrue(b'Content-Transfer-Encoding: 7bit' in s)
|
self.assertIn(b'Content-Transfer-Encoding: 7bit', s)
|
||||||
|
|
||||||
# Shouldn't use quoted printable, should detect it can represent content with 8 bit data
|
# 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'})
|
msg = EmailMessage('Subject', 'Body with latin characters: àáä.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
|
||||||
s = msg.message().as_bytes()
|
s = msg.message().as_bytes()
|
||||||
self.assertFalse(b'Content-Transfer-Encoding: quoted-printable' in s)
|
self.assertNotIn(b'Content-Transfer-Encoding: quoted-printable', s)
|
||||||
self.assertTrue(b'Content-Transfer-Encoding: 8bit' in 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'})
|
msg = EmailMessage('Subject', 'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
|
||||||
s = msg.message().as_bytes()
|
s = msg.message().as_bytes()
|
||||||
self.assertFalse(b'Content-Transfer-Encoding: quoted-printable' in s)
|
self.assertNotIn(b'Content-Transfer-Encoding: quoted-printable', s)
|
||||||
self.assertTrue(b'Content-Transfer-Encoding: 8bit' in s)
|
self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
|
||||||
|
|
||||||
def test_dont_base64_encode_message_rfc822(self):
|
def test_dont_base64_encode_message_rfc822(self):
|
||||||
# Ticket #18967
|
# Ticket #18967
|
||||||
|
@ -387,7 +387,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
|
||||||
parent_s = parent_msg.message().as_string()
|
parent_s = parent_msg.message().as_string()
|
||||||
|
|
||||||
# Verify that the child message header is not base64 encoded
|
# 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.
|
# 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'})
|
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()
|
parent_s = parent_msg.message().as_string()
|
||||||
|
|
||||||
# Verify that the child message header is not base64 encoded
|
# 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.
|
# 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'})
|
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()
|
parent_s = parent_msg.message().as_string()
|
||||||
|
|
||||||
# Verify that the child message header is not base64 encoded
|
# 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):
|
class PythonGlobalState(SimpleTestCase):
|
||||||
|
@ -415,19 +415,19 @@ class PythonGlobalState(SimpleTestCase):
|
||||||
|
|
||||||
def test_utf8(self):
|
def test_utf8(self):
|
||||||
txt = MIMEText('UTF-8 encoded body', 'plain', 'utf-8')
|
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):
|
def test_7bit(self):
|
||||||
txt = MIMEText('Body with only ASCII characters.', 'plain', 'utf-8')
|
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):
|
def test_8bit_latin(self):
|
||||||
txt = MIMEText('Body with latin characters: àáä.', 'plain', 'utf-8')
|
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):
|
def test_8bit_non_latin(self):
|
||||||
txt = MIMEText('Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'plain', 'utf-8')
|
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):
|
class BaseEmailBackendTests(HeadersCheckMixin, object):
|
||||||
|
|
|
@ -417,10 +417,10 @@ class ManyToOneTests(TestCase):
|
||||||
r2 = Reporter.objects.create(first_name='John')
|
r2 = Reporter.objects.create(first_name='John')
|
||||||
|
|
||||||
# Same twice
|
# 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
|
# 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):
|
def test_create_relation_with_ugettext_lazy(self):
|
||||||
reporter = Reporter.objects.create(first_name='John',
|
reporter = Reporter.objects.create(first_name='John',
|
||||||
|
@ -456,28 +456,28 @@ class ManyToOneTests(TestCase):
|
||||||
p = c.parent
|
p = c.parent
|
||||||
|
|
||||||
# Accessing the related object again returns the exactly same object.
|
# 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.
|
# But if we kill the cache, we get a new object.
|
||||||
del c._parent_cache
|
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.
|
# Assigning a new object results in that object getting cached immediately.
|
||||||
p2 = Parent.objects.create(name="Parent 2")
|
p2 = Parent.objects.create(name="Parent 2")
|
||||||
c.parent = p2
|
c.parent = p2
|
||||||
self.assertTrue(c.parent is p2)
|
self.assertIs(c.parent, p2)
|
||||||
|
|
||||||
# Assigning None succeeds if field is null=True.
|
# Assigning None succeeds if field is null=True.
|
||||||
p.bestchild = None
|
p.bestchild = None
|
||||||
self.assertTrue(p.bestchild is None)
|
self.assertIsNone(p.bestchild)
|
||||||
|
|
||||||
# bestchild should still be None after saving.
|
# bestchild should still be None after saving.
|
||||||
p.save()
|
p.save()
|
||||||
self.assertTrue(p.bestchild is None)
|
self.assertIsNone(p.bestchild)
|
||||||
|
|
||||||
# bestchild should still be None after fetching the object again.
|
# bestchild should still be None after fetching the object again.
|
||||||
p = Parent.objects.get(name="Parent")
|
p = Parent.objects.get(name="Parent")
|
||||||
self.assertTrue(p.bestchild is None)
|
self.assertIsNone(p.bestchild)
|
||||||
|
|
||||||
# Assigning None fails: Child.parent is null=False.
|
# Assigning None fails: Child.parent is null=False.
|
||||||
self.assertRaises(ValueError, setattr, c, "parent", None)
|
self.assertRaises(ValueError, setattr, c, "parent", None)
|
||||||
|
@ -493,7 +493,7 @@ class ManyToOneTests(TestCase):
|
||||||
# Creation using keyword argument should cache the related object.
|
# Creation using keyword argument should cache the related object.
|
||||||
p = Parent.objects.get(name="Parent")
|
p = Parent.objects.get(name="Parent")
|
||||||
c = Child(parent=p)
|
c = Child(parent=p)
|
||||||
self.assertTrue(c.parent is p)
|
self.assertIs(c.parent, p)
|
||||||
|
|
||||||
# Creation using keyword argument and unsaved related instance (#8070).
|
# Creation using keyword argument and unsaved related instance (#8070).
|
||||||
p = Parent()
|
p = Parent()
|
||||||
|
@ -511,7 +511,7 @@ class ManyToOneTests(TestCase):
|
||||||
# related object to be fetched.
|
# related object to be fetched.
|
||||||
p = Parent.objects.get(name="Parent")
|
p = Parent.objects.get(name="Parent")
|
||||||
c = Child(parent_id=p.id)
|
c = Child(parent_id=p.id)
|
||||||
self.assertFalse(c.parent is p)
|
self.assertIsNot(c.parent, p)
|
||||||
self.assertEqual(c.parent, p)
|
self.assertEqual(c.parent, p)
|
||||||
|
|
||||||
def test_multiple_foreignkeys(self):
|
def test_multiple_foreignkeys(self):
|
||||||
|
|
|
@ -152,7 +152,7 @@ class SecurityMiddlewareTest(TestCase):
|
||||||
With BROWSER_XSS_FILTER set to False, the middleware does not add an
|
With BROWSER_XSS_FILTER set to False, the middleware does not add an
|
||||||
"x-xss-protection" header to the response.
|
"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)
|
@override_settings(SECURE_SSL_REDIRECT=True)
|
||||||
def test_ssl_redirect_on(self):
|
def test_ssl_redirect_on(self):
|
||||||
|
|
|
@ -162,7 +162,7 @@ class CommonMiddlewareTest(TestCase):
|
||||||
request = self._get_request('customurlconf/slash')
|
request = self._get_request('customurlconf/slash')
|
||||||
request.urlconf = 'middleware.extra_urls'
|
request.urlconf = 'middleware.extra_urls'
|
||||||
r = CommonMiddleware().process_request(request)
|
r = CommonMiddleware().process_request(request)
|
||||||
self.assertFalse(r is None,
|
self.assertIsNotNone(r,
|
||||||
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
|
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
|
||||||
self.assertEqual(r.status_code, 301)
|
self.assertEqual(r.status_code, 301)
|
||||||
self.assertEqual(r.url, 'http://testserver/customurlconf/slash/')
|
self.assertEqual(r.url, 'http://testserver/customurlconf/slash/')
|
||||||
|
@ -198,7 +198,7 @@ class CommonMiddlewareTest(TestCase):
|
||||||
request = self._get_request('customurlconf/needsquoting#')
|
request = self._get_request('customurlconf/needsquoting#')
|
||||||
request.urlconf = 'middleware.extra_urls'
|
request.urlconf = 'middleware.extra_urls'
|
||||||
r = CommonMiddleware().process_request(request)
|
r = CommonMiddleware().process_request(request)
|
||||||
self.assertFalse(r is None,
|
self.assertIsNotNone(r,
|
||||||
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
|
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
|
||||||
self.assertEqual(r.status_code, 301)
|
self.assertEqual(r.status_code, 301)
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
|
@ -318,24 +318,24 @@ class ConditionalGetMiddlewareTest(TestCase):
|
||||||
# Tests for the Date header
|
# Tests for the Date header
|
||||||
|
|
||||||
def test_date_header_added(self):
|
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.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
|
# Tests for the Content-Length header
|
||||||
|
|
||||||
def test_content_length_header_added(self):
|
def test_content_length_header_added(self):
|
||||||
content_length = len(self.resp.content)
|
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.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)
|
self.assertEqual(int(self.resp['Content-Length']), content_length)
|
||||||
|
|
||||||
def test_content_length_header_not_added(self):
|
def test_content_length_header_not_added(self):
|
||||||
resp = StreamingHttpResponse('content')
|
resp = StreamingHttpResponse('content')
|
||||||
self.assertFalse('Content-Length' in resp)
|
self.assertNotIn('Content-Length', resp)
|
||||||
resp = ConditionalGetMiddleware().process_response(self.req, 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):
|
def test_content_length_header_not_changed(self):
|
||||||
bad_content_length = len(self.resp.content) + 10
|
bad_content_length = len(self.resp.content) + 10
|
||||||
|
|
|
@ -590,8 +590,8 @@ class AutodetectorTests(TestCase):
|
||||||
# Right number/type of migrations?
|
# Right number/type of migrations?
|
||||||
self.assertNumberMigrations(changes, 'eggs', 1)
|
self.assertNumberMigrations(changes, 'eggs', 1)
|
||||||
self.assertOperationTypes(changes, 'eggs', 0, ["CreateModel", "CreateModel", "AlterUniqueTogether"])
|
self.assertOperationTypes(changes, 'eggs', 0, ["CreateModel", "CreateModel", "AlterUniqueTogether"])
|
||||||
self.assertFalse("unique_together" in changes['eggs'][0].operations[0].options)
|
self.assertNotIn("unique_together", 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[1].options)
|
||||||
# Right dependencies?
|
# Right dependencies?
|
||||||
self.assertEqual(changes['eggs'][0].dependencies, [])
|
self.assertEqual(changes['eggs'][0].dependencies, [])
|
||||||
|
|
||||||
|
|
|
@ -196,19 +196,19 @@ class MakeMigrationsTests(MigrationTestBase):
|
||||||
|
|
||||||
with codecs.open(initial_file, 'r', encoding='utf-8') as fp:
|
with codecs.open(initial_file, 'r', encoding='utf-8') as fp:
|
||||||
content = fp.read()
|
content = fp.read()
|
||||||
self.assertTrue('# -*- coding: utf-8 -*-' in content)
|
self.assertIn('# -*- coding: utf-8 -*-', content)
|
||||||
self.assertTrue('migrations.CreateModel' in content)
|
self.assertIn('migrations.CreateModel', content)
|
||||||
|
|
||||||
if six.PY3:
|
if six.PY3:
|
||||||
self.assertTrue('úñí©óðé µóðéø' in content) # Meta.verbose_name
|
self.assertIn('úñí©óðé µóðéø', content) # Meta.verbose_name
|
||||||
self.assertTrue('úñí©óðé µóðéøß' in content) # Meta.verbose_name_plural
|
self.assertIn('úñí©óðé µóðéøß', content) # Meta.verbose_name_plural
|
||||||
self.assertTrue('ÚÑÍ¢ÓÐÉ' in content) # title.verbose_name
|
self.assertIn('ÚÑÍ¢ÓÐÉ', content) # title.verbose_name
|
||||||
self.assertTrue('“Ðjáñgó”' in content) # title.default
|
self.assertIn('“Ðjáñgó”', content) # title.default
|
||||||
else:
|
else:
|
||||||
self.assertTrue('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8' in content) # Meta.verbose_name
|
self.assertIn('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8', 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.assertIn('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8\\xdf', content) # Meta.verbose_name_plural
|
||||||
self.assertTrue('\\xda\\xd1\\xcd\\xa2\\xd3\\xd0\\xc9' in content) # title.verbose_name
|
self.assertIn('\\xda\\xd1\\xcd\\xa2\\xd3\\xd0\\xc9', content) # title.verbose_name
|
||||||
self.assertTrue('\\u201c\\xd0j\\xe1\\xf1g\\xf3\\u201d' in content) # title.default
|
self.assertIn('\\u201c\\xd0j\\xe1\\xf1g\\xf3\\u201d', content) # title.default
|
||||||
|
|
||||||
def test_failing_migration(self):
|
def test_failing_migration(self):
|
||||||
#21280 - If a migration fails to serialize, it shouldn't generate an empty file.
|
#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:
|
with codecs.open(initial_file, 'r', encoding='utf-8') as fp:
|
||||||
content = fp.read()
|
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
|
# Remove all whitespace to check for empty dependencies and operations
|
||||||
content = content.replace(' ', '')
|
content = content.replace(' ', '')
|
||||||
|
@ -529,7 +529,7 @@ class MakeMigrationsTests(MigrationTestBase):
|
||||||
self.assertTrue(os.path.exists(migration_file))
|
self.assertTrue(os.path.exists(migration_file))
|
||||||
with codecs.open(migration_file, "r", encoding="utf-8") as fp:
|
with codecs.open(migration_file, "r", encoding="utf-8") as fp:
|
||||||
content = fp.read()
|
content = fp.read()
|
||||||
self.assertTrue("# -*- coding: utf-8 -*-" in content)
|
self.assertIn("# -*- coding: utf-8 -*-", content)
|
||||||
content = content.replace(" ", "")
|
content = content.replace(" ", "")
|
||||||
return content
|
return content
|
||||||
|
|
||||||
|
|
|
@ -223,8 +223,8 @@ class BooleanFieldTests(unittest.TestCase):
|
||||||
self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])
|
self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])
|
||||||
|
|
||||||
def _test_to_python(self, f):
|
def _test_to_python(self, f):
|
||||||
self.assertTrue(f.to_python(1) is True)
|
self.assertIs(f.to_python(1), True)
|
||||||
self.assertTrue(f.to_python(0) is False)
|
self.assertIs(f.to_python(0), False)
|
||||||
|
|
||||||
def test_booleanfield_get_db_prep_lookup(self):
|
def test_booleanfield_get_db_prep_lookup(self):
|
||||||
self._test_get_db_prep_lookup(models.BooleanField())
|
self._test_get_db_prep_lookup(models.BooleanField())
|
||||||
|
|
|
@ -258,7 +258,7 @@ class ModelFormBaseTest(TestCase):
|
||||||
except FieldError as e:
|
except FieldError as e:
|
||||||
# Make sure the exception contains some reference to the
|
# Make sure the exception contains some reference to the
|
||||||
# field responsible for the problem.
|
# field responsible for the problem.
|
||||||
self.assertTrue('no-field' in e.args[0])
|
self.assertIn('no-field', e.args[0])
|
||||||
else:
|
else:
|
||||||
self.fail('Invalid "no-field" field not caught')
|
self.fail('Invalid "no-field" field not caught')
|
||||||
|
|
||||||
|
@ -1464,8 +1464,8 @@ class ModelChoiceFieldTests(TestCase):
|
||||||
field1 = form1.fields['category']
|
field1 = form1.fields['category']
|
||||||
# To allow the widget to change the queryset of field1.widget.choices correctly,
|
# To allow the widget to change the queryset of field1.widget.choices correctly,
|
||||||
# without affecting other forms, the following must hold:
|
# without affecting other forms, the following must hold:
|
||||||
self.assertTrue(field1 is not ModelChoiceForm.base_fields['category'])
|
self.assertIsNot(field1, ModelChoiceForm.base_fields['category'])
|
||||||
self.assertTrue(field1.widget.choices.field is field1)
|
self.assertIs(field1.widget.choices.field, field1)
|
||||||
|
|
||||||
def test_modelchoicefield_22745(self):
|
def test_modelchoicefield_22745(self):
|
||||||
"""
|
"""
|
||||||
|
@ -1764,14 +1764,14 @@ class FileAndImageFieldTests(TestCase):
|
||||||
fields = '__all__'
|
fields = '__all__'
|
||||||
|
|
||||||
form = DocumentForm()
|
form = DocumentForm()
|
||||||
self.assertTrue('name="myfile"' in six.text_type(form))
|
self.assertIn('name="myfile"', six.text_type(form))
|
||||||
self.assertTrue('myfile-clear' not in six.text_type(form))
|
self.assertNotIn('myfile-clear', six.text_type(form))
|
||||||
form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')})
|
form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')})
|
||||||
self.assertTrue(form.is_valid())
|
self.assertTrue(form.is_valid())
|
||||||
doc = form.save(commit=False)
|
doc = form.save(commit=False)
|
||||||
self.assertEqual(doc.myfile.name, 'something.txt')
|
self.assertEqual(doc.myfile.name, 'something.txt')
|
||||||
form = DocumentForm(instance=doc)
|
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'})
|
form = DocumentForm(instance=doc, data={'myfile-clear': 'true'})
|
||||||
doc = form.save(commit=False)
|
doc = form.save(commit=False)
|
||||||
self.assertEqual(bool(doc.myfile), False)
|
self.assertEqual(bool(doc.myfile), False)
|
||||||
|
@ -1797,8 +1797,8 @@ class FileAndImageFieldTests(TestCase):
|
||||||
self.assertEqual(form.errors['myfile'],
|
self.assertEqual(form.errors['myfile'],
|
||||||
['Please either submit a file or check the clear checkbox, not both.'])
|
['Please either submit a file or check the clear checkbox, not both.'])
|
||||||
rendered = six.text_type(form)
|
rendered = six.text_type(form)
|
||||||
self.assertTrue('something.txt' in rendered)
|
self.assertIn('something.txt', rendered)
|
||||||
self.assertTrue('myfile-clear' in rendered)
|
self.assertIn('myfile-clear', rendered)
|
||||||
|
|
||||||
def test_file_field_data(self):
|
def test_file_field_data(self):
|
||||||
# Test conditions when files is either not given or empty.
|
# Test conditions when files is either not given or empty.
|
||||||
|
@ -2421,7 +2421,7 @@ class FormFieldCallbackTests(TestCase):
|
||||||
fields = "__all__"
|
fields = "__all__"
|
||||||
|
|
||||||
Form = modelform_factory(Person, form=BaseForm)
|
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):
|
def test_factory_with_widget_argument(self):
|
||||||
""" Regression for #15315: modelform_factory should accept widgets
|
""" Regression for #15315: modelform_factory should accept widgets
|
||||||
|
|
|
@ -449,11 +449,11 @@ class ModelFormsetTest(TestCase):
|
||||||
|
|
||||||
PostFormSet = modelformset_factory(Post, form=PostForm1)
|
PostFormSet = modelformset_factory(Post, form=PostForm1)
|
||||||
formset = PostFormSet()
|
formset = PostFormSet()
|
||||||
self.assertFalse("subtitle" in formset.forms[0].fields)
|
self.assertNotIn("subtitle", formset.forms[0].fields)
|
||||||
|
|
||||||
PostFormSet = modelformset_factory(Post, form=PostForm2)
|
PostFormSet = modelformset_factory(Post, form=PostForm2)
|
||||||
formset = PostFormSet()
|
formset = PostFormSet()
|
||||||
self.assertFalse("subtitle" in formset.forms[0].fields)
|
self.assertNotIn("subtitle", formset.forms[0].fields)
|
||||||
|
|
||||||
def test_custom_queryset_init(self):
|
def test_custom_queryset_init(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -203,7 +203,7 @@ class InlineFormsetTests(TestCase):
|
||||||
UserFormSet = modelformset_factory(User, fields=())
|
UserFormSet = modelformset_factory(User, fields=())
|
||||||
formset = UserFormSet()
|
formset = UserFormSet()
|
||||||
for form in formset.forms:
|
for form in formset.forms:
|
||||||
self.assertTrue('id' in form.fields)
|
self.assertIn('id', form.fields)
|
||||||
self.assertEqual(len(form.fields), 1)
|
self.assertEqual(len(form.fields), 1)
|
||||||
|
|
||||||
def test_save_as_new_with_new_inlines(self):
|
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}])
|
formset = FormSet(instance=user, initial=[{'data': 41}, {'data': 42}])
|
||||||
self.assertEqual(formset.forms[0].initial['data'], 7)
|
self.assertEqual(formset.forms[0].initial['data'], 7)
|
||||||
self.assertEqual(formset.extra_forms[0].initial['data'], 41)
|
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):
|
class FormsetTests(TestCase):
|
||||||
|
@ -282,7 +282,7 @@ class FormsetTests(TestCase):
|
||||||
formset = Formset(initial=[{'username': 'apollo11'}, {'username': 'apollo12'}])
|
formset = Formset(initial=[{'username': 'apollo11'}, {'username': 'apollo12'}])
|
||||||
self.assertEqual(formset.forms[0].initial['username'], "bibi")
|
self.assertEqual(formset.forms[0].initial['username'], "bibi")
|
||||||
self.assertEqual(formset.extra_forms[0].initial['username'], "apollo11")
|
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):
|
def test_extraneous_query_is_not_run(self):
|
||||||
Formset = modelformset_factory(Network, fields="__all__")
|
Formset = modelformset_factory(Network, fields="__all__")
|
||||||
|
|
|
@ -609,13 +609,13 @@ class RelatedM2MTests(OptionsBaseTests):
|
||||||
|
|
||||||
def test_related_m2m_asymmetrical(self):
|
def test_related_m2m_asymmetrical(self):
|
||||||
m2m = Person._meta.many_to_many
|
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()
|
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):
|
def test_related_m2m_symmetrical(self):
|
||||||
m2m = Person._meta.many_to_many
|
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()
|
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])
|
self.assertIn('friends_inherited_rel_+', [o.field.related_query_name() for o in related_m2m])
|
||||||
|
|
||||||
|
|
|
@ -1485,7 +1485,7 @@ class AuthTestCase(TestCase):
|
||||||
new_io = StringIO()
|
new_io = StringIO()
|
||||||
management.call_command('dumpdata', 'auth', format='json', database='other', stdout=new_io)
|
management.call_command('dumpdata', 'auth', format='json', database='other', stdout=new_io)
|
||||||
command_output = new_io.getvalue().strip()
|
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):
|
class AntiPetRouter(object):
|
||||||
|
|
|
@ -35,7 +35,7 @@ class NullFkTests(TestCase):
|
||||||
)
|
)
|
||||||
|
|
||||||
# Regression test for #7530, #7716.
|
# 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(
|
self.assertQuerysetEqual(
|
||||||
Comment.objects.select_related('post__forum__system_info__system_details'),
|
Comment.objects.select_related('post__forum__system_info__system_details'),
|
||||||
|
|
|
@ -22,7 +22,7 @@ class NullFkOrderingTests(TestCase):
|
||||||
# We can't compare results directly (since different databases sort NULLs to
|
# 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
|
# different ends of the ordering), but we can check that all results are
|
||||||
# returned.
|
# 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')
|
s = SystemInfo.objects.create(system_name='System Info')
|
||||||
f = Forum.objects.create(system_info=s, forum_name='First forum')
|
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
|
# 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
|
# and check the length. Before the fix, this list was too short (some values
|
||||||
# were omitted).
|
# were omitted).
|
||||||
self.assertTrue(len(list(Comment.objects.all())) == 4)
|
self.assertEqual(len(list(Comment.objects.all())), 4)
|
||||||
|
|
|
@ -190,23 +190,23 @@ class OneToOneTests(TestCase):
|
||||||
r = p.restaurant
|
r = p.restaurant
|
||||||
|
|
||||||
# Accessing the related object again returns the exactly same object
|
# 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
|
# But if we kill the cache, we get a new object
|
||||||
del p._restaurant_cache
|
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
|
# 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
|
# 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.
|
# with a new *instance* the is test below will fail if #6886 regresses.
|
||||||
r2 = Restaurant.objects.get(pk=r.pk)
|
r2 = Restaurant.objects.get(pk=r.pk)
|
||||||
p.restaurant = r2
|
p.restaurant = r2
|
||||||
self.assertTrue(p.restaurant is r2)
|
self.assertIs(p.restaurant, r2)
|
||||||
|
|
||||||
# Assigning None succeeds if field is null=True.
|
# Assigning None succeeds if field is null=True.
|
||||||
ug_bar = UndergroundBar.objects.create(place=p, serves_cocktails=False)
|
ug_bar = UndergroundBar.objects.create(place=p, serves_cocktails=False)
|
||||||
ug_bar.place = None
|
ug_bar.place = None
|
||||||
self.assertTrue(ug_bar.place is None)
|
self.assertIsNone(ug_bar.place)
|
||||||
|
|
||||||
# Assigning None fails: Place.restaurant is null=False
|
# Assigning None fails: Place.restaurant is null=False
|
||||||
self.assertRaises(ValueError, setattr, p, 'restaurant', None)
|
self.assertRaises(ValueError, setattr, p, 'restaurant', None)
|
||||||
|
@ -217,13 +217,13 @@ class OneToOneTests(TestCase):
|
||||||
# Creation using keyword argument should cache the related object.
|
# Creation using keyword argument should cache the related object.
|
||||||
p = Place.objects.get(name="Demon Dogs")
|
p = Place.objects.get(name="Demon Dogs")
|
||||||
r = Restaurant(place=p)
|
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
|
# Creation using attname keyword argument and an id will cause the related
|
||||||
# object to be fetched.
|
# object to be fetched.
|
||||||
p = Place.objects.get(name="Demon Dogs")
|
p = Place.objects.get(name="Demon Dogs")
|
||||||
r = Restaurant(place_id=p.id)
|
r = Restaurant(place_id=p.id)
|
||||||
self.assertFalse(r.place is p)
|
self.assertIsNot(r.place, p)
|
||||||
self.assertEqual(r.place, p)
|
self.assertEqual(r.place, p)
|
||||||
|
|
||||||
def test_filter_one_to_one_relations(self):
|
def test_filter_one_to_one_relations(self):
|
||||||
|
|
|
@ -213,8 +213,8 @@ class PaginationTests(unittest.TestCase):
|
||||||
eleven = 'abcdefghijk'
|
eleven = 'abcdefghijk'
|
||||||
page2 = Paginator(eleven, per_page=5, orphans=1).page(2)
|
page2 = Paginator(eleven, per_page=5, orphans=1).page(2)
|
||||||
self.assertEqual(len(page2), 6)
|
self.assertEqual(len(page2), 6)
|
||||||
self.assertTrue('k' in page2)
|
self.assertIn('k', page2)
|
||||||
self.assertFalse('a' in page2)
|
self.assertNotIn('a', page2)
|
||||||
self.assertEqual(''.join(page2), 'fghijk')
|
self.assertEqual(''.join(page2), 'fghijk')
|
||||||
self.assertEqual(''.join(reversed(page2)), 'kjihgf')
|
self.assertEqual(''.join(reversed(page2)), 'kjihgf')
|
||||||
|
|
||||||
|
|
|
@ -113,7 +113,7 @@ class PrefetchRelatedTests(TestCase):
|
||||||
70679243d1786e03557c28929f9762a119e3ac14.
|
70679243d1786e03557c28929f9762a119e3ac14.
|
||||||
"""
|
"""
|
||||||
qs = Book.objects.prefetch_related('first_time_authors')
|
qs = Book.objects.prefetch_related('first_time_authors')
|
||||||
self.assertTrue(qs[0] in qs)
|
self.assertIn(qs[0], qs)
|
||||||
|
|
||||||
def test_clear(self):
|
def test_clear(self):
|
||||||
"""
|
"""
|
||||||
|
@ -211,15 +211,15 @@ class PrefetchRelatedTests(TestCase):
|
||||||
with self.assertRaises(AttributeError) as cm:
|
with self.assertRaises(AttributeError) as cm:
|
||||||
list(qs)
|
list(qs)
|
||||||
|
|
||||||
self.assertTrue('prefetch_related' in str(cm.exception))
|
self.assertIn('prefetch_related', str(cm.exception))
|
||||||
|
|
||||||
def test_invalid_final_lookup(self):
|
def test_invalid_final_lookup(self):
|
||||||
qs = Book.objects.prefetch_related('authors__name')
|
qs = Book.objects.prefetch_related('authors__name')
|
||||||
with self.assertRaises(ValueError) as cm:
|
with self.assertRaises(ValueError) as cm:
|
||||||
list(qs)
|
list(qs)
|
||||||
|
|
||||||
self.assertTrue('prefetch_related' in str(cm.exception))
|
self.assertIn('prefetch_related', str(cm.exception))
|
||||||
self.assertTrue("name" in str(cm.exception))
|
self.assertIn("name", str(cm.exception))
|
||||||
|
|
||||||
|
|
||||||
class CustomPrefetchTests(TestCase):
|
class CustomPrefetchTests(TestCase):
|
||||||
|
|
|
@ -272,7 +272,7 @@ class ProxyModelTests(TestCase):
|
||||||
|
|
||||||
def test_content_type(self):
|
def test_content_type(self):
|
||||||
ctype = ContentType.objects.get_for_model
|
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):
|
def test_user_userproxy_userproxyproxy(self):
|
||||||
User.objects.create(name='Bruce')
|
User.objects.create(name='Bruce')
|
||||||
|
@ -396,9 +396,9 @@ class ProxyModelAdminTests(TestCase):
|
||||||
with self.assertNumQueries(7):
|
with self.assertNumQueries(7):
|
||||||
collector = admin.utils.NestedObjects('default')
|
collector = admin.utils.NestedObjects('default')
|
||||||
collector.collect(ProxyTrackerUser.objects.all())
|
collector.collect(ProxyTrackerUser.objects.all())
|
||||||
self.assertTrue(tracker_user in collector.edges.get(None, ()))
|
self.assertIn(tracker_user, collector.edges.get(None, ()))
|
||||||
self.assertTrue(base_user in collector.edges.get(None, ()))
|
self.assertIn(base_user, collector.edges.get(None, ()))
|
||||||
self.assertTrue(issue in collector.edges.get(tracker_user, ()))
|
self.assertIn(issue, collector.edges.get(tracker_user, ()))
|
||||||
|
|
||||||
def test_delete_str_in_model_admin(self):
|
def test_delete_str_in_model_admin(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -127,7 +127,7 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
def test_ticket2306(self):
|
def test_ticket2306(self):
|
||||||
# Checking that no join types are "left outer" joins.
|
# Checking that no join types are "left outer" joins.
|
||||||
query = Item.objects.filter(tags=self.t2).query
|
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(
|
self.assertQuerysetEqual(
|
||||||
Item.objects.filter(Q(tags=self.t1)).order_by('name'),
|
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.
|
# Excluding from a relation that cannot be NULL should not use outer joins.
|
||||||
query = Item.objects.exclude(creator__in=[self.a1, self.a2]).query
|
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
|
# Similarly, when one of the joins cannot possibly, ever, involve NULL
|
||||||
# values (Author -> ExtraInfo, in the following), it should never be
|
# values (Author -> ExtraInfo, in the following), it should never be
|
||||||
|
@ -500,7 +500,7 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
# actually allow both "foo" and "foo_id".
|
# actually allow both "foo" and "foo_id".
|
||||||
|
|
||||||
# The *_id version is returned by default.
|
# 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.
|
# You can also pass it in explicitly.
|
||||||
self.assertValueQuerysetEqual(
|
self.assertValueQuerysetEqual(
|
||||||
|
@ -777,14 +777,14 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
self.assertQuerysetEqual(qs, ['<Author: a1>', '<Author: a2>'])
|
self.assertQuerysetEqual(qs, ['<Author: a1>', '<Author: a2>'])
|
||||||
|
|
||||||
# The subquery result cache should not be populated
|
# 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)
|
subq = Author.objects.filter(num__lt=3000)
|
||||||
qs = Author.objects.exclude(pk__in=subq)
|
qs = Author.objects.exclude(pk__in=subq)
|
||||||
self.assertQuerysetEqual(qs, ['<Author: a3>', '<Author: a4>'])
|
self.assertQuerysetEqual(qs, ['<Author: a3>', '<Author: a4>'])
|
||||||
|
|
||||||
# The subquery result cache should not be populated
|
# 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)
|
subq = Author.objects.filter(num__lt=3000)
|
||||||
self.assertQuerysetEqual(
|
self.assertQuerysetEqual(
|
||||||
|
@ -793,7 +793,7 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
)
|
)
|
||||||
|
|
||||||
# The subquery result cache should not be populated
|
# The subquery result cache should not be populated
|
||||||
self.assertTrue(subq._result_cache is None)
|
self.assertIsNone(subq._result_cache)
|
||||||
|
|
||||||
def test_ticket7076(self):
|
def test_ticket7076(self):
|
||||||
# Excluding shouldn't eliminate NULL entries.
|
# Excluding shouldn't eliminate NULL entries.
|
||||||
|
@ -911,7 +911,7 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
q = Tag.objects.filter(parent__isnull=True)
|
q = Tag.objects.filter(parent__isnull=True)
|
||||||
|
|
||||||
self.assertQuerysetEqual(q, ['<Tag: t1>'])
|
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)
|
q = Tag.objects.filter(parent__isnull=False)
|
||||||
|
|
||||||
|
@ -919,18 +919,18 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
q,
|
q,
|
||||||
['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'],
|
['<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)
|
q = Tag.objects.exclude(parent__isnull=True)
|
||||||
self.assertQuerysetEqual(
|
self.assertQuerysetEqual(
|
||||||
q,
|
q,
|
||||||
['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'],
|
['<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)
|
q = Tag.objects.exclude(parent__isnull=False)
|
||||||
self.assertQuerysetEqual(q, ['<Tag: t1>'])
|
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)
|
q = Tag.objects.exclude(parent__parent__isnull=False)
|
||||||
|
|
||||||
|
@ -938,8 +938,8 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
q,
|
q,
|
||||||
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'],
|
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'],
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 1)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1)
|
||||||
self.assertTrue('INNER JOIN' not in str(q.query))
|
self.assertNotIn('INNER JOIN', str(q.query))
|
||||||
|
|
||||||
def test_ticket_10790_2(self):
|
def test_ticket_10790_2(self):
|
||||||
# Querying across several tables should strip only the last outer join,
|
# Querying across several tables should strip only the last outer join,
|
||||||
|
@ -950,8 +950,8 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
q,
|
q,
|
||||||
['<Tag: t4>', '<Tag: t5>'],
|
['<Tag: t4>', '<Tag: t5>'],
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
|
||||||
self.assertTrue(str(q.query).count('INNER JOIN') == 1)
|
self.assertEqual(str(q.query).count('INNER JOIN'), 1)
|
||||||
|
|
||||||
# Querying without isnull should not convert anything to left outer join.
|
# Querying without isnull should not convert anything to left outer join.
|
||||||
q = Tag.objects.filter(parent__parent=self.t1)
|
q = Tag.objects.filter(parent__parent=self.t1)
|
||||||
|
@ -959,22 +959,22 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
q,
|
q,
|
||||||
['<Tag: t4>', '<Tag: t5>'],
|
['<Tag: t4>', '<Tag: t5>'],
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
|
||||||
self.assertTrue(str(q.query).count('INNER JOIN') == 1)
|
self.assertEqual(str(q.query).count('INNER JOIN'), 1)
|
||||||
|
|
||||||
def test_ticket_10790_3(self):
|
def test_ticket_10790_3(self):
|
||||||
# Querying via indirect fields should populate the left outer join
|
# Querying via indirect fields should populate the left outer join
|
||||||
q = NamedCategory.objects.filter(tag__isnull=True)
|
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
|
# 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, [])
|
self.assertQuerysetEqual(q, [])
|
||||||
|
|
||||||
# Querying across several tables should strip only the last join, while
|
# Querying across several tables should strip only the last join, while
|
||||||
# preserving the preceding left outer joins.
|
# preserving the preceding left outer joins.
|
||||||
q = NamedCategory.objects.filter(tag__parent__isnull=True)
|
q = NamedCategory.objects.filter(tag__parent__isnull=True)
|
||||||
self.assertTrue(str(q.query).count('INNER JOIN') == 1)
|
self.assertEqual(str(q.query).count('INNER JOIN'), 1)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 1)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1)
|
||||||
self.assertQuerysetEqual(q, ['<NamedCategory: Generic>'])
|
self.assertQuerysetEqual(q, ['<NamedCategory: Generic>'])
|
||||||
|
|
||||||
def test_ticket_10790_4(self):
|
def test_ticket_10790_4(self):
|
||||||
|
@ -984,16 +984,16 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
q,
|
q,
|
||||||
['<Author: a2>', '<Author: a3>'],
|
['<Author: a2>', '<Author: a3>'],
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 2)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 2)
|
||||||
self.assertTrue('INNER JOIN' not in str(q.query))
|
self.assertNotIn('INNER JOIN', str(q.query))
|
||||||
|
|
||||||
q = Author.objects.filter(item__tags__parent__isnull=True)
|
q = Author.objects.filter(item__tags__parent__isnull=True)
|
||||||
self.assertQuerysetEqual(
|
self.assertQuerysetEqual(
|
||||||
q,
|
q,
|
||||||
['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a3>'],
|
['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a3>'],
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 3)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 3)
|
||||||
self.assertTrue('INNER JOIN' not in str(q.query))
|
self.assertNotIn('INNER JOIN', str(q.query))
|
||||||
|
|
||||||
def test_ticket_10790_5(self):
|
def test_ticket_10790_5(self):
|
||||||
# Querying with isnull=False across m2m field should not create outer joins
|
# Querying with isnull=False across m2m field should not create outer joins
|
||||||
|
@ -1002,24 +1002,24 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
q,
|
q,
|
||||||
['<Author: a1>', '<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a4>']
|
['<Author: a1>', '<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a4>']
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
|
||||||
self.assertTrue(str(q.query).count('INNER JOIN') == 2)
|
self.assertEqual(str(q.query).count('INNER JOIN'), 2)
|
||||||
|
|
||||||
q = Author.objects.filter(item__tags__parent__isnull=False)
|
q = Author.objects.filter(item__tags__parent__isnull=False)
|
||||||
self.assertQuerysetEqual(
|
self.assertQuerysetEqual(
|
||||||
q,
|
q,
|
||||||
['<Author: a1>', '<Author: a2>', '<Author: a4>']
|
['<Author: a1>', '<Author: a2>', '<Author: a4>']
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
|
||||||
self.assertTrue(str(q.query).count('INNER JOIN') == 3)
|
self.assertEqual(str(q.query).count('INNER JOIN'), 3)
|
||||||
|
|
||||||
q = Author.objects.filter(item__tags__parent__parent__isnull=False)
|
q = Author.objects.filter(item__tags__parent__parent__isnull=False)
|
||||||
self.assertQuerysetEqual(
|
self.assertQuerysetEqual(
|
||||||
q,
|
q,
|
||||||
['<Author: a4>']
|
['<Author: a4>']
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
|
||||||
self.assertTrue(str(q.query).count('INNER JOIN') == 4)
|
self.assertEqual(str(q.query).count('INNER JOIN'), 4)
|
||||||
|
|
||||||
def test_ticket_10790_6(self):
|
def test_ticket_10790_6(self):
|
||||||
# Querying with isnull=True across m2m field should not create inner joins
|
# 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: a1>', '<Author: a1>', '<Author: a2>', '<Author: a2>',
|
||||||
'<Author: a2>', '<Author: a3>']
|
'<Author: a2>', '<Author: a3>']
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 4)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 4)
|
||||||
self.assertTrue(str(q.query).count('INNER JOIN') == 0)
|
self.assertEqual(str(q.query).count('INNER JOIN'), 0)
|
||||||
|
|
||||||
q = Author.objects.filter(item__tags__parent__isnull=True)
|
q = Author.objects.filter(item__tags__parent__isnull=True)
|
||||||
self.assertQuerysetEqual(
|
self.assertQuerysetEqual(
|
||||||
q,
|
q,
|
||||||
['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a3>']
|
['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a3>']
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 3)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 3)
|
||||||
self.assertTrue(str(q.query).count('INNER JOIN') == 0)
|
self.assertEqual(str(q.query).count('INNER JOIN'), 0)
|
||||||
|
|
||||||
def test_ticket_10790_7(self):
|
def test_ticket_10790_7(self):
|
||||||
# Reverse querying with isnull should not strip the join
|
# Reverse querying with isnull should not strip the join
|
||||||
|
@ -1048,16 +1048,16 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
q,
|
q,
|
||||||
['<Author: a3>']
|
['<Author: a3>']
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 1)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1)
|
||||||
self.assertTrue(str(q.query).count('INNER JOIN') == 0)
|
self.assertEqual(str(q.query).count('INNER JOIN'), 0)
|
||||||
|
|
||||||
q = Author.objects.filter(item__isnull=False)
|
q = Author.objects.filter(item__isnull=False)
|
||||||
self.assertQuerysetEqual(
|
self.assertQuerysetEqual(
|
||||||
q,
|
q,
|
||||||
['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a4>']
|
['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a4>']
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
|
||||||
self.assertTrue(str(q.query).count('INNER JOIN') == 1)
|
self.assertEqual(str(q.query).count('INNER JOIN'), 1)
|
||||||
|
|
||||||
def test_ticket_10790_8(self):
|
def test_ticket_10790_8(self):
|
||||||
# Querying with combined q-objects should also strip the left outer join
|
# Querying with combined q-objects should also strip the left outer join
|
||||||
|
@ -1066,8 +1066,8 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
q,
|
q,
|
||||||
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
|
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
|
self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
|
||||||
self.assertTrue(str(q.query).count('INNER JOIN') == 0)
|
self.assertEqual(str(q.query).count('INNER JOIN'), 0)
|
||||||
|
|
||||||
def test_ticket_10790_combine(self):
|
def test_ticket_10790_combine(self):
|
||||||
# Combining queries should not re-populate the left outer join
|
# Combining queries should not re-populate the left outer join
|
||||||
|
@ -1079,13 +1079,13 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
q3,
|
q3,
|
||||||
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'],
|
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'],
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 0)
|
self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0)
|
||||||
self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
|
self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
|
||||||
|
|
||||||
q3 = q1 & q2
|
q3 = q1 & q2
|
||||||
self.assertQuerysetEqual(q3, [])
|
self.assertQuerysetEqual(q3, [])
|
||||||
self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 0)
|
self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0)
|
||||||
self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
|
self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
|
||||||
|
|
||||||
q2 = Tag.objects.filter(parent=self.t1)
|
q2 = Tag.objects.filter(parent=self.t1)
|
||||||
q3 = q1 | q2
|
q3 = q1 | q2
|
||||||
|
@ -1093,16 +1093,16 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
q3,
|
q3,
|
||||||
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
|
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 0)
|
self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0)
|
||||||
self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
|
self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
|
||||||
|
|
||||||
q3 = q2 | q1
|
q3 = q2 | q1
|
||||||
self.assertQuerysetEqual(
|
self.assertQuerysetEqual(
|
||||||
q3,
|
q3,
|
||||||
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
|
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 0)
|
self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0)
|
||||||
self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
|
self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
|
||||||
|
|
||||||
q1 = Tag.objects.filter(parent__isnull=True)
|
q1 = Tag.objects.filter(parent__isnull=True)
|
||||||
q2 = Tag.objects.filter(parent__parent__isnull=True)
|
q2 = Tag.objects.filter(parent__parent__isnull=True)
|
||||||
|
@ -1112,16 +1112,16 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
q3,
|
q3,
|
||||||
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
|
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 1)
|
self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 1)
|
||||||
self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
|
self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
|
||||||
|
|
||||||
q3 = q2 | q1
|
q3 = q2 | q1
|
||||||
self.assertQuerysetEqual(
|
self.assertQuerysetEqual(
|
||||||
q3,
|
q3,
|
||||||
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
|
['<Tag: t1>', '<Tag: t2>', '<Tag: t3>']
|
||||||
)
|
)
|
||||||
self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 1)
|
self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 1)
|
||||||
self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
|
self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
|
||||||
|
|
||||||
def test_ticket19672(self):
|
def test_ticket19672(self):
|
||||||
self.assertQuerysetEqual(
|
self.assertQuerysetEqual(
|
||||||
|
@ -1135,7 +1135,7 @@ class Queries1Tests(BaseQuerysetTest):
|
||||||
qs = Author.objects.annotate(Count('item'))
|
qs = Author.objects.annotate(Count('item'))
|
||||||
qs = qs.filter(~Q(extra__value=0))
|
qs = qs.filter(~Q(extra__value=0))
|
||||||
|
|
||||||
self.assertTrue('SELECT' in str(qs.query))
|
self.assertIn('SELECT', str(qs.query))
|
||||||
self.assertQuerysetEqual(
|
self.assertQuerysetEqual(
|
||||||
qs,
|
qs,
|
||||||
['<Author: a1>', '<Author: a2>', '<Author: a3>', '<Author: a4>']
|
['<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
|
# 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.
|
# model. But it should still be possible to add new ordering after that.
|
||||||
qs = Author.objects.order_by().order_by('name')
|
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):
|
def test_order_by_reverse_fk(self):
|
||||||
# It is possible to order by reverse of foreign key, although that can lead
|
# 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)
|
r = RelatedObject.objects.create(single=s, f=1)
|
||||||
Plaything.objects.create(name="p2", others=r)
|
Plaything.objects.create(name="p2", others=r)
|
||||||
qs = Plaything.objects.all().filter(others__isnull=False).order_by('pk')
|
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')
|
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')
|
qs = qs.order_by('others__single__name')
|
||||||
# The ordering by others__single__pk will add one new join (to single)
|
# 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
|
# 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)
|
self.assertEqual(len(captured_queries), 1)
|
||||||
qstr = captured_queries[0]
|
qstr = captured_queries[0]
|
||||||
id, name = connection.ops.quote_name('id'), connection.ops.quote_name('name')
|
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):
|
def test_ticket_18414(self):
|
||||||
Article.objects.create(name='one', created=datetime.datetime.now())
|
Article.objects.create(name='one', created=datetime.datetime.now())
|
||||||
|
@ -2961,13 +2962,13 @@ class NullJoinPromotionOrTest(TestCase):
|
||||||
|
|
||||||
def test_null_join_demotion(self):
|
def test_null_join_demotion(self):
|
||||||
qs = ModelA.objects.filter(Q(b__name__isnull=False) & Q(b__name__isnull=True))
|
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))
|
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))
|
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))
|
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):
|
def test_ticket_21366(self):
|
||||||
n = Note.objects.create(note='n', misc='m')
|
n = Note.objects.create(note='n', misc='m')
|
||||||
|
@ -3314,9 +3315,9 @@ class Ticket20101Tests(TestCase):
|
||||||
n = Note.objects.create(note='foo', misc='bar')
|
n = Note.objects.create(note='foo', misc='bar')
|
||||||
qs1 = Note.objects.exclude(annotation__in=[a1, a2])
|
qs1 = Note.objects.exclude(annotation__in=[a1, a2])
|
||||||
qs2 = Note.objects.filter(annotation__in=[a3])
|
qs2 = Note.objects.filter(annotation__in=[a3])
|
||||||
self.assertTrue(n in qs1)
|
self.assertIn(n, qs1)
|
||||||
self.assertFalse(n in qs2)
|
self.assertNotIn(n, qs2)
|
||||||
self.assertTrue(n in (qs1 | qs2))
|
self.assertIn(n, (qs1 | qs2))
|
||||||
|
|
||||||
|
|
||||||
class EmptyStringPromotionTests(TestCase):
|
class EmptyStringPromotionTests(TestCase):
|
||||||
|
@ -3545,16 +3546,16 @@ class Ticket21203Tests(TestCase):
|
||||||
class ValuesJoinPromotionTests(TestCase):
|
class ValuesJoinPromotionTests(TestCase):
|
||||||
def test_values_no_promotion_for_existing(self):
|
def test_values_no_promotion_for_existing(self):
|
||||||
qs = Node.objects.filter(parent__parent__isnull=False)
|
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')
|
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.
|
# Make sure there is a left outer join without the filter.
|
||||||
qs = Node.objects.values('parent__parent__id')
|
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):
|
def test_non_nullable_fk_not_promoted(self):
|
||||||
qs = ObjectB.objects.values('objecta__name')
|
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):
|
def test_ticket_21376(self):
|
||||||
a = ObjectA.objects.create()
|
a = ObjectA.objects.create()
|
||||||
|
@ -3567,7 +3568,7 @@ class ValuesJoinPromotionTests(TestCase):
|
||||||
)
|
)
|
||||||
self.assertEqual(qs.count(), 1)
|
self.assertEqual(qs.count(), 1)
|
||||||
tblname = connection.ops.quote_name(ObjectB._meta.db_table)
|
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):
|
class ForeignKeyToBaseExcludeTests(TestCase):
|
||||||
|
|
|
@ -73,9 +73,9 @@ class RawQueryTests(TestCase):
|
||||||
iterated over.
|
iterated over.
|
||||||
"""
|
"""
|
||||||
q = Author.objects.raw('SELECT * FROM raw_query_author')
|
q = Author.objects.raw('SELECT * FROM raw_query_author')
|
||||||
self.assertTrue(q.query.cursor is None)
|
self.assertIsNone(q.query.cursor)
|
||||||
list(q)
|
list(q)
|
||||||
self.assertTrue(q.query.cursor is not None)
|
self.assertIsNotNone(q.query.cursor)
|
||||||
|
|
||||||
def test_FK_raw_query(self):
|
def test_FK_raw_query(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -204,7 +204,7 @@ class RequestsTests(SimpleTestCase):
|
||||||
example_cookie = response.cookies['example']
|
example_cookie = response.cookies['example']
|
||||||
# A compat cookie may be in use -- check that it has worked
|
# A compat cookie may be in use -- check that it has worked
|
||||||
# both as an output string, and using the cookie attributes
|
# 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'])
|
self.assertTrue(example_cookie['httponly'])
|
||||||
|
|
||||||
def test_unicode_cookie(self):
|
def test_unicode_cookie(self):
|
||||||
|
|
|
@ -152,7 +152,7 @@ class SelectRelatedRegressTests(TestCase):
|
||||||
self.assertEqual(qs[0].state, wa)
|
self.assertEqual(qs[0].state, wa)
|
||||||
# The select_related join wasn't promoted as there was already an
|
# The select_related join wasn't promoted as there was already an
|
||||||
# existing (even if trimmed) inner join to state.
|
# 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')
|
qs = Client.objects.select_related('state').order_by('name')
|
||||||
with self.assertNumQueries(1):
|
with self.assertNumQueries(1):
|
||||||
self.assertEqual(list(qs), [bob, jack])
|
self.assertEqual(list(qs), [bob, jack])
|
||||||
|
@ -160,7 +160,7 @@ class SelectRelatedRegressTests(TestCase):
|
||||||
self.assertEqual(qs[1].state, wa)
|
self.assertEqual(qs[1].state, wa)
|
||||||
# The select_related join was promoted as there is already an
|
# The select_related join was promoted as there is already an
|
||||||
# existing join.
|
# existing join.
|
||||||
self.assertTrue('LEFT OUTER' in str(qs.query))
|
self.assertIn('LEFT OUTER', str(qs.query))
|
||||||
|
|
||||||
def test_regression_19870(self):
|
def test_regression_19870(self):
|
||||||
hen = Hen.objects.create(name='Hen')
|
hen = Hen.objects.create(name='Hen')
|
||||||
|
|
|
@ -281,7 +281,7 @@ class TestComplexSettingOverride(TestCase):
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
signals.COMPLEX_OVERRIDE_SETTINGS = self.old_warn_override_settings
|
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):
|
def test_complex_override_warning(self):
|
||||||
"""Regression test for #19031"""
|
"""Regression test for #19031"""
|
||||||
|
|
|
@ -403,7 +403,7 @@ class TemplateRegressionTests(TestCase):
|
||||||
while tb.tb_next is not None:
|
while tb.tb_next is not None:
|
||||||
tb = tb.tb_next
|
tb = tb.tb_next
|
||||||
depth += 1
|
depth += 1
|
||||||
self.assertTrue(depth > 5,
|
self.assertGreater(depth, 5,
|
||||||
"The traceback context was lost when reraising the traceback. See #19827")
|
"The traceback context was lost when reraising the traceback. See #19827")
|
||||||
|
|
||||||
@override_settings(DEBUG=True, TEMPLATE_DEBUG=True)
|
@override_settings(DEBUG=True, TEMPLATE_DEBUG=True)
|
||||||
|
@ -1852,8 +1852,8 @@ class TemplateTagLoading(TestCase):
|
||||||
try:
|
try:
|
||||||
template.Template(ttext)
|
template.Template(ttext)
|
||||||
except template.TemplateSyntaxError as e:
|
except template.TemplateSyntaxError as e:
|
||||||
self.assertTrue('ImportError' in e.args[0])
|
self.assertIn('ImportError', e.args[0])
|
||||||
self.assertTrue('Xtemplate' in e.args[0])
|
self.assertIn('Xtemplate', e.args[0])
|
||||||
|
|
||||||
def test_load_error_egg(self):
|
def test_load_error_egg(self):
|
||||||
ttext = "{% load broken_egg %}"
|
ttext = "{% load broken_egg %}"
|
||||||
|
@ -1866,8 +1866,8 @@ class TemplateTagLoading(TestCase):
|
||||||
with self.settings(INSTALLED_APPS=['tagsegg']):
|
with self.settings(INSTALLED_APPS=['tagsegg']):
|
||||||
template.Template(ttext)
|
template.Template(ttext)
|
||||||
except template.TemplateSyntaxError as e:
|
except template.TemplateSyntaxError as e:
|
||||||
self.assertTrue('ImportError' in e.args[0])
|
self.assertIn('ImportError', e.args[0])
|
||||||
self.assertTrue('Xtemplate' in e.args[0])
|
self.assertIn('Xtemplate', e.args[0])
|
||||||
|
|
||||||
def test_load_working_egg(self):
|
def test_load_working_egg(self):
|
||||||
ttext = "{% load working_egg %}"
|
ttext = "{% load working_egg %}"
|
||||||
|
|
|
@ -955,7 +955,7 @@ class ContextTests(TestCase):
|
||||||
"Context variables can be retrieved from a single context"
|
"Context variables can be retrieved from a single context"
|
||||||
response = self.client.get("/request_data/", data={'foo': 'whiz'})
|
response = self.client.get("/request_data/", data={'foo': 'whiz'})
|
||||||
self.assertEqual(response.context.__class__, Context)
|
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['get-foo'], 'whiz')
|
||||||
self.assertEqual(response.context['request-foo'], 'whiz')
|
self.assertEqual(response.context['request-foo'], 'whiz')
|
||||||
self.assertEqual(response.context['data'], 'sausage')
|
self.assertEqual(response.context['data'], 'sausage')
|
||||||
|
@ -971,7 +971,7 @@ class ContextTests(TestCase):
|
||||||
response = self.client.get("/request_data_extended/", data={'foo': 'whiz'})
|
response = self.client.get("/request_data_extended/", data={'foo': 'whiz'})
|
||||||
self.assertEqual(response.context.__class__, ContextList)
|
self.assertEqual(response.context.__class__, ContextList)
|
||||||
self.assertEqual(len(response.context), 2)
|
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['get-foo'], 'whiz')
|
||||||
self.assertEqual(response.context['request-foo'], 'whiz')
|
self.assertEqual(response.context['request-foo'], 'whiz')
|
||||||
self.assertEqual(response.context['data'], 'bacon')
|
self.assertEqual(response.context['data'], 'bacon')
|
||||||
|
|
|
@ -399,7 +399,7 @@ class DeprecationDisplayTest(AdminScriptTestCase):
|
||||||
args = ['test', '--settings=test_project.settings', '--verbosity=0', 'test_runner_deprecation_app']
|
args = ['test', '--settings=test_project.settings', '--verbosity=0', 'test_runner_deprecation_app']
|
||||||
out, err = self.run_django_admin(args)
|
out, err = self.run_django_admin(args)
|
||||||
self.assertIn("Ran 1 test", err)
|
self.assertIn("Ran 1 test", err)
|
||||||
self.assertFalse("warning from test" in err)
|
self.assertNotIn("warning from test", err)
|
||||||
|
|
||||||
|
|
||||||
class AutoIncrementResetTest(TransactionTestCase):
|
class AutoIncrementResetTest(TransactionTestCase):
|
||||||
|
|
|
@ -542,24 +542,24 @@ class HTMLEqualTests(TestCase):
|
||||||
# equal html contains each other
|
# equal html contains each other
|
||||||
dom1 = parse_html('<p>foo')
|
dom1 = parse_html('<p>foo')
|
||||||
dom2 = parse_html('<p>foo</p>')
|
dom2 = parse_html('<p>foo</p>')
|
||||||
self.assertTrue(dom1 in dom2)
|
self.assertIn(dom1, dom2)
|
||||||
self.assertTrue(dom2 in dom1)
|
self.assertIn(dom2, dom1)
|
||||||
|
|
||||||
dom2 = parse_html('<div><p>foo</p></div>')
|
dom2 = parse_html('<div><p>foo</p></div>')
|
||||||
self.assertTrue(dom1 in dom2)
|
self.assertIn(dom1, dom2)
|
||||||
self.assertTrue(dom2 not in dom1)
|
self.assertNotIn(dom2, dom1)
|
||||||
|
|
||||||
self.assertFalse('<p>foo</p>' in dom2)
|
self.assertNotIn('<p>foo</p>', dom2)
|
||||||
self.assertTrue('foo' in dom2)
|
self.assertIn('foo', dom2)
|
||||||
|
|
||||||
# when a root element is used ...
|
# when a root element is used ...
|
||||||
dom1 = parse_html('<p>foo</p><p>bar</p>')
|
dom1 = parse_html('<p>foo</p><p>bar</p>')
|
||||||
dom2 = 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>')
|
dom1 = parse_html('<p>foo</p>')
|
||||||
self.assertTrue(dom1 in dom2)
|
self.assertIn(dom1, dom2)
|
||||||
dom1 = parse_html('<p>bar</p>')
|
dom1 = parse_html('<p>bar</p>')
|
||||||
self.assertTrue(dom1 in dom2)
|
self.assertIn(dom1, dom2)
|
||||||
|
|
||||||
def test_count(self):
|
def test_count(self):
|
||||||
# equal html contains each other one time
|
# equal html contains each other one time
|
||||||
|
|
|
@ -50,7 +50,7 @@ class ManyToManyUnmanagedTests(TestCase):
|
||||||
"""
|
"""
|
||||||
table = Unmanaged2._meta.get_field('mm').m2m_db_table()
|
table = Unmanaged2._meta.get_field('mm').m2m_db_table()
|
||||||
tables = connection.introspection.table_names()
|
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):
|
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()
|
table = Managed1._meta.get_field('mm').m2m_db_table()
|
||||||
tables = connection.introspection.table_names()
|
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)
|
||||||
|
|
|
@ -204,10 +204,10 @@ class UpdateOnlyFieldsTests(TestCase):
|
||||||
p.save(update_fields=['name'])
|
p.save(update_fields=['name'])
|
||||||
self.assertEqual(len(pre_save_data), 1)
|
self.assertEqual(len(pre_save_data), 1)
|
||||||
self.assertEqual(len(pre_save_data[0]), 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), 1)
|
||||||
self.assertEqual(len(post_save_data[0]), 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)
|
pre_save.disconnect(pre_save_receiver)
|
||||||
post_save.disconnect(post_save_receiver)
|
post_save.disconnect(post_save_receiver)
|
||||||
|
|
|
@ -292,7 +292,7 @@ class ResolverTests(unittest.TestCase):
|
||||||
self.fail('resolve did not raise a 404')
|
self.fail('resolve did not raise a 404')
|
||||||
except Resolver404 as e:
|
except Resolver404 as e:
|
||||||
# make sure we at least matched the root ('/') url resolver:
|
# 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']
|
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'])))
|
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):
|
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'])
|
self.assertIsInstance(t, e['type']), str('%s is not an instance of %s') % (t, e['type'])
|
||||||
if 'name' in e:
|
if 'name' in e:
|
||||||
if not e['name']:
|
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:
|
else:
|
||||||
self.assertEqual(t.name, e['name'], 'Wrong URL name. Expected "%s", got "%s".' % (e['name'], t.name))
|
self.assertEqual(t.name, e['name'], 'Wrong URL name. Expected "%s", got "%s".' % (e['name'], t.name))
|
||||||
|
|
||||||
|
|
|
@ -177,7 +177,7 @@ class MergeDictTests(IgnoreDeprecationWarningsMixin, SimpleTestCase):
|
||||||
self.assertEqual(sorted(six.iterkeys(mm)), ['key1', 'key2', 'key4'])
|
self.assertEqual(sorted(six.iterkeys(mm)), ['key1', 'key2', 'key4'])
|
||||||
self.assertEqual(len(list(six.itervalues(mm))), 3)
|
self.assertEqual(len(list(six.itervalues(mm))), 3)
|
||||||
|
|
||||||
self.assertTrue('value1' in six.itervalues(mm))
|
self.assertIn('value1', six.itervalues(mm))
|
||||||
|
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
sorted(six.iteritems(mm), key=lambda k: k[0]),
|
sorted(six.iteritems(mm), key=lambda k: k[0]),
|
||||||
|
|
|
@ -20,7 +20,7 @@ class FunctionalTestCase(unittest.TestCase):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
t = lazy(lambda: Klazz(), Klazz)()
|
t = lazy(lambda: Klazz(), Klazz)()
|
||||||
self.assertTrue('base_method' in dir(t))
|
self.assertIn('base_method', dir(t))
|
||||||
|
|
||||||
def test_lazy_property(self):
|
def test_lazy_property(self):
|
||||||
|
|
||||||
|
|
|
@ -47,7 +47,7 @@ class TestUtilsHttp(unittest.TestCase):
|
||||||
'c=3&a=1&b=2',
|
'c=3&a=1&b=2',
|
||||||
'c=3&b=2&a=1'
|
'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)
|
result = http.urlencode({'a': [1, 2]}, doseq=False)
|
||||||
self.assertEqual(result, 'a=%5B%271%27%2C+%272%27%5D')
|
self.assertEqual(result, 'a=%5B%271%27%2C+%272%27%5D')
|
||||||
result = http.urlencode({'a': [1, 2]}, doseq=True)
|
result = http.urlencode({'a': [1, 2]}, doseq=True)
|
||||||
|
@ -65,7 +65,7 @@ class TestUtilsHttp(unittest.TestCase):
|
||||||
'name=Adrian&name=Simon&position=Developer',
|
'name=Adrian&name=Simon&position=Developer',
|
||||||
'position=Developer&name=Adrian&name=Simon'
|
'position=Developer&name=Adrian&name=Simon'
|
||||||
]
|
]
|
||||||
self.assertTrue(result in acceptable_results)
|
self.assertIn(result, acceptable_results)
|
||||||
|
|
||||||
def test_base36(self):
|
def test_base36(self):
|
||||||
# reciprocity works
|
# reciprocity works
|
||||||
|
|
|
@ -257,8 +257,8 @@ class SimpleLazyObjectTestCase(LazyObjectTestCase):
|
||||||
self.assertEqual(lazydict['one'], 1)
|
self.assertEqual(lazydict['one'], 1)
|
||||||
lazydict['one'] = -1
|
lazydict['one'] = -1
|
||||||
self.assertEqual(lazydict['one'], -1)
|
self.assertEqual(lazydict['one'], -1)
|
||||||
self.assertTrue('one' in lazydict)
|
self.assertIn('one', lazydict)
|
||||||
self.assertFalse('two' in lazydict)
|
self.assertNotIn('two', lazydict)
|
||||||
self.assertEqual(len(lazydict), 1)
|
self.assertEqual(len(lazydict), 1)
|
||||||
del lazydict['one']
|
del lazydict['one']
|
||||||
with self.assertRaises(KeyError):
|
with self.assertRaises(KeyError):
|
||||||
|
@ -267,9 +267,9 @@ class SimpleLazyObjectTestCase(LazyObjectTestCase):
|
||||||
def test_list_set(self):
|
def test_list_set(self):
|
||||||
lazy_list = SimpleLazyObject(lambda: [1, 2, 3, 4, 5])
|
lazy_list = SimpleLazyObject(lambda: [1, 2, 3, 4, 5])
|
||||||
lazy_set = SimpleLazyObject(lambda: {1, 2, 3, 4})
|
lazy_set = SimpleLazyObject(lambda: {1, 2, 3, 4})
|
||||||
self.assertTrue(1 in lazy_list)
|
self.assertIn(1, lazy_list)
|
||||||
self.assertTrue(1 in lazy_set)
|
self.assertIn(1, lazy_set)
|
||||||
self.assertFalse(6 in lazy_list)
|
self.assertNotIn(6, lazy_list)
|
||||||
self.assertFalse(6 in lazy_set)
|
self.assertNotIn(6, lazy_set)
|
||||||
self.assertEqual(len(lazy_list), 5)
|
self.assertEqual(len(lazy_list), 5)
|
||||||
self.assertEqual(len(lazy_set), 4)
|
self.assertEqual(len(lazy_set), 4)
|
||||||
|
|
|
@ -115,7 +115,7 @@ class DebugViewTests(TestCase):
|
||||||
# '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"'
|
# '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"'
|
||||||
self.assertContains(response, '<div class="context" id="', status_code=500)
|
self.assertContains(response, '<div class="context" id="', status_code=500)
|
||||||
match = re.search(b'<div class="context" id="(?P<id>[^"]+)">', response.content)
|
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')
|
id_repr = match.group('id')
|
||||||
self.assertFalse(re.search(b'[^c0-9]', id_repr),
|
self.assertFalse(re.search(b'[^c0-9]', id_repr),
|
||||||
"Numeric IDs in debug response HTML page shouldn't be localized (value: %s)." % 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,)))
|
self.client.get(reverse('template_exception', args=(n,)))
|
||||||
except Exception:
|
except Exception:
|
||||||
raising_loc = inspect.trace()[-1][-2][0].strip()
|
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" %
|
"Failed to find 'raise BrokenException' in last frame of traceback, instead found: %s" %
|
||||||
raising_loc)
|
raising_loc)
|
||||||
|
|
||||||
|
|
|
@ -64,7 +64,7 @@ class GetInternalWSGIApplicationTest(unittest.TestCase):
|
||||||
|
|
||||||
from .wsgi import application
|
from .wsgi import application
|
||||||
|
|
||||||
self.assertTrue(app is application)
|
self.assertIs(app, application)
|
||||||
|
|
||||||
@override_settings(WSGI_APPLICATION=None)
|
@override_settings(WSGI_APPLICATION=None)
|
||||||
def test_default(self):
|
def test_default(self):
|
||||||
|
@ -85,7 +85,7 @@ class GetInternalWSGIApplicationTest(unittest.TestCase):
|
||||||
try:
|
try:
|
||||||
app = get_internal_wsgi_application()
|
app = get_internal_wsgi_application()
|
||||||
|
|
||||||
self.assertTrue(app is fake_app)
|
self.assertIs(app, fake_app)
|
||||||
finally:
|
finally:
|
||||||
basehttp.get_wsgi_application = _orig_get_wsgi_app
|
basehttp.get_wsgi_application = _orig_get_wsgi_app
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue