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):
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 my_callable():
@ -947,7 +947,7 @@ class BaseCacheTests:
self.assertIsNone(cache.get('projector'))
self.assertEqual(cache.get_or_set('projector', 42), 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 my_callable():

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -229,8 +229,8 @@ class CallbackFilterTest(SimpleTestCase):
f_false = CallbackFilter(lambda r: False)
f_true = CallbackFilter(lambda r: True)
self.assertEqual(f_false.filter("record"), False)
self.assertEqual(f_true.filter("record"), True)
self.assertFalse(f_false.filter('record'))
self.assertTrue(f_true.filter('record'))
def test_passes_on_record(self):
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]
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'):
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):
with connections[using].cursor() as cursor:

View File

@ -1052,7 +1052,7 @@ class ModelStateTests(SimpleTestCase):
['searchablelocation_ptr', 'name', 'bus_routes', 'inbound']
)
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(
station_state.options,
{'abstract': False, 'swappable': 'TEST_SWAPPABLE_MODEL', 'indexes': [], 'constraints': []}

View File

@ -66,7 +66,7 @@ class ChoicesTests(SimpleTestCase):
def test_integerchoices_empty_label(self):
self.assertEqual(Vehicle.choices[0], (None, '(Unknown)'))
self.assertEqual(Vehicle.labels[0], '(Unknown)')
self.assertEqual(Vehicle.values[0], None)
self.assertIsNone(Vehicle.values[0])
self.assertEqual(Vehicle.names[0], '__empty__')
def test_integerchoices_functional_api(self):
@ -107,7 +107,7 @@ class ChoicesTests(SimpleTestCase):
def test_textchoices_empty_label(self):
self.assertEqual(Gender.choices[0], (None, '(Undeclared)'))
self.assertEqual(Gender.labels[0], '(Undeclared)')
self.assertEqual(Gender.values[0], None)
self.assertIsNone(Gender.values[0])
self.assertEqual(Gender.names[0], '__empty__')
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.
p.mugshot.delete(save=False)
self.assertEqual(p.mugshot, None)
self.assertIsNone(p.mugshot.name)
self.check_dimensions(p, None, None)
def test_dimensions(self):

View File

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

View File

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

View File

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

View File

@ -250,7 +250,7 @@ class TestUtilsText(SimpleTestCase):
actual_length = len(b''.join(seq))
out = text.compress_sequence(seq)
compressed_length = len(b''.join(out))
self.assertTrue(compressed_length < actual_length)
self.assertLess(compressed_length, actual_length)
def test_format_lazy(self):
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['path'], '/test/')
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['secure'], True)
self.assertIs(language_cookie['secure'], True)
def test_setlang_decodes_http_referer_url(self):
"""