Used more specific unittest assertions in tests.

* assertIsNone()/assertIsNotNone() instead of comparing to None.
* assertLess() for < comparisons.
* assertIs() for 'is' expressions.
* assertIsInstance() for isinstance() expressions.
* rounding of assertAlmostEqual() for round() expressions.
* assertIs(..., True/False) instead of comparing to True/False.
* assertIs()/assertIsNot() for ==/!= comparisons.
* assertNotEqual() for == comparisons.
* assertTrue()/assertFalse() instead of comparing to True/False.
This commit is contained in:
Nick Pope 2019-10-21 09:55:05 +01:00 committed by Mariusz Felisiak
parent a6cb8ec389
commit 7552de7866
18 changed files with 54 additions and 51 deletions

View File

@ -219,7 +219,7 @@ class DummyCacheTests(SimpleTestCase):
def test_get_or_set(self): def test_get_or_set(self):
self.assertEqual(cache.get_or_set('mykey', 'default'), 'default') self.assertEqual(cache.get_or_set('mykey', 'default'), 'default')
self.assertEqual(cache.get_or_set('mykey', None), None) self.assertIsNone(cache.get_or_set('mykey', None))
def test_get_or_set_callable(self): def test_get_or_set_callable(self):
def my_callable(): def my_callable():
@ -947,7 +947,7 @@ class BaseCacheTests:
self.assertIsNone(cache.get('projector')) self.assertIsNone(cache.get('projector'))
self.assertEqual(cache.get_or_set('projector', 42), 42) self.assertEqual(cache.get_or_set('projector', 42), 42)
self.assertEqual(cache.get('projector'), 42) self.assertEqual(cache.get('projector'), 42)
self.assertEqual(cache.get_or_set('null', None), None) self.assertIsNone(cache.get_or_set('null', None))
def test_get_or_set_callable(self): def test_get_or_set_callable(self):
def my_callable(): def my_callable():

View File

@ -20,16 +20,16 @@ class RoundTests(TestCase):
obj = DecimalModel.objects.annotate(n1_round=Round('n1'), n2_round=Round('n2')).first() obj = DecimalModel.objects.annotate(n1_round=Round('n1'), n2_round=Round('n2')).first()
self.assertIsInstance(obj.n1_round, Decimal) self.assertIsInstance(obj.n1_round, Decimal)
self.assertIsInstance(obj.n2_round, Decimal) self.assertIsInstance(obj.n2_round, Decimal)
self.assertAlmostEqual(obj.n1_round, round(obj.n1)) self.assertAlmostEqual(obj.n1_round, obj.n1, places=0)
self.assertAlmostEqual(obj.n2_round, round(obj.n2)) self.assertAlmostEqual(obj.n2_round, obj.n2, places=0)
def test_float(self): def test_float(self):
FloatModel.objects.create(f1=-27.55, f2=0.55) FloatModel.objects.create(f1=-27.55, f2=0.55)
obj = FloatModel.objects.annotate(f1_round=Round('f1'), f2_round=Round('f2')).first() obj = FloatModel.objects.annotate(f1_round=Round('f1'), f2_round=Round('f2')).first()
self.assertIsInstance(obj.f1_round, float) self.assertIsInstance(obj.f1_round, float)
self.assertIsInstance(obj.f2_round, float) self.assertIsInstance(obj.f2_round, float)
self.assertAlmostEqual(obj.f1_round, round(obj.f1)) self.assertAlmostEqual(obj.f1_round, obj.f1, places=0)
self.assertAlmostEqual(obj.f2_round, round(obj.f2)) self.assertAlmostEqual(obj.f2_round, obj.f2, places=0)
def test_integer(self): def test_integer(self):
IntegerModel.objects.create(small=-20, normal=15, big=-1) IntegerModel.objects.create(small=-20, normal=15, big=-1)
@ -41,9 +41,9 @@ class RoundTests(TestCase):
self.assertIsInstance(obj.small_round, int) self.assertIsInstance(obj.small_round, int)
self.assertIsInstance(obj.normal_round, int) self.assertIsInstance(obj.normal_round, int)
self.assertIsInstance(obj.big_round, int) self.assertIsInstance(obj.big_round, int)
self.assertEqual(obj.small_round, round(obj.small)) self.assertAlmostEqual(obj.small_round, obj.small, places=0)
self.assertEqual(obj.normal_round, round(obj.normal)) self.assertAlmostEqual(obj.normal_round, obj.normal, places=0)
self.assertEqual(obj.big_round, round(obj.big)) self.assertAlmostEqual(obj.big_round, obj.big, places=0)
def test_transform(self): def test_transform(self):
with register_lookup(DecimalField, Round): with register_lookup(DecimalField, Round):

View File

@ -479,8 +479,9 @@ class FileUploadTests(TestCase):
try: try:
self.client.post('/upload_errors/', post_data) self.client.post('/upload_errors/', post_data)
except reference_error.__class__ as err: except reference_error.__class__ as err:
self.assertFalse( self.assertNotEqual(
str(err) == str(reference_error), str(err),
str(reference_error),
"Caught a repeated exception that'll cause an infinite loop in file uploads." "Caught a repeated exception that'll cause an infinite loop in file uploads."
) )
except Exception as err: except Exception as err:

View File

@ -1973,7 +1973,7 @@ Password: <input type="password" name="password" required></li>
occupation = CharField(initial=lambda: 'Unknown') occupation = CharField(initial=lambda: 'Unknown')
form = PersonForm(initial={'first_name': 'Jane'}) form = PersonForm(initial={'first_name': 'Jane'})
self.assertEqual(form.get_initial_for_field(form.fields['age'], 'age'), None) self.assertIsNone(form.get_initial_for_field(form.fields['age'], 'age'))
self.assertEqual(form.get_initial_for_field(form.fields['last_name'], 'last_name'), 'Doe') self.assertEqual(form.get_initial_for_field(form.fields['last_name'], 'last_name'), 'Doe')
# Form.initial overrides Field.initial. # Form.initial overrides Field.initial.
self.assertEqual(form.get_initial_for_field(form.fields['first_name'], 'first_name'), 'Jane') self.assertEqual(form.get_initial_for_field(form.fields['first_name'], 'first_name'), 'Jane')
@ -3729,7 +3729,7 @@ class RendererTests(SimpleTestCase):
default_renderer = CustomRenderer default_renderer = CustomRenderer
form = CustomForm() form = CustomForm()
self.assertTrue(isinstance(form.renderer, CustomForm.default_renderer)) self.assertIsInstance(form.renderer, CustomForm.default_renderer)
def test_attribute_override(self): def test_attribute_override(self):
class CustomForm(Form): class CustomForm(Form):

View File

@ -257,13 +257,13 @@ class SelectTest(WidgetTest):
self.assertEqual(options[0]['value'], 'J') self.assertEqual(options[0]['value'], 'J')
self.assertEqual(options[0]['label'], 'John') self.assertEqual(options[0]['label'], 'John')
self.assertEqual(options[0]['index'], '0') self.assertEqual(options[0]['index'], '0')
self.assertEqual(options[0]['selected'], True) self.assertIs(options[0]['selected'], True)
# Template-related attributes # Template-related attributes
self.assertEqual(options[1]['name'], 'name') self.assertEqual(options[1]['name'], 'name')
self.assertEqual(options[1]['value'], 'P') self.assertEqual(options[1]['value'], 'P')
self.assertEqual(options[1]['label'], 'Paul') self.assertEqual(options[1]['label'], 'Paul')
self.assertEqual(options[1]['index'], '1') self.assertEqual(options[1]['index'], '1')
self.assertEqual(options[1]['selected'], False) self.assertIs(options[1]['selected'], False)
def test_optgroups(self): def test_optgroups(self):
choices = [ choices = [
@ -336,7 +336,7 @@ class SelectTest(WidgetTest):
) )
self.assertEqual(index, 1) self.assertEqual(index, 1)
label, options, index = unknown label, options, index = unknown
self.assertEqual(label, None) self.assertIsNone(label)
self.assertEqual( self.assertEqual(
options, options,
[{ [{

View File

@ -183,9 +183,9 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
# Error shouldn't be raise on equivalence testing with # Error shouldn't be raise on equivalence testing with
# an invalid type. # an invalid type.
for g in (p, ls): for g in (p, ls):
self.assertNotEqual(g, None) self.assertIsNotNone(g)
self.assertNotEqual(g, {'foo': 'bar'}) self.assertNotEqual(g, {'foo': 'bar'})
self.assertNotEqual(g, False) self.assertIsNot(g, False)
def test_hash(self): def test_hash(self):
point_1 = Point(5, 23) point_1 = Point(5, 23)
@ -236,7 +236,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertEqual(p.x, pnt.x) self.assertEqual(p.x, pnt.x)
self.assertEqual(p.y, pnt.y) self.assertEqual(p.y, pnt.y)
self.assertEqual(pnt, fromstr(p.wkt)) self.assertEqual(pnt, fromstr(p.wkt))
self.assertEqual(False, pnt == prev) # Use assertEqual to test __eq__ self.assertIs(pnt == prev, False) # Use assertIs() to test __eq__.
# Making sure that the point's X, Y components are what we expect # Making sure that the point's X, Y components are what we expect
self.assertAlmostEqual(p.x, pnt.tuple[0], 9) self.assertAlmostEqual(p.x, pnt.tuple[0], 9)
@ -323,7 +323,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertEqual(l.tup, ls.tuple) self.assertEqual(l.tup, ls.tuple)
self.assertEqual(ls, fromstr(l.wkt)) self.assertEqual(ls, fromstr(l.wkt))
self.assertEqual(False, ls == prev) # Use assertEqual to test __eq__ self.assertIs(ls == prev, False) # Use assertIs() to test __eq__.
with self.assertRaises(IndexError): with self.assertRaises(IndexError):
ls.__getitem__(len(ls)) ls.__getitem__(len(ls))
prev = ls prev = ls
@ -399,7 +399,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertAlmostEqual(l.centroid[1], ml.centroid.y, 9) self.assertAlmostEqual(l.centroid[1], ml.centroid.y, 9)
self.assertEqual(ml, fromstr(l.wkt)) self.assertEqual(ml, fromstr(l.wkt))
self.assertEqual(False, ml == prev) # Use assertEqual to test __eq__ self.assertIs(ml == prev, False) # Use assertIs() to test __eq__.
prev = ml prev = ml
for ls in ml: for ls in ml:
@ -483,8 +483,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
# Testing the geometry equivalence # Testing the geometry equivalence
self.assertEqual(poly, fromstr(p.wkt)) self.assertEqual(poly, fromstr(p.wkt))
# Should not be equal to previous geometry # Should not be equal to previous geometry
self.assertEqual(False, poly == prev) # Use assertEqual to test __eq__ self.assertIs(poly == prev, False) # Use assertIs() to test __eq__.
self.assertNotEqual(poly, prev) # Use assertNotEqual to test __ne__ self.assertIs(poly != prev, True) # Use assertIs() to test __ne__.
# Testing the exterior ring # Testing the exterior ring
ring = poly.exterior_ring ring = poly.exterior_ring

View File

@ -229,8 +229,8 @@ class CallbackFilterTest(SimpleTestCase):
f_false = CallbackFilter(lambda r: False) f_false = CallbackFilter(lambda r: False)
f_true = CallbackFilter(lambda r: True) f_true = CallbackFilter(lambda r: True)
self.assertEqual(f_false.filter("record"), False) self.assertFalse(f_false.filter('record'))
self.assertEqual(f_true.filter("record"), True) self.assertTrue(f_true.filter('record'))
def test_passes_on_record(self): def test_passes_on_record(self):
collector = [] collector = []

View File

@ -50,10 +50,10 @@ class MigrationTestBase(TransactionTestCase):
return [c.null_ok for c in self.get_table_description(table, using=using) if c.name == column][0] return [c.null_ok for c in self.get_table_description(table, using=using) if c.name == column][0]
def assertColumnNull(self, table, column, using='default'): def assertColumnNull(self, table, column, using='default'):
self.assertEqual(self._get_column_allows_null(table, column, using), True) self.assertTrue(self._get_column_allows_null(table, column, using))
def assertColumnNotNull(self, table, column, using='default'): def assertColumnNotNull(self, table, column, using='default'):
self.assertEqual(self._get_column_allows_null(table, column, using), False) self.assertFalse(self._get_column_allows_null(table, column, using))
def assertIndexExists(self, table, columns, value=True, using='default', index_type=None): def assertIndexExists(self, table, columns, value=True, using='default', index_type=None):
with connections[using].cursor() as cursor: with connections[using].cursor() as cursor:

View File

@ -1052,7 +1052,7 @@ class ModelStateTests(SimpleTestCase):
['searchablelocation_ptr', 'name', 'bus_routes', 'inbound'] ['searchablelocation_ptr', 'name', 'bus_routes', 'inbound']
) )
self.assertEqual(station_state.fields[1][1].max_length, 128) self.assertEqual(station_state.fields[1][1].max_length, 128)
self.assertEqual(station_state.fields[2][1].null, False) self.assertIs(station_state.fields[2][1].null, False)
self.assertEqual( self.assertEqual(
station_state.options, station_state.options,
{'abstract': False, 'swappable': 'TEST_SWAPPABLE_MODEL', 'indexes': [], 'constraints': []} {'abstract': False, 'swappable': 'TEST_SWAPPABLE_MODEL', 'indexes': [], 'constraints': []}

View File

@ -66,7 +66,7 @@ class ChoicesTests(SimpleTestCase):
def test_integerchoices_empty_label(self): def test_integerchoices_empty_label(self):
self.assertEqual(Vehicle.choices[0], (None, '(Unknown)')) self.assertEqual(Vehicle.choices[0], (None, '(Unknown)'))
self.assertEqual(Vehicle.labels[0], '(Unknown)') self.assertEqual(Vehicle.labels[0], '(Unknown)')
self.assertEqual(Vehicle.values[0], None) self.assertIsNone(Vehicle.values[0])
self.assertEqual(Vehicle.names[0], '__empty__') self.assertEqual(Vehicle.names[0], '__empty__')
def test_integerchoices_functional_api(self): def test_integerchoices_functional_api(self):
@ -107,7 +107,7 @@ class ChoicesTests(SimpleTestCase):
def test_textchoices_empty_label(self): def test_textchoices_empty_label(self):
self.assertEqual(Gender.choices[0], (None, '(Undeclared)')) self.assertEqual(Gender.choices[0], (None, '(Undeclared)'))
self.assertEqual(Gender.labels[0], '(Undeclared)') self.assertEqual(Gender.labels[0], '(Undeclared)')
self.assertEqual(Gender.values[0], None) self.assertIsNone(Gender.values[0])
self.assertEqual(Gender.names[0], '__empty__') self.assertEqual(Gender.names[0], '__empty__')
def test_textchoices_functional_api(self): def test_textchoices_functional_api(self):

View File

@ -269,7 +269,7 @@ class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase):
# Field and dimensions should be cleared after a delete. # Field and dimensions should be cleared after a delete.
p.mugshot.delete(save=False) p.mugshot.delete(save=False)
self.assertEqual(p.mugshot, None) self.assertIsNone(p.mugshot.name)
self.check_dimensions(p, None, None) self.check_dimensions(p, None, None)
def test_dimensions(self): def test_dimensions(self):

View File

@ -271,7 +271,7 @@ class OneToOneTests(TestCase):
# Creation using keyword argument and unsaved related instance (#8070). # Creation using keyword argument and unsaved related instance (#8070).
p = Place() p = Place()
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.

View File

@ -114,4 +114,4 @@ class DeleteCookieTests(SimpleTestCase):
with self.subTest(prefix=prefix): with self.subTest(prefix=prefix):
cookie_name = '__%s-c' % prefix cookie_name = '__%s-c' % prefix
response.delete_cookie(cookie_name) response.delete_cookie(cookie_name)
self.assertEqual(response.cookies[cookie_name]['secure'], True) self.assertIs(response.cookies[cookie_name]['secure'], True)

View File

@ -468,7 +468,7 @@ class SchemaTests(TransactionTestCase):
# Ensure the field is right afterwards # Ensure the field is right afterwards
columns = self.column_classes(Author) columns = self.column_classes(Author)
self.assertEqual(columns['age'][0], "IntegerField") self.assertEqual(columns['age'][0], "IntegerField")
self.assertEqual(columns['age'][1][6], True) self.assertTrue(columns['age'][1][6])
def test_add_field_remove_field(self): def test_add_field_remove_field(self):
""" """
@ -620,7 +620,7 @@ class SchemaTests(TransactionTestCase):
# Ensure the field is right afterwards # Ensure the field is right afterwards
columns = self.column_classes(Author) columns = self.column_classes(Author)
self.assertEqual(columns['name'][0], "TextField") self.assertEqual(columns['name'][0], "TextField")
self.assertEqual(columns['name'][1][6], True) self.assertTrue(columns['name'][1][6])
# Change nullability again # Change nullability again
new_field2 = TextField(null=False) new_field2 = TextField(null=False)
new_field2.set_attributes_from_name("name") new_field2.set_attributes_from_name("name")
@ -2100,25 +2100,25 @@ class SchemaTests(TransactionTestCase):
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
editor.create_model(Tag) editor.create_model(Tag)
# Ensure there's no index on the year/slug columns first # Ensure there's no index on the year/slug columns first
self.assertEqual( self.assertIs(
False,
any( any(
c["index"] c["index"]
for c in self.get_constraints("schema_tag").values() for c in self.get_constraints("schema_tag").values()
if c['columns'] == ["slug", "title"] if c['columns'] == ["slug", "title"]
), ),
False,
) )
# Alter the model to add an index # Alter the model to add an index
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
editor.alter_index_together(Tag, [], [("slug", "title")]) editor.alter_index_together(Tag, [], [("slug", "title")])
# Ensure there is now an index # Ensure there is now an index
self.assertEqual( self.assertIs(
True,
any( any(
c["index"] c["index"]
for c in self.get_constraints("schema_tag").values() for c in self.get_constraints("schema_tag").values()
if c['columns'] == ["slug", "title"] if c['columns'] == ["slug", "title"]
), ),
True,
) )
# Alter it back # Alter it back
new_field2 = SlugField(unique=True) new_field2 = SlugField(unique=True)
@ -2126,13 +2126,13 @@ class SchemaTests(TransactionTestCase):
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
editor.alter_index_together(Tag, [("slug", "title")], []) editor.alter_index_together(Tag, [("slug", "title")], [])
# Ensure there's no index # Ensure there's no index
self.assertEqual( self.assertIs(
False,
any( any(
c["index"] c["index"]
for c in self.get_constraints("schema_tag").values() for c in self.get_constraints("schema_tag").values()
if c['columns'] == ["slug", "title"] if c['columns'] == ["slug", "title"]
), ),
False,
) )
def test_index_together_with_fk(self): def test_index_together_with_fk(self):
@ -2161,13 +2161,13 @@ class SchemaTests(TransactionTestCase):
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
editor.create_model(TagIndexed) editor.create_model(TagIndexed)
# Ensure there is an index # Ensure there is an index
self.assertEqual( self.assertIs(
True,
any( any(
c["index"] c["index"]
for c in self.get_constraints("schema_tagindexed").values() for c in self.get_constraints("schema_tagindexed").values()
if c['columns'] == ["slug", "title"] if c['columns'] == ["slug", "title"]
), ),
True,
) )
@skipUnlessDBFeature('allows_multiple_constraints_on_same_fields') @skipUnlessDBFeature('allows_multiple_constraints_on_same_fields')

View File

@ -13,12 +13,14 @@ class OriginTestCase(TestCase):
a = self.engine.get_template('index.html') a = self.engine.get_template('index.html')
b = self.engine.get_template('index.html') b = self.engine.get_template('index.html')
self.assertEqual(a.origin, b.origin) self.assertEqual(a.origin, b.origin)
self.assertTrue(a.origin == b.origin) # Use assertIs() to test __eq__/__ne__.
self.assertFalse(a.origin != b.origin) self.assertIs(a.origin == b.origin, True)
self.assertIs(a.origin != b.origin, False)
def test_origin_compares_not_equal(self): def test_origin_compares_not_equal(self):
a = self.engine.get_template('first/test.html') a = self.engine.get_template('first/test.html')
b = self.engine.get_template('second/test.html') b = self.engine.get_template('second/test.html')
self.assertNotEqual(a.origin, b.origin) self.assertNotEqual(a.origin, b.origin)
self.assertFalse(a.origin == b.origin) # Use assertIs() to test __eq__/__ne__.
self.assertTrue(a.origin != b.origin) self.assertIs(a.origin == b.origin, False)
self.assertIs(a.origin != b.origin, True)

View File

@ -104,7 +104,7 @@ class TestEncodingUtils(SimpleTestCase):
class TestRFC3987IEncodingUtils(unittest.TestCase): class TestRFC3987IEncodingUtils(unittest.TestCase):
def test_filepath_to_uri(self): def test_filepath_to_uri(self):
self.assertEqual(filepath_to_uri(None), None) self.assertIsNone(filepath_to_uri(None))
self.assertEqual(filepath_to_uri('upload\\чубака.mp4'), 'upload/%D1%87%D1%83%D0%B1%D0%B0%D0%BA%D0%B0.mp4') self.assertEqual(filepath_to_uri('upload\\чубака.mp4'), 'upload/%D1%87%D1%83%D0%B1%D0%B0%D0%BA%D0%B0.mp4')
def test_iri_to_uri(self): def test_iri_to_uri(self):

View File

@ -250,7 +250,7 @@ class TestUtilsText(SimpleTestCase):
actual_length = len(b''.join(seq)) actual_length = len(b''.join(seq))
out = text.compress_sequence(seq) out = text.compress_sequence(seq)
compressed_length = len(b''.join(out)) compressed_length = len(b''.join(out))
self.assertTrue(compressed_length < actual_length) self.assertLess(compressed_length, actual_length)
def test_format_lazy(self): def test_format_lazy(self):
self.assertEqual('django/test', format_lazy('{}/{}', 'django', lazystr('test'))) self.assertEqual('django/test', format_lazy('{}/{}', 'django', lazystr('test')))

View File

@ -190,9 +190,9 @@ class SetLanguageTests(TestCase):
self.assertEqual(language_cookie['domain'], '.example.com') self.assertEqual(language_cookie['domain'], '.example.com')
self.assertEqual(language_cookie['path'], '/test/') self.assertEqual(language_cookie['path'], '/test/')
self.assertEqual(language_cookie['max-age'], 3600 * 7 * 2) self.assertEqual(language_cookie['max-age'], 3600 * 7 * 2)
self.assertEqual(language_cookie['httponly'], True) self.assertIs(language_cookie['httponly'], True)
self.assertEqual(language_cookie['samesite'], 'Strict') self.assertEqual(language_cookie['samesite'], 'Strict')
self.assertEqual(language_cookie['secure'], True) self.assertIs(language_cookie['secure'], True)
def test_setlang_decodes_http_referer_url(self): def test_setlang_decodes_http_referer_url(self):
""" """