Unify using assertIsInstance

Use assertIsInstance(A, B) to replace assertTrue(isinstance(A, B)).

Prefer specific assertions such as assert(Not)IsInstance over generic ones
(assertTrue/False, assertEqual) because they raise more meaningful errors.

Change-Id: I56278b1a74108e2765a8a740658f33954f5404c7
Closes-bug: #1268480
This commit is contained in:
lzklibj 2016-01-06 11:27:34 +08:00
parent b318c2b0e8
commit d2a1d6fcb7
3 changed files with 31 additions and 0 deletions

View File

@ -21,6 +21,7 @@ Neutron Specific Commandments
- [N329] Method's default argument shouldn't be mutable
- [N330] Use assertEqual(*empty*, observed) instead of
assertEqual(observed, *empty*)
- [N331] Detect wrong usage with assertTrue(isinstance()).
Creating Unit Tests
-------------------

View File

@ -219,6 +219,15 @@ def check_assertempty(logical_line, filename):
yield (0, msg)
def check_assertisinstance(logical_line, filename):
if 'neutron/tests/' in filename:
if re.search(r"assertTrue\(\s*isinstance\(\s*[^,]*,\s*[^,]*\)\)",
logical_line):
msg = ("N331: Use assertIsInstance(observed, type) instead "
"of assertTrue(isinstance(observed, type))")
yield (0, msg)
def factory(register):
register(validate_log_translations)
register(use_jsonutils)
@ -233,3 +242,4 @@ def factory(register):
register(no_mutable_default_args)
register(check_assertfalse)
register(check_assertempty)
register(check_assertisinstance)

View File

@ -240,3 +240,23 @@ class HackingTestCase(base.BaseTestCase):
self.assertEqual(
0, len(list(checks.check_assertfalse(pass_code2 % ec,
"neutron/tests/test_assert.py"))))
def test_assertisinstance(self):
fail_code = """
self.assertTrue(isinstance(observed, ANY_TYPE))
"""
pass_code1 = """
self.assertEqual(ANY_TYPE, type(observed))
"""
pass_code2 = """
self.assertIsInstance(observed, ANY_TYPE)
"""
self.assertEqual(
1, len(list(checks.check_assertisinstance(fail_code,
"neutron/tests/test_assert.py"))))
self.assertEqual(
0, len(list(checks.check_assertisinstance(pass_code1,
"neutron/tests/test_assert.py"))))
self.assertEqual(
0, len(list(checks.check_assertisinstance(pass_code2,
"neutron/tests/test_assert.py"))))