file' in output)
+ self.assertNotIn(field.url, output)
+ self.assertIn('href="something?chapter=1§=2©=3&lang=en"', output)
+ self.assertNotIn(six.text_type(field), output)
+ self.assertIn('something<div onclick="alert('oops')">.jpg', output)
+ self.assertIn('my<div>file', output)
+ self.assertNotIn('my
file', output)
def test_clear_input_renders_only_if_not_required(self):
"""
diff --git a/tests/forms_tests/tests/tests.py b/tests/forms_tests/tests/tests.py
index 62b2251ede..d53d030158 100644
--- a/tests/forms_tests/tests/tests.py
+++ b/tests/forms_tests/tests/tests.py
@@ -157,7 +157,7 @@ class FormsModelTestCase(TestCase):
# FileModel with unicode filename and data #########################
f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False)
self.assertTrue(f.is_valid())
- self.assertTrue('file1' in f.cleaned_data)
+ self.assertIn('file1', f.cleaned_data)
m = FileModel.objects.create(file=f.cleaned_data['file1'])
self.assertEqual(m.file.name, 'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt')
m.delete()
diff --git a/tests/generic_relations_regress/tests.py b/tests/generic_relations_regress/tests.py
index 2804530f84..39dfa47f68 100644
--- a/tests/generic_relations_regress/tests.py
+++ b/tests/generic_relations_regress/tests.py
@@ -72,12 +72,12 @@ class GenericRelationTests(TestCase):
# search with a non-matching note and a matching org name
qs = Contact.objects.filter(Q(notes__note__icontains=r'other note') |
Q(organizations__name__icontains=r'org name'))
- self.assertTrue(org_contact in qs)
+ self.assertIn(org_contact, qs)
# search again, with the same query parameters, in reverse order
qs = Contact.objects.filter(
Q(organizations__name__icontains=r'org name') |
Q(notes__note__icontains=r'other note'))
- self.assertTrue(org_contact in qs)
+ self.assertIn(org_contact, qs)
def test_join_reuse(self):
qs = Person.objects.filter(
diff --git a/tests/generic_views/test_base.py b/tests/generic_views/test_base.py
index b23c4582e5..29e225088d 100644
--- a/tests/generic_views/test_base.py
+++ b/tests/generic_views/test_base.py
@@ -447,7 +447,7 @@ class GetContextDataTest(unittest.TestCase):
context = test_view.get_context_data(kwarg_test='kwarg_value')
# the test_name key is inserted by the test classes parent
- self.assertTrue('test_name' in context)
+ self.assertIn('test_name', context)
self.assertEqual(context['kwarg_test'], 'kwarg_value')
self.assertEqual(context['custom_key'], 'custom_value')
diff --git a/tests/generic_views/test_dates.py b/tests/generic_views/test_dates.py
index 643a9c2456..cbd9bd90a0 100644
--- a/tests/generic_views/test_dates.py
+++ b/tests/generic_views/test_dates.py
@@ -35,7 +35,7 @@ class ArchiveIndexViewTests(TestCase):
self.assertEqual(res.status_code, 200)
self.assertEqual(list(res.context['date_list']), list(Book.objects.dates('pubdate', 'year', 'DESC')))
self.assertEqual(list(res.context['thingies']), list(Book.objects.all()))
- self.assertFalse('latest' in res.context)
+ self.assertNotIn('latest', res.context)
self.assertTemplateUsed(res, 'generic_views/book_archive.html')
def test_empty_archive_view(self):
diff --git a/tests/generic_views/test_detail.py b/tests/generic_views/test_detail.py
index ca747351d6..1c8f951ca4 100644
--- a/tests/generic_views/test_detail.py
+++ b/tests/generic_views/test_detail.py
@@ -114,14 +114,14 @@ class DetailViewTest(TestCase):
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
self.assertEqual(res.context['thingy'], Author.objects.get(pk=1))
- self.assertFalse('author' in res.context)
+ self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_duplicated_context_object_name(self):
res = self.client.get('/detail/author/1/dupe_context_object_name/')
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=1))
- self.assertFalse('author' in res.context)
+ self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/author_detail.html')
def test_invalid_url(self):
diff --git a/tests/generic_views/test_edit.py b/tests/generic_views/test_edit.py
index 9f152c9af3..51f4ac6104 100644
--- a/tests/generic_views/test_edit.py
+++ b/tests/generic_views/test_edit.py
@@ -108,8 +108,8 @@ class CreateViewTests(TestCase):
self.assertEqual(res.status_code, 200)
self.assertIsInstance(res.context['form'], forms.ModelForm)
self.assertIsInstance(res.context['view'], View)
- self.assertFalse('object' in res.context)
- self.assertFalse('author' in res.context)
+ self.assertNotIn('object', res.context)
+ self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/author_form.html')
res = self.client.post('/edit/authors/create/',
@@ -153,8 +153,8 @@ class CreateViewTests(TestCase):
res = self.client.get('/edit/authors/create/special/')
self.assertEqual(res.status_code, 200)
self.assertIsInstance(res.context['form'], views.AuthorForm)
- self.assertFalse('object' in res.context)
- self.assertFalse('author' in res.context)
+ self.assertNotIn('object', res.context)
+ self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/form.html')
res = self.client.post('/edit/authors/create/special/',
@@ -302,7 +302,7 @@ class UpdateViewTests(TestCase):
self.assertIsInstance(res.context['form'], views.AuthorForm)
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk))
- self.assertFalse('author' in res.context)
+ self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/form.html')
res = self.client.post('/edit/author/%d/update/special/' % a.pk,
@@ -389,7 +389,7 @@ class DeleteViewTests(TestCase):
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk))
- self.assertFalse('author' in res.context)
+ self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/confirm_delete.html')
res = self.client.post('/edit/author/%d/delete/special/' % a.pk)
diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py
index 0be5df3024..9b9b19e180 100644
--- a/tests/httpwrappers/tests.py
+++ b/tests/httpwrappers/tests.py
@@ -78,10 +78,10 @@ class QueryDictTests(unittest.TestCase):
if six.PY2:
self.assertTrue(q.has_key('foo'))
- self.assertTrue('foo' in q)
+ self.assertIn('foo', q)
if six.PY2:
self.assertFalse(q.has_key('bar'))
- self.assertFalse('bar' in q)
+ self.assertNotIn('bar', q)
self.assertEqual(list(six.iteritems(q)), [('foo', 'bar')])
self.assertEqual(list(six.iterlists(q)), [('foo', ['bar'])])
@@ -118,7 +118,7 @@ class QueryDictTests(unittest.TestCase):
q = QueryDict(mutable=True)
q['name'] = 'john'
del q['name']
- self.assertFalse('name' in q)
+ self.assertNotIn('name', q)
def test_basic_mutable_operations(self):
q = QueryDict(mutable=True)
@@ -137,7 +137,7 @@ class QueryDictTests(unittest.TestCase):
self.assertEqual(q['foo'], 'another')
if six.PY2:
self.assertTrue(q.has_key('foo'))
- self.assertTrue('foo' in q)
+ self.assertIn('foo', q)
self.assertListEqual(sorted(list(six.iteritems(q))),
[('foo', 'another'), ('name', 'john')])
@@ -609,8 +609,8 @@ class CookieTests(unittest.TestCase):
"""
c = SimpleCookie()
c['test'] = "An,awkward;value"
- self.assertTrue(";" not in c.output().rstrip(';')) # IE compat
- self.assertTrue("," not in c.output().rstrip(';')) # Safari compat
+ self.assertNotIn(";", c.output().rstrip(';')) # IE compat
+ self.assertNotIn(",", c.output().rstrip(';')) # Safari compat
def test_decode(self):
"""
@@ -636,13 +636,13 @@ class CookieTests(unittest.TestCase):
"""
Test that a single non-standard cookie name doesn't affect all cookies. Ticket #13007.
"""
- self.assertTrue('good_cookie' in parse_cookie('good_cookie=yes;bad:cookie=yes').keys())
+ self.assertIn('good_cookie', parse_cookie('good_cookie=yes;bad:cookie=yes').keys())
def test_repeated_nonstandard_keys(self):
"""
Test that a repeated non-standard name doesn't affect all cookies. Ticket #15852
"""
- self.assertTrue('good_cookie' in parse_cookie('a:=b; a:=c; good_cookie=yes').keys())
+ self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys())
def test_httponly_after_load(self):
"""
diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py
index cee3c220c8..459de45c18 100644
--- a/tests/i18n/test_extraction.py
+++ b/tests/i18n/test_extraction.py
@@ -96,9 +96,9 @@ class ExtractorTests(SimpleTestCase):
parts.append(':%d' % line_number)
needle = ''.join(parts)
if assert_presence:
- return self.assertTrue(needle in po_contents, '"%s" not found in final .po file.' % needle)
+ return self.assertIn(needle, po_contents, '"%s" not found in final .po file.' % needle)
else:
- return self.assertFalse(needle in po_contents, '"%s" shouldn\'t be in final .po file.' % needle)
+ return self.assertNotIn(needle, po_contents, '"%s" shouldn\'t be in final .po file.' % needle)
def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts):
"""
@@ -141,26 +141,26 @@ class BasicExtractorTests(ExtractorTests):
self.assertTrue(os.path.exists(self.PO_FILE))
with io.open(self.PO_FILE, 'r', encoding='utf-8') as fp:
po_contents = fp.read()
- self.assertTrue('#. Translators: This comment should be extracted' in po_contents)
- self.assertTrue('This comment should not be extracted' not in po_contents)
+ self.assertIn('#. Translators: This comment should be extracted', po_contents)
+ self.assertNotIn('This comment should not be extracted', po_contents)
# Comments in templates
- self.assertTrue('#. Translators: Django template comment for translators' in po_contents)
- self.assertTrue("#. Translators: Django comment block for translators\n#. string's meaning unveiled" in po_contents)
+ self.assertIn('#. Translators: Django template comment for translators', po_contents)
+ self.assertIn("#. Translators: Django comment block for translators\n#. string's meaning unveiled", po_contents)
- self.assertTrue('#. Translators: One-line translator comment #1' in po_contents)
- self.assertTrue('#. Translators: Two-line translator comment #1\n#. continued here.' in po_contents)
+ self.assertIn('#. Translators: One-line translator comment #1', po_contents)
+ self.assertIn('#. Translators: Two-line translator comment #1\n#. continued here.', po_contents)
- self.assertTrue('#. Translators: One-line translator comment #2' in po_contents)
- self.assertTrue('#. Translators: Two-line translator comment #2\n#. continued here.' in po_contents)
+ self.assertIn('#. Translators: One-line translator comment #2', po_contents)
+ self.assertIn('#. Translators: Two-line translator comment #2\n#. continued here.', po_contents)
- self.assertTrue('#. Translators: One-line translator comment #3' in po_contents)
- self.assertTrue('#. Translators: Two-line translator comment #3\n#. continued here.' in po_contents)
+ self.assertIn('#. Translators: One-line translator comment #3', po_contents)
+ self.assertIn('#. Translators: Two-line translator comment #3\n#. continued here.', po_contents)
- self.assertTrue('#. Translators: One-line translator comment #4' in po_contents)
- self.assertTrue('#. Translators: Two-line translator comment #4\n#. continued here.' in po_contents)
+ self.assertIn('#. Translators: One-line translator comment #4', po_contents)
+ self.assertIn('#. Translators: Two-line translator comment #4\n#. continued here.', po_contents)
- self.assertTrue('#. Translators: One-line translator comment #5 -- with non ASCII characters: áéíóúö' in po_contents)
- self.assertTrue('#. Translators: Two-line translator comment #5 -- with non ASCII characters: áéíóúö\n#. continued here.' in po_contents)
+ self.assertIn('#. Translators: One-line translator comment #5 -- with non ASCII characters: áéíóúö', po_contents)
+ self.assertIn('#. Translators: Two-line translator comment #5 -- with non ASCII characters: áéíóúö\n#. continued here.', po_contents)
def test_templatize_trans_tag(self):
# ticket #11240
@@ -250,23 +250,23 @@ class BasicExtractorTests(ExtractorTests):
with open(self.PO_FILE, 'r') as fp:
po_contents = force_text(fp.read())
# {% trans %}
- self.assertTrue('msgctxt "Special trans context #1"' in po_contents)
+ self.assertIn('msgctxt "Special trans context #1"', po_contents)
self.assertMsgId("Translatable literal #7a", po_contents)
- self.assertTrue('msgctxt "Special trans context #2"' in po_contents)
+ self.assertIn('msgctxt "Special trans context #2"', po_contents)
self.assertMsgId("Translatable literal #7b", po_contents)
- self.assertTrue('msgctxt "Special trans context #3"' in po_contents)
+ self.assertIn('msgctxt "Special trans context #3"', po_contents)
self.assertMsgId("Translatable literal #7c", po_contents)
# {% blocktrans %}
- self.assertTrue('msgctxt "Special blocktrans context #1"' in po_contents)
+ self.assertIn('msgctxt "Special blocktrans context #1"', po_contents)
self.assertMsgId("Translatable literal #8a", po_contents)
- self.assertTrue('msgctxt "Special blocktrans context #2"' in po_contents)
+ self.assertIn('msgctxt "Special blocktrans context #2"', po_contents)
self.assertMsgId("Translatable literal #8b-singular", po_contents)
- self.assertTrue("Translatable literal #8b-plural" in po_contents)
- self.assertTrue('msgctxt "Special blocktrans context #3"' in po_contents)
+ self.assertIn("Translatable literal #8b-plural", po_contents)
+ self.assertIn('msgctxt "Special blocktrans context #3"', po_contents)
self.assertMsgId("Translatable literal #8c-singular", po_contents)
- self.assertTrue("Translatable literal #8c-plural" in po_contents)
- self.assertTrue('msgctxt "Special blocktrans context #4"' in po_contents)
+ self.assertIn("Translatable literal #8c-plural", po_contents)
+ self.assertIn('msgctxt "Special blocktrans context #4"', po_contents)
self.assertMsgId("Translatable literal #8d %(a)s", po_contents)
def test_context_in_single_quotes(self):
@@ -276,12 +276,12 @@ class BasicExtractorTests(ExtractorTests):
with open(self.PO_FILE, 'r') as fp:
po_contents = force_text(fp.read())
# {% trans %}
- self.assertTrue('msgctxt "Context wrapped in double quotes"' in po_contents)
- self.assertTrue('msgctxt "Context wrapped in single quotes"' in po_contents)
+ self.assertIn('msgctxt "Context wrapped in double quotes"', po_contents)
+ self.assertIn('msgctxt "Context wrapped in single quotes"', po_contents)
# {% blocktrans %}
- self.assertTrue('msgctxt "Special blocktrans context wrapped in double quotes"' in po_contents)
- self.assertTrue('msgctxt "Special blocktrans context wrapped in single quotes"' in po_contents)
+ self.assertIn('msgctxt "Special blocktrans context wrapped in double quotes"', po_contents)
+ self.assertIn('msgctxt "Special blocktrans context wrapped in single quotes"', po_contents)
def test_template_comments(self):
"""Template comment tags on the same line of other constructs (#19552)"""
@@ -312,31 +312,31 @@ class BasicExtractorTests(ExtractorTests):
po_contents = force_text(fp.read())
self.assertMsgId('Translatable literal #9a', po_contents)
- self.assertFalse('ignored comment #1' in po_contents)
+ self.assertNotIn('ignored comment #1', po_contents)
- self.assertFalse('Translators: ignored i18n comment #1' in po_contents)
+ self.assertNotIn('Translators: ignored i18n comment #1', po_contents)
self.assertMsgId("Translatable literal #9b", po_contents)
- self.assertFalse('ignored i18n comment #2' in po_contents)
- self.assertFalse('ignored comment #2' in po_contents)
+ self.assertNotIn('ignored i18n comment #2', po_contents)
+ self.assertNotIn('ignored comment #2', po_contents)
self.assertMsgId('Translatable literal #9c', po_contents)
- self.assertFalse('ignored comment #3' in po_contents)
- self.assertFalse('ignored i18n comment #3' in po_contents)
+ self.assertNotIn('ignored comment #3', po_contents)
+ self.assertNotIn('ignored i18n comment #3', po_contents)
self.assertMsgId('Translatable literal #9d', po_contents)
- self.assertFalse('ignored comment #4' in po_contents)
+ self.assertNotIn('ignored comment #4', po_contents)
self.assertMsgId('Translatable literal #9e', po_contents)
- self.assertFalse('ignored comment #5' in po_contents)
+ self.assertNotIn('ignored comment #5', po_contents)
- self.assertFalse('ignored i18n comment #4' in po_contents)
+ self.assertNotIn('ignored i18n comment #4', po_contents)
self.assertMsgId('Translatable literal #9f', po_contents)
- self.assertTrue('#. Translators: valid i18n comment #5' in po_contents)
+ self.assertIn('#. Translators: valid i18n comment #5', po_contents)
self.assertMsgId('Translatable literal #9g', po_contents)
- self.assertTrue('#. Translators: valid i18n comment #6' in po_contents)
+ self.assertIn('#. Translators: valid i18n comment #6', po_contents)
self.assertMsgId('Translatable literal #9h', po_contents)
- self.assertTrue('#. Translators: valid i18n comment #7' in po_contents)
+ self.assertIn('#. Translators: valid i18n comment #7', po_contents)
self.assertMsgId('Translatable literal #9i', po_contents)
six.assertRegex(self, po_contents, r'#\..+Translators: valid i18n comment #8')
@@ -391,7 +391,7 @@ class IgnoredExtractorTests(ExtractorTests):
out, po_contents = self._run_makemessages(ignore_patterns=[
os.path.join('ignore_dir', '*'),
])
- self.assertTrue("ignoring directory ignore_dir" in out)
+ self.assertIn("ignoring directory ignore_dir", out)
self.assertMsgId('This literal should be included.', po_contents)
self.assertNotMsgId('This should be ignored.', po_contents)
@@ -400,14 +400,14 @@ class IgnoredExtractorTests(ExtractorTests):
'templates/*/ignore.html',
'templates/subdir/*',
])
- self.assertTrue("ignoring directory subdir" in out)
+ self.assertIn("ignoring directory subdir", out)
self.assertNotMsgId('This subdir should be ignored too.', po_contents)
def test_ignore_file_patterns(self):
out, po_contents = self._run_makemessages(ignore_patterns=[
'xxx_*',
])
- self.assertTrue("ignoring file xxx_ignored.html" in out)
+ self.assertIn("ignoring file xxx_ignored.html", out)
self.assertNotMsgId('This should be ignored too.', po_contents)
@override_settings(
@@ -455,7 +455,7 @@ class SymlinkExtractorTests(ExtractorTests):
with open(self.PO_FILE, 'r') as fp:
po_contents = force_text(fp.read())
self.assertMsgId('This literal should be included.', po_contents)
- self.assertTrue('templates_symlinked/test.html' in po_contents)
+ self.assertIn('templates_symlinked/test.html', po_contents)
class CopyPluralFormsExtractorTests(ExtractorTests):
@@ -477,7 +477,7 @@ class CopyPluralFormsExtractorTests(ExtractorTests):
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE, 'r') as fp:
po_contents = force_text(fp.read())
- self.assertTrue('Plural-Forms: nplurals=2; plural=(n != 1)' in po_contents)
+ self.assertIn('Plural-Forms: nplurals=2; plural=(n != 1)', po_contents)
def test_override_plural_forms(self):
"""Ticket #20311."""
diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py
index a6c8b1dab4..9e271b3fa6 100644
--- a/tests/i18n/tests.py
+++ b/tests/i18n/tests.py
@@ -1153,7 +1153,7 @@ class ResolutionOrderI18NTests(TestCase):
def assertUgettext(self, msgid, msgstr):
result = ugettext(msgid)
- self.assertTrue(msgstr in result, ("The string '%s' isn't in the "
+ self.assertIn(msgstr, result, ("The string '%s' isn't in the "
"translation of '%s'; the actual result is '%s'." % (msgstr, msgid, result)))
diff --git a/tests/introspection/tests.py b/tests/introspection/tests.py
index 201d832e2d..d63358dafd 100644
--- a/tests/introspection/tests.py
+++ b/tests/introspection/tests.py
@@ -11,9 +11,9 @@ class IntrospectionTests(TestCase):
def test_table_names(self):
tl = connection.introspection.table_names()
self.assertEqual(tl, sorted(tl))
- self.assertTrue(Reporter._meta.db_table in tl,
+ self.assertIn(Reporter._meta.db_table, tl,
"'%s' isn't in table_list()." % Reporter._meta.db_table)
- self.assertTrue(Article._meta.db_table in tl,
+ self.assertIn(Article._meta.db_table, tl,
"'%s' isn't in table_list()." % Article._meta.db_table)
def test_django_table_names(self):
@@ -60,7 +60,7 @@ class IntrospectionTests(TestCase):
def test_sequence_list(self):
sequences = connection.introspection.sequence_list()
expected = {'table': Reporter._meta.db_table, 'column': 'id'}
- self.assertTrue(expected in sequences,
+ self.assertIn(expected, sequences,
'Reporter sequence not found in sequence_list()')
def test_get_table_description_names(self):
diff --git a/tests/logging_tests/tests.py b/tests/logging_tests/tests.py
index 71368cc9c3..99981e56e1 100644
--- a/tests/logging_tests/tests.py
+++ b/tests/logging_tests/tests.py
@@ -123,12 +123,12 @@ class WarningLoggerTests(TestCase):
def test_warnings_capture(self):
warnings.warn('Foo Deprecated', RemovedInNextVersionWarning)
output = force_text(self.outputs[0].getvalue())
- self.assertTrue('Foo Deprecated' in output)
+ self.assertIn('Foo Deprecated', output)
def test_warnings_capture_debug_false(self):
warnings.warn('Foo Deprecated', RemovedInNextVersionWarning)
output = force_text(self.outputs[0].getvalue())
- self.assertFalse('Foo Deprecated' in output)
+ self.assertNotIn('Foo Deprecated', output)
@override_settings(DEBUG=True)
def test_error_filter_still_raises(self):
@@ -263,8 +263,8 @@ class AdminEmailHandlerTest(TestCase):
self.logger.error(message)
self.assertEqual(len(mail.outbox), 1)
- self.assertFalse('\n' in mail.outbox[0].subject)
- self.assertFalse('\r' in mail.outbox[0].subject)
+ self.assertNotIn('\n', mail.outbox[0].subject)
+ self.assertNotIn('\r', mail.outbox[0].subject)
self.assertEqual(mail.outbox[0].subject, expected_subject)
@override_settings(
diff --git a/tests/m2m_regress/tests.py b/tests/m2m_regress/tests.py
index fd92a0b634..e795e06594 100644
--- a/tests/m2m_regress/tests.py
+++ b/tests/m2m_regress/tests.py
@@ -85,12 +85,12 @@ class M2MRegressionTests(TestCase):
t2 = Tag.objects.create()
# Get same manager twice in a row:
- self.assertTrue(t1.entry_set.__class__ is t1.entry_set.__class__)
- self.assertTrue(e1.topics.__class__ is e1.topics.__class__)
+ self.assertIs(t1.entry_set.__class__, t1.entry_set.__class__)
+ self.assertIs(e1.topics.__class__, e1.topics.__class__)
# Get same manager for different instances
- self.assertTrue(e1.topics.__class__ is e2.topics.__class__)
- self.assertTrue(t1.entry_set.__class__ is t2.entry_set.__class__)
+ self.assertIs(e1.topics.__class__, e2.topics.__class__)
+ self.assertIs(t1.entry_set.__class__, t2.entry_set.__class__)
def test_m2m_abstract_split(self):
# Regression for #19236 - an abstract class with a 'split' method
diff --git a/tests/mail/tests.py b/tests/mail/tests.py
index e510cf88f6..a6184bd767 100644
--- a/tests/mail/tests.py
+++ b/tests/mail/tests.py
@@ -346,31 +346,31 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
# Regression for #13433 - Make sure that EmailMessage doesn't mangle
# 'From ' in message body.
email = EmailMessage('Subject', 'From the future', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
- self.assertFalse(b'>From the future' in email.message().as_bytes())
+ self.assertNotIn(b'>From the future', email.message().as_bytes())
def test_dont_base64_encode(self):
# Ticket #3472
# Shouldn't use Base64 encoding at all
msg = EmailMessage('Subject', 'UTF-8 encoded body', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
- self.assertFalse(b'Content-Transfer-Encoding: base64' in msg.message().as_bytes())
+ self.assertNotIn(b'Content-Transfer-Encoding: base64', msg.message().as_bytes())
# Ticket #11212
# Shouldn't use quoted printable, should detect it can represent content with 7 bit data
msg = EmailMessage('Subject', 'Body with only ASCII characters.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
s = msg.message().as_bytes()
- self.assertFalse(b'Content-Transfer-Encoding: quoted-printable' in s)
- self.assertTrue(b'Content-Transfer-Encoding: 7bit' in s)
+ self.assertNotIn(b'Content-Transfer-Encoding: quoted-printable', s)
+ self.assertIn(b'Content-Transfer-Encoding: 7bit', s)
# Shouldn't use quoted printable, should detect it can represent content with 8 bit data
msg = EmailMessage('Subject', 'Body with latin characters: àáä.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
s = msg.message().as_bytes()
- self.assertFalse(b'Content-Transfer-Encoding: quoted-printable' in s)
- self.assertTrue(b'Content-Transfer-Encoding: 8bit' in s)
+ self.assertNotIn(b'Content-Transfer-Encoding: quoted-printable', s)
+ self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
msg = EmailMessage('Subject', 'Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
s = msg.message().as_bytes()
- self.assertFalse(b'Content-Transfer-Encoding: quoted-printable' in s)
- self.assertTrue(b'Content-Transfer-Encoding: 8bit' in s)
+ self.assertNotIn(b'Content-Transfer-Encoding: quoted-printable', s)
+ self.assertIn(b'Content-Transfer-Encoding: 8bit', s)
def test_dont_base64_encode_message_rfc822(self):
# Ticket #18967
@@ -387,7 +387,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
parent_s = parent_msg.message().as_string()
# Verify that the child message header is not base64 encoded
- self.assertTrue(str('Child Subject') in parent_s)
+ self.assertIn(str('Child Subject'), parent_s)
# Feature test: try attaching email.Message object directly to the mail.
parent_msg = EmailMessage('Parent Subject', 'Some parent body', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
@@ -395,7 +395,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
parent_s = parent_msg.message().as_string()
# Verify that the child message header is not base64 encoded
- self.assertTrue(str('Child Subject') in parent_s)
+ self.assertIn(str('Child Subject'), parent_s)
# Feature test: try attaching Django's EmailMessage object directly to the mail.
parent_msg = EmailMessage('Parent Subject', 'Some parent body', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'})
@@ -403,7 +403,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
parent_s = parent_msg.message().as_string()
# Verify that the child message header is not base64 encoded
- self.assertTrue(str('Child Subject') in parent_s)
+ self.assertIn(str('Child Subject'), parent_s)
class PythonGlobalState(SimpleTestCase):
@@ -415,19 +415,19 @@ class PythonGlobalState(SimpleTestCase):
def test_utf8(self):
txt = MIMEText('UTF-8 encoded body', 'plain', 'utf-8')
- self.assertTrue('Content-Transfer-Encoding: base64' in txt.as_string())
+ self.assertIn('Content-Transfer-Encoding: base64', txt.as_string())
def test_7bit(self):
txt = MIMEText('Body with only ASCII characters.', 'plain', 'utf-8')
- self.assertTrue('Content-Transfer-Encoding: base64' in txt.as_string())
+ self.assertIn('Content-Transfer-Encoding: base64', txt.as_string())
def test_8bit_latin(self):
txt = MIMEText('Body with latin characters: àáä.', 'plain', 'utf-8')
- self.assertTrue(str('Content-Transfer-Encoding: base64') in txt.as_string())
+ self.assertIn(str('Content-Transfer-Encoding: base64'), txt.as_string())
def test_8bit_non_latin(self):
txt = MIMEText('Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.', 'plain', 'utf-8')
- self.assertTrue(str('Content-Transfer-Encoding: base64') in txt.as_string())
+ self.assertIn(str('Content-Transfer-Encoding: base64'), txt.as_string())
class BaseEmailBackendTests(HeadersCheckMixin, object):
diff --git a/tests/many_to_one/tests.py b/tests/many_to_one/tests.py
index f5949bd22e..0195e5d2d8 100644
--- a/tests/many_to_one/tests.py
+++ b/tests/many_to_one/tests.py
@@ -417,10 +417,10 @@ class ManyToOneTests(TestCase):
r2 = Reporter.objects.create(first_name='John')
# Same twice
- self.assertTrue(r1.article_set.__class__ is r1.article_set.__class__)
+ self.assertIs(r1.article_set.__class__, r1.article_set.__class__)
# Same as each other
- self.assertTrue(r1.article_set.__class__ is r2.article_set.__class__)
+ self.assertIs(r1.article_set.__class__, r2.article_set.__class__)
def test_create_relation_with_ugettext_lazy(self):
reporter = Reporter.objects.create(first_name='John',
@@ -456,28 +456,28 @@ class ManyToOneTests(TestCase):
p = c.parent
# Accessing the related object again returns the exactly same object.
- self.assertTrue(c.parent is p)
+ self.assertIs(c.parent, p)
# But if we kill the cache, we get a new object.
del c._parent_cache
- self.assertFalse(c.parent is p)
+ self.assertIsNot(c.parent, p)
# Assigning a new object results in that object getting cached immediately.
p2 = Parent.objects.create(name="Parent 2")
c.parent = p2
- self.assertTrue(c.parent is p2)
+ self.assertIs(c.parent, p2)
# Assigning None succeeds if field is null=True.
p.bestchild = None
- self.assertTrue(p.bestchild is None)
+ self.assertIsNone(p.bestchild)
# bestchild should still be None after saving.
p.save()
- self.assertTrue(p.bestchild is None)
+ self.assertIsNone(p.bestchild)
# bestchild should still be None after fetching the object again.
p = Parent.objects.get(name="Parent")
- self.assertTrue(p.bestchild is None)
+ self.assertIsNone(p.bestchild)
# Assigning None fails: Child.parent is null=False.
self.assertRaises(ValueError, setattr, c, "parent", None)
@@ -493,7 +493,7 @@ class ManyToOneTests(TestCase):
# Creation using keyword argument should cache the related object.
p = Parent.objects.get(name="Parent")
c = Child(parent=p)
- self.assertTrue(c.parent is p)
+ self.assertIs(c.parent, p)
# Creation using keyword argument and unsaved related instance (#8070).
p = Parent()
@@ -511,7 +511,7 @@ class ManyToOneTests(TestCase):
# related object to be fetched.
p = Parent.objects.get(name="Parent")
c = Child(parent_id=p.id)
- self.assertFalse(c.parent is p)
+ self.assertIsNot(c.parent, p)
self.assertEqual(c.parent, p)
def test_multiple_foreignkeys(self):
diff --git a/tests/middleware/test_security.py b/tests/middleware/test_security.py
index 93cae6ced6..66cbf5f7b2 100644
--- a/tests/middleware/test_security.py
+++ b/tests/middleware/test_security.py
@@ -152,7 +152,7 @@ class SecurityMiddlewareTest(TestCase):
With BROWSER_XSS_FILTER set to False, the middleware does not add an
"x-xss-protection" header to the response.
"""
- self.assertFalse("x-xss-protection" in self.process_response())
+ self.assertNotIn("x-xss-protection", self.process_response())
@override_settings(SECURE_SSL_REDIRECT=True)
def test_ssl_redirect_on(self):
diff --git a/tests/middleware/tests.py b/tests/middleware/tests.py
index 556e07f72c..ec7f7633ba 100644
--- a/tests/middleware/tests.py
+++ b/tests/middleware/tests.py
@@ -162,7 +162,7 @@ class CommonMiddlewareTest(TestCase):
request = self._get_request('customurlconf/slash')
request.urlconf = 'middleware.extra_urls'
r = CommonMiddleware().process_request(request)
- self.assertFalse(r is None,
+ self.assertIsNotNone(r,
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, 'http://testserver/customurlconf/slash/')
@@ -198,7 +198,7 @@ class CommonMiddlewareTest(TestCase):
request = self._get_request('customurlconf/needsquoting#')
request.urlconf = 'middleware.extra_urls'
r = CommonMiddleware().process_request(request)
- self.assertFalse(r is None,
+ self.assertIsNotNone(r,
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
self.assertEqual(r.status_code, 301)
self.assertEqual(
@@ -318,24 +318,24 @@ class ConditionalGetMiddlewareTest(TestCase):
# Tests for the Date header
def test_date_header_added(self):
- self.assertFalse('Date' in self.resp)
+ self.assertNotIn('Date', self.resp)
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
- self.assertTrue('Date' in self.resp)
+ self.assertIn('Date', self.resp)
# Tests for the Content-Length header
def test_content_length_header_added(self):
content_length = len(self.resp.content)
- self.assertFalse('Content-Length' in self.resp)
+ self.assertNotIn('Content-Length', self.resp)
self.resp = ConditionalGetMiddleware().process_response(self.req, self.resp)
- self.assertTrue('Content-Length' in self.resp)
+ self.assertIn('Content-Length', self.resp)
self.assertEqual(int(self.resp['Content-Length']), content_length)
def test_content_length_header_not_added(self):
resp = StreamingHttpResponse('content')
- self.assertFalse('Content-Length' in resp)
+ self.assertNotIn('Content-Length', resp)
resp = ConditionalGetMiddleware().process_response(self.req, resp)
- self.assertFalse('Content-Length' in resp)
+ self.assertNotIn('Content-Length', resp)
def test_content_length_header_not_changed(self):
bad_content_length = len(self.resp.content) + 10
diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py
index 33236c320f..bd6763e4db 100644
--- a/tests/migrations/test_autodetector.py
+++ b/tests/migrations/test_autodetector.py
@@ -590,8 +590,8 @@ class AutodetectorTests(TestCase):
# Right number/type of migrations?
self.assertNumberMigrations(changes, 'eggs', 1)
self.assertOperationTypes(changes, 'eggs', 0, ["CreateModel", "CreateModel", "AlterUniqueTogether"])
- self.assertFalse("unique_together" in changes['eggs'][0].operations[0].options)
- self.assertFalse("unique_together" in changes['eggs'][0].operations[1].options)
+ self.assertNotIn("unique_together", changes['eggs'][0].operations[0].options)
+ self.assertNotIn("unique_together", changes['eggs'][0].operations[1].options)
# Right dependencies?
self.assertEqual(changes['eggs'][0].dependencies, [])
diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py
index 1091603d1b..f4e3878d17 100644
--- a/tests/migrations/test_commands.py
+++ b/tests/migrations/test_commands.py
@@ -196,19 +196,19 @@ class MakeMigrationsTests(MigrationTestBase):
with codecs.open(initial_file, 'r', encoding='utf-8') as fp:
content = fp.read()
- self.assertTrue('# -*- coding: utf-8 -*-' in content)
- self.assertTrue('migrations.CreateModel' in content)
+ self.assertIn('# -*- coding: utf-8 -*-', content)
+ self.assertIn('migrations.CreateModel', content)
if six.PY3:
- self.assertTrue('úñí©óðé µóðéø' in content) # Meta.verbose_name
- self.assertTrue('úñí©óðé µóðéøß' in content) # Meta.verbose_name_plural
- self.assertTrue('ÚÑÍ¢ÓÐÉ' in content) # title.verbose_name
- self.assertTrue('“Ðjáñgó”' in content) # title.default
+ self.assertIn('úñí©óðé µóðéø', content) # Meta.verbose_name
+ self.assertIn('úñí©óðé µóðéøß', content) # Meta.verbose_name_plural
+ self.assertIn('ÚÑÍ¢ÓÐÉ', content) # title.verbose_name
+ self.assertIn('“Ðjáñgó”', content) # title.default
else:
- self.assertTrue('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8' in content) # Meta.verbose_name
- self.assertTrue('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8\\xdf' in content) # Meta.verbose_name_plural
- self.assertTrue('\\xda\\xd1\\xcd\\xa2\\xd3\\xd0\\xc9' in content) # title.verbose_name
- self.assertTrue('\\u201c\\xd0j\\xe1\\xf1g\\xf3\\u201d' in content) # title.default
+ self.assertIn('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8', content) # Meta.verbose_name
+ self.assertIn('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8\\xdf', content) # Meta.verbose_name_plural
+ self.assertIn('\\xda\\xd1\\xcd\\xa2\\xd3\\xd0\\xc9', content) # title.verbose_name
+ self.assertIn('\\u201c\\xd0j\\xe1\\xf1g\\xf3\\u201d', content) # title.default
def test_failing_migration(self):
#21280 - If a migration fails to serialize, it shouldn't generate an empty file.
@@ -274,7 +274,7 @@ class MakeMigrationsTests(MigrationTestBase):
with codecs.open(initial_file, 'r', encoding='utf-8') as fp:
content = fp.read()
- self.assertTrue('# -*- coding: utf-8 -*-' in content)
+ self.assertIn('# -*- coding: utf-8 -*-', content)
# Remove all whitespace to check for empty dependencies and operations
content = content.replace(' ', '')
@@ -529,7 +529,7 @@ class MakeMigrationsTests(MigrationTestBase):
self.assertTrue(os.path.exists(migration_file))
with codecs.open(migration_file, "r", encoding="utf-8") as fp:
content = fp.read()
- self.assertTrue("# -*- coding: utf-8 -*-" in content)
+ self.assertIn("# -*- coding: utf-8 -*-", content)
content = content.replace(" ", "")
return content
diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py
index 793538c791..650e6dc0f9 100644
--- a/tests/model_fields/tests.py
+++ b/tests/model_fields/tests.py
@@ -223,8 +223,8 @@ class BooleanFieldTests(unittest.TestCase):
self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])
def _test_to_python(self, f):
- self.assertTrue(f.to_python(1) is True)
- self.assertTrue(f.to_python(0) is False)
+ self.assertIs(f.to_python(1), True)
+ self.assertIs(f.to_python(0), False)
def test_booleanfield_get_db_prep_lookup(self):
self._test_get_db_prep_lookup(models.BooleanField())
diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py
index e704c62d2e..8ebc46625c 100644
--- a/tests/model_forms/tests.py
+++ b/tests/model_forms/tests.py
@@ -258,7 +258,7 @@ class ModelFormBaseTest(TestCase):
except FieldError as e:
# Make sure the exception contains some reference to the
# field responsible for the problem.
- self.assertTrue('no-field' in e.args[0])
+ self.assertIn('no-field', e.args[0])
else:
self.fail('Invalid "no-field" field not caught')
@@ -1464,8 +1464,8 @@ class ModelChoiceFieldTests(TestCase):
field1 = form1.fields['category']
# To allow the widget to change the queryset of field1.widget.choices correctly,
# without affecting other forms, the following must hold:
- self.assertTrue(field1 is not ModelChoiceForm.base_fields['category'])
- self.assertTrue(field1.widget.choices.field is field1)
+ self.assertIsNot(field1, ModelChoiceForm.base_fields['category'])
+ self.assertIs(field1.widget.choices.field, field1)
def test_modelchoicefield_22745(self):
"""
@@ -1764,14 +1764,14 @@ class FileAndImageFieldTests(TestCase):
fields = '__all__'
form = DocumentForm()
- self.assertTrue('name="myfile"' in six.text_type(form))
- self.assertTrue('myfile-clear' not in six.text_type(form))
+ self.assertIn('name="myfile"', six.text_type(form))
+ self.assertNotIn('myfile-clear', six.text_type(form))
form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')})
self.assertTrue(form.is_valid())
doc = form.save(commit=False)
self.assertEqual(doc.myfile.name, 'something.txt')
form = DocumentForm(instance=doc)
- self.assertTrue('myfile-clear' in six.text_type(form))
+ self.assertIn('myfile-clear', six.text_type(form))
form = DocumentForm(instance=doc, data={'myfile-clear': 'true'})
doc = form.save(commit=False)
self.assertEqual(bool(doc.myfile), False)
@@ -1797,8 +1797,8 @@ class FileAndImageFieldTests(TestCase):
self.assertEqual(form.errors['myfile'],
['Please either submit a file or check the clear checkbox, not both.'])
rendered = six.text_type(form)
- self.assertTrue('something.txt' in rendered)
- self.assertTrue('myfile-clear' in rendered)
+ self.assertIn('something.txt', rendered)
+ self.assertIn('myfile-clear', rendered)
def test_file_field_data(self):
# Test conditions when files is either not given or empty.
@@ -2421,7 +2421,7 @@ class FormFieldCallbackTests(TestCase):
fields = "__all__"
Form = modelform_factory(Person, form=BaseForm)
- self.assertTrue(Form.base_fields['name'].widget is widget)
+ self.assertIs(Form.base_fields['name'].widget, widget)
def test_factory_with_widget_argument(self):
""" Regression for #15315: modelform_factory should accept widgets
diff --git a/tests/model_formsets/tests.py b/tests/model_formsets/tests.py
index 58d8bcc9ab..80c5c6fa09 100644
--- a/tests/model_formsets/tests.py
+++ b/tests/model_formsets/tests.py
@@ -449,11 +449,11 @@ class ModelFormsetTest(TestCase):
PostFormSet = modelformset_factory(Post, form=PostForm1)
formset = PostFormSet()
- self.assertFalse("subtitle" in formset.forms[0].fields)
+ self.assertNotIn("subtitle", formset.forms[0].fields)
PostFormSet = modelformset_factory(Post, form=PostForm2)
formset = PostFormSet()
- self.assertFalse("subtitle" in formset.forms[0].fields)
+ self.assertNotIn("subtitle", formset.forms[0].fields)
def test_custom_queryset_init(self):
"""
diff --git a/tests/model_formsets_regress/tests.py b/tests/model_formsets_regress/tests.py
index f0ff06f875..761d337e49 100644
--- a/tests/model_formsets_regress/tests.py
+++ b/tests/model_formsets_regress/tests.py
@@ -203,7 +203,7 @@ class InlineFormsetTests(TestCase):
UserFormSet = modelformset_factory(User, fields=())
formset = UserFormSet()
for form in formset.forms:
- self.assertTrue('id' in form.fields)
+ self.assertIn('id', form.fields)
self.assertEqual(len(form.fields), 1)
def test_save_as_new_with_new_inlines(self):
@@ -247,7 +247,7 @@ class InlineFormsetTests(TestCase):
formset = FormSet(instance=user, initial=[{'data': 41}, {'data': 42}])
self.assertEqual(formset.forms[0].initial['data'], 7)
self.assertEqual(formset.extra_forms[0].initial['data'], 41)
- self.assertTrue('value="42"' in formset.extra_forms[1].as_p())
+ self.assertIn('value="42"', formset.extra_forms[1].as_p())
class FormsetTests(TestCase):
@@ -282,7 +282,7 @@ class FormsetTests(TestCase):
formset = Formset(initial=[{'username': 'apollo11'}, {'username': 'apollo12'}])
self.assertEqual(formset.forms[0].initial['username'], "bibi")
self.assertEqual(formset.extra_forms[0].initial['username'], "apollo11")
- self.assertTrue('value="apollo12"' in formset.extra_forms[1].as_p())
+ self.assertIn('value="apollo12"', formset.extra_forms[1].as_p())
def test_extraneous_query_is_not_run(self):
Formset = modelformset_factory(Network, fields="__all__")
diff --git a/tests/model_meta/test.py b/tests/model_meta/test.py
index 8fd0a6bb33..cbc348eae3 100644
--- a/tests/model_meta/test.py
+++ b/tests/model_meta/test.py
@@ -609,13 +609,13 @@ class RelatedM2MTests(OptionsBaseTests):
def test_related_m2m_asymmetrical(self):
m2m = Person._meta.many_to_many
- self.assertTrue('following_base' in [f.attname for f in m2m])
+ self.assertIn('following_base', [f.attname for f in m2m])
related_m2m = Person._meta.get_all_related_many_to_many_objects()
- self.assertTrue('followers_base' in [o.field.related_query_name() for o in related_m2m])
+ self.assertIn('followers_base', [o.field.related_query_name() for o in related_m2m])
def test_related_m2m_symmetrical(self):
m2m = Person._meta.many_to_many
- self.assertTrue('friends_base' in [f.attname for f in m2m])
+ self.assertIn('friends_base', [f.attname for f in m2m])
related_m2m = Person._meta.get_all_related_many_to_many_objects()
self.assertIn('friends_inherited_rel_+', [o.field.related_query_name() for o in related_m2m])
diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py
index 88da4072ae..f230311eed 100644
--- a/tests/multiple_database/tests.py
+++ b/tests/multiple_database/tests.py
@@ -1485,7 +1485,7 @@ class AuthTestCase(TestCase):
new_io = StringIO()
management.call_command('dumpdata', 'auth', format='json', database='other', stdout=new_io)
command_output = new_io.getvalue().strip()
- self.assertTrue('"email": "alice@example.com"' in command_output)
+ self.assertIn('"email": "alice@example.com"', command_output)
class AntiPetRouter(object):
diff --git a/tests/null_fk/tests.py b/tests/null_fk/tests.py
index 696c7a3035..26eae6491e 100644
--- a/tests/null_fk/tests.py
+++ b/tests/null_fk/tests.py
@@ -35,7 +35,7 @@ class NullFkTests(TestCase):
)
# Regression test for #7530, #7716.
- self.assertTrue(Comment.objects.select_related('post').filter(post__isnull=True)[0].post is None)
+ self.assertIsNone(Comment.objects.select_related('post').filter(post__isnull=True)[0].post)
self.assertQuerysetEqual(
Comment.objects.select_related('post__forum__system_info__system_details'),
diff --git a/tests/null_fk_ordering/tests.py b/tests/null_fk_ordering/tests.py
index ebbd089c36..2fe48f0b19 100644
--- a/tests/null_fk_ordering/tests.py
+++ b/tests/null_fk_ordering/tests.py
@@ -22,7 +22,7 @@ class NullFkOrderingTests(TestCase):
# We can't compare results directly (since different databases sort NULLs to
# different ends of the ordering), but we can check that all results are
# returned.
- self.assertTrue(len(list(Article.objects.all())) == 3)
+ self.assertEqual(len(list(Article.objects.all())), 3)
s = SystemInfo.objects.create(system_name='System Info')
f = Forum.objects.create(system_info=s, forum_name='First forum')
@@ -39,4 +39,4 @@ class NullFkOrderingTests(TestCase):
# everything else, some sort them afterwards. So we extract the ordered list
# and check the length. Before the fix, this list was too short (some values
# were omitted).
- self.assertTrue(len(list(Comment.objects.all())) == 4)
+ self.assertEqual(len(list(Comment.objects.all())), 4)
diff --git a/tests/one_to_one/tests.py b/tests/one_to_one/tests.py
index d9eef0b133..f59749f8cf 100644
--- a/tests/one_to_one/tests.py
+++ b/tests/one_to_one/tests.py
@@ -190,23 +190,23 @@ class OneToOneTests(TestCase):
r = p.restaurant
# Accessing the related object again returns the exactly same object
- self.assertTrue(p.restaurant is r)
+ self.assertIs(p.restaurant, r)
# But if we kill the cache, we get a new object
del p._restaurant_cache
- self.assertFalse(p.restaurant is r)
+ self.assertIsNot(p.restaurant, r)
# Reassigning the Restaurant object results in an immediate cache update
# We can't use a new Restaurant because that'll violate one-to-one, but
# with a new *instance* the is test below will fail if #6886 regresses.
r2 = Restaurant.objects.get(pk=r.pk)
p.restaurant = r2
- self.assertTrue(p.restaurant is r2)
+ self.assertIs(p.restaurant, r2)
# Assigning None succeeds if field is null=True.
ug_bar = UndergroundBar.objects.create(place=p, serves_cocktails=False)
ug_bar.place = None
- self.assertTrue(ug_bar.place is None)
+ self.assertIsNone(ug_bar.place)
# Assigning None fails: Place.restaurant is null=False
self.assertRaises(ValueError, setattr, p, 'restaurant', None)
@@ -217,13 +217,13 @@ class OneToOneTests(TestCase):
# Creation using keyword argument should cache the related object.
p = Place.objects.get(name="Demon Dogs")
r = Restaurant(place=p)
- self.assertTrue(r.place is p)
+ self.assertIs(r.place, p)
# Creation using attname keyword argument and an id will cause the related
# object to be fetched.
p = Place.objects.get(name="Demon Dogs")
r = Restaurant(place_id=p.id)
- self.assertFalse(r.place is p)
+ self.assertIsNot(r.place, p)
self.assertEqual(r.place, p)
def test_filter_one_to_one_relations(self):
diff --git a/tests/pagination/tests.py b/tests/pagination/tests.py
index c2ad54c5ad..7f405cffaa 100644
--- a/tests/pagination/tests.py
+++ b/tests/pagination/tests.py
@@ -213,8 +213,8 @@ class PaginationTests(unittest.TestCase):
eleven = 'abcdefghijk'
page2 = Paginator(eleven, per_page=5, orphans=1).page(2)
self.assertEqual(len(page2), 6)
- self.assertTrue('k' in page2)
- self.assertFalse('a' in page2)
+ self.assertIn('k', page2)
+ self.assertNotIn('a', page2)
self.assertEqual(''.join(page2), 'fghijk')
self.assertEqual(''.join(reversed(page2)), 'kjihgf')
diff --git a/tests/prefetch_related/tests.py b/tests/prefetch_related/tests.py
index decadd83a2..5fe37d5966 100644
--- a/tests/prefetch_related/tests.py
+++ b/tests/prefetch_related/tests.py
@@ -113,7 +113,7 @@ class PrefetchRelatedTests(TestCase):
70679243d1786e03557c28929f9762a119e3ac14.
"""
qs = Book.objects.prefetch_related('first_time_authors')
- self.assertTrue(qs[0] in qs)
+ self.assertIn(qs[0], qs)
def test_clear(self):
"""
@@ -211,15 +211,15 @@ class PrefetchRelatedTests(TestCase):
with self.assertRaises(AttributeError) as cm:
list(qs)
- self.assertTrue('prefetch_related' in str(cm.exception))
+ self.assertIn('prefetch_related', str(cm.exception))
def test_invalid_final_lookup(self):
qs = Book.objects.prefetch_related('authors__name')
with self.assertRaises(ValueError) as cm:
list(qs)
- self.assertTrue('prefetch_related' in str(cm.exception))
- self.assertTrue("name" in str(cm.exception))
+ self.assertIn('prefetch_related', str(cm.exception))
+ self.assertIn("name", str(cm.exception))
class CustomPrefetchTests(TestCase):
diff --git a/tests/proxy_models/tests.py b/tests/proxy_models/tests.py
index 7cb5bdf441..cb4ea3c9eb 100644
--- a/tests/proxy_models/tests.py
+++ b/tests/proxy_models/tests.py
@@ -272,7 +272,7 @@ class ProxyModelTests(TestCase):
def test_content_type(self):
ctype = ContentType.objects.get_for_model
- self.assertTrue(ctype(Person) is ctype(OtherPerson))
+ self.assertIs(ctype(Person), ctype(OtherPerson))
def test_user_userproxy_userproxyproxy(self):
User.objects.create(name='Bruce')
@@ -396,9 +396,9 @@ class ProxyModelAdminTests(TestCase):
with self.assertNumQueries(7):
collector = admin.utils.NestedObjects('default')
collector.collect(ProxyTrackerUser.objects.all())
- self.assertTrue(tracker_user in collector.edges.get(None, ()))
- self.assertTrue(base_user in collector.edges.get(None, ()))
- self.assertTrue(issue in collector.edges.get(tracker_user, ()))
+ self.assertIn(tracker_user, collector.edges.get(None, ()))
+ self.assertIn(base_user, collector.edges.get(None, ()))
+ self.assertIn(issue, collector.edges.get(tracker_user, ()))
def test_delete_str_in_model_admin(self):
"""
diff --git a/tests/queries/tests.py b/tests/queries/tests.py
index 8ec3fd5945..5ee7c85005 100644
--- a/tests/queries/tests.py
+++ b/tests/queries/tests.py
@@ -127,7 +127,7 @@ class Queries1Tests(BaseQuerysetTest):
def test_ticket2306(self):
# Checking that no join types are "left outer" joins.
query = Item.objects.filter(tags=self.t2).query
- self.assertTrue(query.LOUTER not in [x[2] for x in query.alias_map.values()])
+ self.assertNotIn(query.LOUTER, [x[2] for x in query.alias_map.values()])
self.assertQuerysetEqual(
Item.objects.filter(Q(tags=self.t1)).order_by('name'),
@@ -335,7 +335,7 @@ class Queries1Tests(BaseQuerysetTest):
# Excluding from a relation that cannot be NULL should not use outer joins.
query = Item.objects.exclude(creator__in=[self.a1, self.a2]).query
- self.assertTrue(query.LOUTER not in [x[2] for x in query.alias_map.values()])
+ self.assertNotIn(query.LOUTER, [x[2] for x in query.alias_map.values()])
# Similarly, when one of the joins cannot possibly, ever, involve NULL
# values (Author -> ExtraInfo, in the following), it should never be
@@ -500,7 +500,7 @@ class Queries1Tests(BaseQuerysetTest):
# actually allow both "foo" and "foo_id".
# The *_id version is returned by default.
- self.assertTrue('note_id' in ExtraInfo.objects.values()[0])
+ self.assertIn('note_id', ExtraInfo.objects.values()[0])
# You can also pass it in explicitly.
self.assertValueQuerysetEqual(
@@ -777,14 +777,14 @@ class Queries1Tests(BaseQuerysetTest):
self.assertQuerysetEqual(qs, ['
', ''])
# The subquery result cache should not be populated
- self.assertTrue(subq._result_cache is None)
+ self.assertIsNone(subq._result_cache)
subq = Author.objects.filter(num__lt=3000)
qs = Author.objects.exclude(pk__in=subq)
self.assertQuerysetEqual(qs, ['', ''])
# The subquery result cache should not be populated
- self.assertTrue(subq._result_cache is None)
+ self.assertIsNone(subq._result_cache)
subq = Author.objects.filter(num__lt=3000)
self.assertQuerysetEqual(
@@ -793,7 +793,7 @@ class Queries1Tests(BaseQuerysetTest):
)
# The subquery result cache should not be populated
- self.assertTrue(subq._result_cache is None)
+ self.assertIsNone(subq._result_cache)
def test_ticket7076(self):
# Excluding shouldn't eliminate NULL entries.
@@ -911,7 +911,7 @@ class Queries1Tests(BaseQuerysetTest):
q = Tag.objects.filter(parent__isnull=True)
self.assertQuerysetEqual(q, [''])
- self.assertTrue('JOIN' not in str(q.query))
+ self.assertNotIn('JOIN', str(q.query))
q = Tag.objects.filter(parent__isnull=False)
@@ -919,18 +919,18 @@ class Queries1Tests(BaseQuerysetTest):
q,
['', '', '', ''],
)
- self.assertTrue('JOIN' not in str(q.query))
+ self.assertNotIn('JOIN', str(q.query))
q = Tag.objects.exclude(parent__isnull=True)
self.assertQuerysetEqual(
q,
['', '', '', ''],
)
- self.assertTrue('JOIN' not in str(q.query))
+ self.assertNotIn('JOIN', str(q.query))
q = Tag.objects.exclude(parent__isnull=False)
self.assertQuerysetEqual(q, [''])
- self.assertTrue('JOIN' not in str(q.query))
+ self.assertNotIn('JOIN', str(q.query))
q = Tag.objects.exclude(parent__parent__isnull=False)
@@ -938,8 +938,8 @@ class Queries1Tests(BaseQuerysetTest):
q,
['', '', ''],
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 1)
- self.assertTrue('INNER JOIN' not in str(q.query))
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1)
+ self.assertNotIn('INNER JOIN', str(q.query))
def test_ticket_10790_2(self):
# Querying across several tables should strip only the last outer join,
@@ -950,8 +950,8 @@ class Queries1Tests(BaseQuerysetTest):
q,
['', ''],
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
- self.assertTrue(str(q.query).count('INNER JOIN') == 1)
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
+ self.assertEqual(str(q.query).count('INNER JOIN'), 1)
# Querying without isnull should not convert anything to left outer join.
q = Tag.objects.filter(parent__parent=self.t1)
@@ -959,22 +959,22 @@ class Queries1Tests(BaseQuerysetTest):
q,
['', ''],
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
- self.assertTrue(str(q.query).count('INNER JOIN') == 1)
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
+ self.assertEqual(str(q.query).count('INNER JOIN'), 1)
def test_ticket_10790_3(self):
# Querying via indirect fields should populate the left outer join
q = NamedCategory.objects.filter(tag__isnull=True)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 1)
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1)
# join to dumbcategory ptr_id
- self.assertTrue(str(q.query).count('INNER JOIN') == 1)
+ self.assertEqual(str(q.query).count('INNER JOIN'), 1)
self.assertQuerysetEqual(q, [])
# Querying across several tables should strip only the last join, while
# preserving the preceding left outer joins.
q = NamedCategory.objects.filter(tag__parent__isnull=True)
- self.assertTrue(str(q.query).count('INNER JOIN') == 1)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 1)
+ self.assertEqual(str(q.query).count('INNER JOIN'), 1)
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1)
self.assertQuerysetEqual(q, [''])
def test_ticket_10790_4(self):
@@ -984,16 +984,16 @@ class Queries1Tests(BaseQuerysetTest):
q,
['', ''],
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 2)
- self.assertTrue('INNER JOIN' not in str(q.query))
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 2)
+ self.assertNotIn('INNER JOIN', str(q.query))
q = Author.objects.filter(item__tags__parent__isnull=True)
self.assertQuerysetEqual(
q,
['', '', '', ''],
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 3)
- self.assertTrue('INNER JOIN' not in str(q.query))
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 3)
+ self.assertNotIn('INNER JOIN', str(q.query))
def test_ticket_10790_5(self):
# Querying with isnull=False across m2m field should not create outer joins
@@ -1002,24 +1002,24 @@ class Queries1Tests(BaseQuerysetTest):
q,
['', '', '', '', '']
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
- self.assertTrue(str(q.query).count('INNER JOIN') == 2)
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
+ self.assertEqual(str(q.query).count('INNER JOIN'), 2)
q = Author.objects.filter(item__tags__parent__isnull=False)
self.assertQuerysetEqual(
q,
['', '', '']
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
- self.assertTrue(str(q.query).count('INNER JOIN') == 3)
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
+ self.assertEqual(str(q.query).count('INNER JOIN'), 3)
q = Author.objects.filter(item__tags__parent__parent__isnull=False)
self.assertQuerysetEqual(
q,
['']
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
- self.assertTrue(str(q.query).count('INNER JOIN') == 4)
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
+ self.assertEqual(str(q.query).count('INNER JOIN'), 4)
def test_ticket_10790_6(self):
# Querying with isnull=True across m2m field should not create inner joins
@@ -1030,16 +1030,16 @@ class Queries1Tests(BaseQuerysetTest):
['', '', '', '',
'', '']
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 4)
- self.assertTrue(str(q.query).count('INNER JOIN') == 0)
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 4)
+ self.assertEqual(str(q.query).count('INNER JOIN'), 0)
q = Author.objects.filter(item__tags__parent__isnull=True)
self.assertQuerysetEqual(
q,
['', '', '', '']
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 3)
- self.assertTrue(str(q.query).count('INNER JOIN') == 0)
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 3)
+ self.assertEqual(str(q.query).count('INNER JOIN'), 0)
def test_ticket_10790_7(self):
# Reverse querying with isnull should not strip the join
@@ -1048,16 +1048,16 @@ class Queries1Tests(BaseQuerysetTest):
q,
['']
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 1)
- self.assertTrue(str(q.query).count('INNER JOIN') == 0)
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1)
+ self.assertEqual(str(q.query).count('INNER JOIN'), 0)
q = Author.objects.filter(item__isnull=False)
self.assertQuerysetEqual(
q,
['', '', '', '']
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
- self.assertTrue(str(q.query).count('INNER JOIN') == 1)
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
+ self.assertEqual(str(q.query).count('INNER JOIN'), 1)
def test_ticket_10790_8(self):
# Querying with combined q-objects should also strip the left outer join
@@ -1066,8 +1066,8 @@ class Queries1Tests(BaseQuerysetTest):
q,
['', '', '']
)
- self.assertTrue(str(q.query).count('LEFT OUTER JOIN') == 0)
- self.assertTrue(str(q.query).count('INNER JOIN') == 0)
+ self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0)
+ self.assertEqual(str(q.query).count('INNER JOIN'), 0)
def test_ticket_10790_combine(self):
# Combining queries should not re-populate the left outer join
@@ -1079,13 +1079,13 @@ class Queries1Tests(BaseQuerysetTest):
q3,
['', '', '', '', ''],
)
- self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 0)
- self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
+ self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0)
+ self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
q3 = q1 & q2
self.assertQuerysetEqual(q3, [])
- self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 0)
- self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
+ self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0)
+ self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
q2 = Tag.objects.filter(parent=self.t1)
q3 = q1 | q2
@@ -1093,16 +1093,16 @@ class Queries1Tests(BaseQuerysetTest):
q3,
['', '', '']
)
- self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 0)
- self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
+ self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0)
+ self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
q3 = q2 | q1
self.assertQuerysetEqual(
q3,
['', '', '']
)
- self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 0)
- self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
+ self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0)
+ self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
q1 = Tag.objects.filter(parent__isnull=True)
q2 = Tag.objects.filter(parent__parent__isnull=True)
@@ -1112,16 +1112,16 @@ class Queries1Tests(BaseQuerysetTest):
q3,
['', '', '']
)
- self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 1)
- self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
+ self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 1)
+ self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
q3 = q2 | q1
self.assertQuerysetEqual(
q3,
['', '', '']
)
- self.assertTrue(str(q3.query).count('LEFT OUTER JOIN') == 1)
- self.assertTrue(str(q3.query).count('INNER JOIN') == 0)
+ self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 1)
+ self.assertEqual(str(q3.query).count('INNER JOIN'), 0)
def test_ticket19672(self):
self.assertQuerysetEqual(
@@ -1135,7 +1135,7 @@ class Queries1Tests(BaseQuerysetTest):
qs = Author.objects.annotate(Count('item'))
qs = qs.filter(~Q(extra__value=0))
- self.assertTrue('SELECT' in str(qs.query))
+ self.assertIn('SELECT', str(qs.query))
self.assertQuerysetEqual(
qs,
['', '', '', '']
@@ -1395,7 +1395,7 @@ class Queries4Tests(BaseQuerysetTest):
# Calling order_by() with no parameters removes any existing ordering on the
# model. But it should still be possible to add new ordering after that.
qs = Author.objects.order_by().order_by('name')
- self.assertTrue('ORDER BY' in qs.query.get_compiler(qs.db).as_sql()[0])
+ self.assertIn('ORDER BY', qs.query.get_compiler(qs.db).as_sql()[0])
def test_order_by_reverse_fk(self):
# It is possible to order by reverse of foreign key, although that can lead
@@ -1719,9 +1719,9 @@ class NullableRelOrderingTests(TestCase):
r = RelatedObject.objects.create(single=s, f=1)
Plaything.objects.create(name="p2", others=r)
qs = Plaything.objects.all().filter(others__isnull=False).order_by('pk')
- self.assertTrue('JOIN' not in str(qs.query))
+ self.assertNotIn('JOIN', str(qs.query))
qs = Plaything.objects.all().filter(others__f__isnull=False).order_by('pk')
- self.assertTrue('INNER' in str(qs.query))
+ self.assertIn('INNER', str(qs.query))
qs = qs.order_by('others__single__name')
# The ordering by others__single__pk will add one new join (to single)
# and that join must be LEFT join. The already existing join to related
@@ -1915,7 +1915,8 @@ class ExistsSql(TestCase):
self.assertEqual(len(captured_queries), 1)
qstr = captured_queries[0]
id, name = connection.ops.quote_name('id'), connection.ops.quote_name('name')
- self.assertTrue(id not in qstr and name not in qstr)
+ self.assertNotIn(id, qstr)
+ self.assertNotIn(name, qstr)
def test_ticket_18414(self):
Article.objects.create(name='one', created=datetime.datetime.now())
@@ -2961,13 +2962,13 @@ class NullJoinPromotionOrTest(TestCase):
def test_null_join_demotion(self):
qs = ModelA.objects.filter(Q(b__name__isnull=False) & Q(b__name__isnull=True))
- self.assertTrue(' INNER JOIN ' in str(qs.query))
+ self.assertIn(' INNER JOIN ', str(qs.query))
qs = ModelA.objects.filter(Q(b__name__isnull=True) & Q(b__name__isnull=False))
- self.assertTrue(' INNER JOIN ' in str(qs.query))
+ self.assertIn(' INNER JOIN ', str(qs.query))
qs = ModelA.objects.filter(Q(b__name__isnull=False) | Q(b__name__isnull=True))
- self.assertTrue(' LEFT OUTER JOIN ' in str(qs.query))
+ self.assertIn(' LEFT OUTER JOIN ', str(qs.query))
qs = ModelA.objects.filter(Q(b__name__isnull=True) | Q(b__name__isnull=False))
- self.assertTrue(' LEFT OUTER JOIN ' in str(qs.query))
+ self.assertIn(' LEFT OUTER JOIN ', str(qs.query))
def test_ticket_21366(self):
n = Note.objects.create(note='n', misc='m')
@@ -3314,9 +3315,9 @@ class Ticket20101Tests(TestCase):
n = Note.objects.create(note='foo', misc='bar')
qs1 = Note.objects.exclude(annotation__in=[a1, a2])
qs2 = Note.objects.filter(annotation__in=[a3])
- self.assertTrue(n in qs1)
- self.assertFalse(n in qs2)
- self.assertTrue(n in (qs1 | qs2))
+ self.assertIn(n, qs1)
+ self.assertNotIn(n, qs2)
+ self.assertIn(n, (qs1 | qs2))
class EmptyStringPromotionTests(TestCase):
@@ -3545,16 +3546,16 @@ class Ticket21203Tests(TestCase):
class ValuesJoinPromotionTests(TestCase):
def test_values_no_promotion_for_existing(self):
qs = Node.objects.filter(parent__parent__isnull=False)
- self.assertTrue(' INNER JOIN ' in str(qs.query))
+ self.assertIn(' INNER JOIN ', str(qs.query))
qs = qs.values('parent__parent__id')
- self.assertTrue(' INNER JOIN ' in str(qs.query))
+ self.assertIn(' INNER JOIN ', str(qs.query))
# Make sure there is a left outer join without the filter.
qs = Node.objects.values('parent__parent__id')
- self.assertTrue(' LEFT OUTER JOIN ' in str(qs.query))
+ self.assertIn(' LEFT OUTER JOIN ', str(qs.query))
def test_non_nullable_fk_not_promoted(self):
qs = ObjectB.objects.values('objecta__name')
- self.assertTrue(' INNER JOIN ' in str(qs.query))
+ self.assertIn(' INNER JOIN ', str(qs.query))
def test_ticket_21376(self):
a = ObjectA.objects.create()
@@ -3567,7 +3568,7 @@ class ValuesJoinPromotionTests(TestCase):
)
self.assertEqual(qs.count(), 1)
tblname = connection.ops.quote_name(ObjectB._meta.db_table)
- self.assertTrue(' LEFT OUTER JOIN %s' % tblname in str(qs.query))
+ self.assertIn(' LEFT OUTER JOIN %s' % tblname, str(qs.query))
class ForeignKeyToBaseExcludeTests(TestCase):
diff --git a/tests/raw_query/tests.py b/tests/raw_query/tests.py
index 200ffb61e1..287b0f24dd 100644
--- a/tests/raw_query/tests.py
+++ b/tests/raw_query/tests.py
@@ -73,9 +73,9 @@ class RawQueryTests(TestCase):
iterated over.
"""
q = Author.objects.raw('SELECT * FROM raw_query_author')
- self.assertTrue(q.query.cursor is None)
+ self.assertIsNone(q.query.cursor)
list(q)
- self.assertTrue(q.query.cursor is not None)
+ self.assertIsNotNone(q.query.cursor)
def test_FK_raw_query(self):
"""
diff --git a/tests/requests/tests.py b/tests/requests/tests.py
index 22b3021d1f..2065ba7e6d 100644
--- a/tests/requests/tests.py
+++ b/tests/requests/tests.py
@@ -204,7 +204,7 @@ class RequestsTests(SimpleTestCase):
example_cookie = response.cookies['example']
# A compat cookie may be in use -- check that it has worked
# both as an output string, and using the cookie attributes
- self.assertTrue('; httponly' in str(example_cookie))
+ self.assertIn('; httponly', str(example_cookie))
self.assertTrue(example_cookie['httponly'])
def test_unicode_cookie(self):
diff --git a/tests/select_related_regress/tests.py b/tests/select_related_regress/tests.py
index 4a498d707a..6ee48e9aec 100644
--- a/tests/select_related_regress/tests.py
+++ b/tests/select_related_regress/tests.py
@@ -152,7 +152,7 @@ class SelectRelatedRegressTests(TestCase):
self.assertEqual(qs[0].state, wa)
# The select_related join wasn't promoted as there was already an
# existing (even if trimmed) inner join to state.
- self.assertFalse('LEFT OUTER' in str(qs.query))
+ self.assertNotIn('LEFT OUTER', str(qs.query))
qs = Client.objects.select_related('state').order_by('name')
with self.assertNumQueries(1):
self.assertEqual(list(qs), [bob, jack])
@@ -160,7 +160,7 @@ class SelectRelatedRegressTests(TestCase):
self.assertEqual(qs[1].state, wa)
# The select_related join was promoted as there is already an
# existing join.
- self.assertTrue('LEFT OUTER' in str(qs.query))
+ self.assertIn('LEFT OUTER', str(qs.query))
def test_regression_19870(self):
hen = Hen.objects.create(name='Hen')
diff --git a/tests/settings_tests/tests.py b/tests/settings_tests/tests.py
index 51bcd114e2..c679962a99 100644
--- a/tests/settings_tests/tests.py
+++ b/tests/settings_tests/tests.py
@@ -281,7 +281,7 @@ class TestComplexSettingOverride(TestCase):
def tearDown(self):
signals.COMPLEX_OVERRIDE_SETTINGS = self.old_warn_override_settings
- self.assertFalse('TEST_WARN' in signals.COMPLEX_OVERRIDE_SETTINGS)
+ self.assertNotIn('TEST_WARN', signals.COMPLEX_OVERRIDE_SETTINGS)
def test_complex_override_warning(self):
"""Regression test for #19031"""
diff --git a/tests/template_tests/tests.py b/tests/template_tests/tests.py
index ed3a019721..cfcde1d912 100644
--- a/tests/template_tests/tests.py
+++ b/tests/template_tests/tests.py
@@ -403,7 +403,7 @@ class TemplateRegressionTests(TestCase):
while tb.tb_next is not None:
tb = tb.tb_next
depth += 1
- self.assertTrue(depth > 5,
+ self.assertGreater(depth, 5,
"The traceback context was lost when reraising the traceback. See #19827")
@override_settings(DEBUG=True, TEMPLATE_DEBUG=True)
@@ -1852,8 +1852,8 @@ class TemplateTagLoading(TestCase):
try:
template.Template(ttext)
except template.TemplateSyntaxError as e:
- self.assertTrue('ImportError' in e.args[0])
- self.assertTrue('Xtemplate' in e.args[0])
+ self.assertIn('ImportError', e.args[0])
+ self.assertIn('Xtemplate', e.args[0])
def test_load_error_egg(self):
ttext = "{% load broken_egg %}"
@@ -1866,8 +1866,8 @@ class TemplateTagLoading(TestCase):
with self.settings(INSTALLED_APPS=['tagsegg']):
template.Template(ttext)
except template.TemplateSyntaxError as e:
- self.assertTrue('ImportError' in e.args[0])
- self.assertTrue('Xtemplate' in e.args[0])
+ self.assertIn('ImportError', e.args[0])
+ self.assertIn('Xtemplate', e.args[0])
def test_load_working_egg(self):
ttext = "{% load working_egg %}"
diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py
index b3656e4963..9ceba4992f 100644
--- a/tests/test_client_regress/tests.py
+++ b/tests/test_client_regress/tests.py
@@ -955,7 +955,7 @@ class ContextTests(TestCase):
"Context variables can be retrieved from a single context"
response = self.client.get("/request_data/", data={'foo': 'whiz'})
self.assertEqual(response.context.__class__, Context)
- self.assertTrue('get-foo' in response.context)
+ self.assertIn('get-foo', response.context)
self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['request-foo'], 'whiz')
self.assertEqual(response.context['data'], 'sausage')
@@ -971,7 +971,7 @@ class ContextTests(TestCase):
response = self.client.get("/request_data_extended/", data={'foo': 'whiz'})
self.assertEqual(response.context.__class__, ContextList)
self.assertEqual(len(response.context), 2)
- self.assertTrue('get-foo' in response.context)
+ self.assertIn('get-foo', response.context)
self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['request-foo'], 'whiz')
self.assertEqual(response.context['data'], 'bacon')
diff --git a/tests/test_runner/tests.py b/tests/test_runner/tests.py
index 66d98a40c5..e1eb9a55e1 100644
--- a/tests/test_runner/tests.py
+++ b/tests/test_runner/tests.py
@@ -399,7 +399,7 @@ class DeprecationDisplayTest(AdminScriptTestCase):
args = ['test', '--settings=test_project.settings', '--verbosity=0', 'test_runner_deprecation_app']
out, err = self.run_django_admin(args)
self.assertIn("Ran 1 test", err)
- self.assertFalse("warning from test" in err)
+ self.assertNotIn("warning from test", err)
class AutoIncrementResetTest(TransactionTestCase):
diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py
index ead688dcef..99ddaf87ef 100644
--- a/tests/test_utils/tests.py
+++ b/tests/test_utils/tests.py
@@ -542,24 +542,24 @@ class HTMLEqualTests(TestCase):
# equal html contains each other
dom1 = parse_html('foo')
dom2 = parse_html('
foo
')
- self.assertTrue(dom1 in dom2)
- self.assertTrue(dom2 in dom1)
+ self.assertIn(dom1, dom2)
+ self.assertIn(dom2, dom1)
dom2 = parse_html('')
- self.assertTrue(dom1 in dom2)
- self.assertTrue(dom2 not in dom1)
+ self.assertIn(dom1, dom2)
+ self.assertNotIn(dom2, dom1)
- self.assertFalse('foo
' in dom2)
- self.assertTrue('foo' in dom2)
+ self.assertNotIn('foo
', dom2)
+ self.assertIn('foo', dom2)
# when a root element is used ...
dom1 = parse_html('foo
bar
')
dom2 = parse_html('foo
bar
')
- self.assertTrue(dom1 in dom2)
+ self.assertIn(dom1, dom2)
dom1 = parse_html('foo
')
- self.assertTrue(dom1 in dom2)
+ self.assertIn(dom1, dom2)
dom1 = parse_html('bar
')
- self.assertTrue(dom1 in dom2)
+ self.assertIn(dom1, dom2)
def test_count(self):
# equal html contains each other one time
diff --git a/tests/unmanaged_models/tests.py b/tests/unmanaged_models/tests.py
index 7b23a46096..b103cd3adc 100644
--- a/tests/unmanaged_models/tests.py
+++ b/tests/unmanaged_models/tests.py
@@ -50,7 +50,7 @@ class ManyToManyUnmanagedTests(TestCase):
"""
table = Unmanaged2._meta.get_field('mm').m2m_db_table()
tables = connection.introspection.table_names()
- self.assertTrue(table not in tables, "Table '%s' should not exist, but it does." % table)
+ self.assertNotIn(table, tables, "Table '%s' should not exist, but it does." % table)
def test_many_to_many_between_unmanaged_and_managed(self):
"""
@@ -58,4 +58,4 @@ class ManyToManyUnmanagedTests(TestCase):
"""
table = Managed1._meta.get_field('mm').m2m_db_table()
tables = connection.introspection.table_names()
- self.assertTrue(table in tables, "Table '%s' does not exist." % table)
+ self.assertIn(table, tables, "Table '%s' does not exist." % table)
diff --git a/tests/update_only_fields/tests.py b/tests/update_only_fields/tests.py
index cfca761e4c..324fc183d4 100644
--- a/tests/update_only_fields/tests.py
+++ b/tests/update_only_fields/tests.py
@@ -204,10 +204,10 @@ class UpdateOnlyFieldsTests(TestCase):
p.save(update_fields=['name'])
self.assertEqual(len(pre_save_data), 1)
self.assertEqual(len(pre_save_data[0]), 1)
- self.assertTrue('name' in pre_save_data[0])
+ self.assertIn('name', pre_save_data[0])
self.assertEqual(len(post_save_data), 1)
self.assertEqual(len(post_save_data[0]), 1)
- self.assertTrue('name' in post_save_data[0])
+ self.assertIn('name', post_save_data[0])
pre_save.disconnect(pre_save_receiver)
post_save.disconnect(post_save_receiver)
diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py
index 9e5e4f513f..18299fe733 100644
--- a/tests/urlpatterns_reverse/tests.py
+++ b/tests/urlpatterns_reverse/tests.py
@@ -292,7 +292,7 @@ class ResolverTests(unittest.TestCase):
self.fail('resolve did not raise a 404')
except Resolver404 as e:
# make sure we at least matched the root ('/') url resolver:
- self.assertTrue('tried' in e.args[0])
+ self.assertIn('tried', e.args[0])
tried = e.args[0]['tried']
self.assertEqual(len(e.args[0]['tried']), len(url_types_names), 'Wrong number of tried URLs returned. Expected %s, got %s.' % (len(url_types_names), len(e.args[0]['tried'])))
for tried, expected in zip(e.args[0]['tried'], url_types_names):
@@ -300,7 +300,7 @@ class ResolverTests(unittest.TestCase):
self.assertIsInstance(t, e['type']), str('%s is not an instance of %s') % (t, e['type'])
if 'name' in e:
if not e['name']:
- self.assertTrue(t.name is None, 'Expected no URL name but found %s.' % t.name)
+ self.assertIsNone(t.name, 'Expected no URL name but found %s.' % t.name)
else:
self.assertEqual(t.name, e['name'], 'Wrong URL name. Expected "%s", got "%s".' % (e['name'], t.name))
diff --git a/tests/utils_tests/test_datastructures.py b/tests/utils_tests/test_datastructures.py
index ec4001cafc..d9a0a678f8 100644
--- a/tests/utils_tests/test_datastructures.py
+++ b/tests/utils_tests/test_datastructures.py
@@ -177,7 +177,7 @@ class MergeDictTests(IgnoreDeprecationWarningsMixin, SimpleTestCase):
self.assertEqual(sorted(six.iterkeys(mm)), ['key1', 'key2', 'key4'])
self.assertEqual(len(list(six.itervalues(mm))), 3)
- self.assertTrue('value1' in six.itervalues(mm))
+ self.assertIn('value1', six.itervalues(mm))
self.assertEqual(
sorted(six.iteritems(mm), key=lambda k: k[0]),
diff --git a/tests/utils_tests/test_functional.py b/tests/utils_tests/test_functional.py
index b806be0b16..7d71f32415 100644
--- a/tests/utils_tests/test_functional.py
+++ b/tests/utils_tests/test_functional.py
@@ -20,7 +20,7 @@ class FunctionalTestCase(unittest.TestCase):
pass
t = lazy(lambda: Klazz(), Klazz)()
- self.assertTrue('base_method' in dir(t))
+ self.assertIn('base_method', dir(t))
def test_lazy_property(self):
diff --git a/tests/utils_tests/test_http.py b/tests/utils_tests/test_http.py
index c54c15a95d..b3e2c7b8d3 100644
--- a/tests/utils_tests/test_http.py
+++ b/tests/utils_tests/test_http.py
@@ -47,7 +47,7 @@ class TestUtilsHttp(unittest.TestCase):
'c=3&a=1&b=2',
'c=3&b=2&a=1'
]
- self.assertTrue(result in acceptable_results)
+ self.assertIn(result, acceptable_results)
result = http.urlencode({'a': [1, 2]}, doseq=False)
self.assertEqual(result, 'a=%5B%271%27%2C+%272%27%5D')
result = http.urlencode({'a': [1, 2]}, doseq=True)
@@ -65,7 +65,7 @@ class TestUtilsHttp(unittest.TestCase):
'name=Adrian&name=Simon&position=Developer',
'position=Developer&name=Adrian&name=Simon'
]
- self.assertTrue(result in acceptable_results)
+ self.assertIn(result, acceptable_results)
def test_base36(self):
# reciprocity works
diff --git a/tests/utils_tests/test_lazyobject.py b/tests/utils_tests/test_lazyobject.py
index c15388fb3b..a80f0a2c95 100644
--- a/tests/utils_tests/test_lazyobject.py
+++ b/tests/utils_tests/test_lazyobject.py
@@ -257,8 +257,8 @@ class SimpleLazyObjectTestCase(LazyObjectTestCase):
self.assertEqual(lazydict['one'], 1)
lazydict['one'] = -1
self.assertEqual(lazydict['one'], -1)
- self.assertTrue('one' in lazydict)
- self.assertFalse('two' in lazydict)
+ self.assertIn('one', lazydict)
+ self.assertNotIn('two', lazydict)
self.assertEqual(len(lazydict), 1)
del lazydict['one']
with self.assertRaises(KeyError):
@@ -267,9 +267,9 @@ class SimpleLazyObjectTestCase(LazyObjectTestCase):
def test_list_set(self):
lazy_list = SimpleLazyObject(lambda: [1, 2, 3, 4, 5])
lazy_set = SimpleLazyObject(lambda: {1, 2, 3, 4})
- self.assertTrue(1 in lazy_list)
- self.assertTrue(1 in lazy_set)
- self.assertFalse(6 in lazy_list)
- self.assertFalse(6 in lazy_set)
+ self.assertIn(1, lazy_list)
+ self.assertIn(1, lazy_set)
+ self.assertNotIn(6, lazy_list)
+ self.assertNotIn(6, lazy_set)
self.assertEqual(len(lazy_list), 5)
self.assertEqual(len(lazy_set), 4)
diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py
index ffe4daec93..e50a29f1d1 100644
--- a/tests/view_tests/tests/test_debug.py
+++ b/tests/view_tests/tests/test_debug.py
@@ -115,7 +115,7 @@ class DebugViewTests(TestCase):
# '', not '
', response.content)
- self.assertFalse(match is None)
+ self.assertIsNotNone(match)
id_repr = match.group('id')
self.assertFalse(re.search(b'[^c0-9]', id_repr),
"Numeric IDs in debug response HTML page shouldn't be localized (value: %s)." % id_repr)
@@ -126,7 +126,7 @@ class DebugViewTests(TestCase):
self.client.get(reverse('template_exception', args=(n,)))
except Exception:
raising_loc = inspect.trace()[-1][-2][0].strip()
- self.assertFalse(raising_loc.find('raise BrokenException') == -1,
+ self.assertNotEqual(raising_loc.find('raise BrokenException'), -1,
"Failed to find 'raise BrokenException' in last frame of traceback, instead found: %s" %
raising_loc)
diff --git a/tests/wsgi/tests.py b/tests/wsgi/tests.py
index 092d3a751e..e8f29c60d8 100644
--- a/tests/wsgi/tests.py
+++ b/tests/wsgi/tests.py
@@ -64,7 +64,7 @@ class GetInternalWSGIApplicationTest(unittest.TestCase):
from .wsgi import application
- self.assertTrue(app is application)
+ self.assertIs(app, application)
@override_settings(WSGI_APPLICATION=None)
def test_default(self):
@@ -85,7 +85,7 @@ class GetInternalWSGIApplicationTest(unittest.TestCase):
try:
app = get_internal_wsgi_application()
- self.assertTrue(app is fake_app)
+ self.assertIs(app, fake_app)
finally:
basehttp.get_wsgi_application = _orig_get_wsgi_app