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
- [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
-------------------
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)
register(no_mutable_default_args)
register(check_assertfalse)
register(check_assertempty)
+ register(check_assertisinstance)
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"))))