Add contributor doc on assertEqual vs assertFalse

Explain a caveat of using assertFalse.

Change-Id: I2d535477dae071b80b0469f4b51287a49846d01d
This commit is contained in:
Eric Harney 2017-08-30 11:49:38 -04:00
parent 40c2eeabc9
commit 0dd63d7084
2 changed files with 52 additions and 2 deletions

View File

@ -58,8 +58,6 @@ no_contextlib_nested = re.compile(r"\s*with (contextlib\.)?nested\(")
logging_instance = re.compile(
r"(.)*LOG\.(warning|info|debug|error|exception)\(")
assert_None = re.compile(
r".*assertEqual\(None, .*\)")
assert_True = re.compile(
r".*assertEqual\(True, .*\)")
@ -447,6 +445,10 @@ def no_test_log(logical_line, filename, noqa):
def validate_assertTrue(logical_line):
# Note: a comparable check cannot be implemented for
# assertFalse(), because assertFalse(None) passes.
# Therefore, assertEqual(False, value) is required to
# have the strongest test.
if re.match(assert_True, logical_line):
msg = ("C313: Unit tests should use assertTrue(value) instead"
" of using assertEqual(True, value).")

View File

@ -160,6 +160,54 @@ To Fix:
sudo dnf install python3-devel
**Assertion types in unit tests**
In general, it is best to use the most specific assertion possible in a unit
test, to have the strongest validation of code behavior.
For example:
.. code-block:: python
self.assertEqual("in-use", volume.status)
is preferred over
.. code-block:: python
self.assertIsNotNone(volume.status)
or
Test methods that implement comparison checks are also generally preferred
over writing code into assertEqual() or assertTrue().
.. code-block:: python
self.assertGreater(2, volume.size)
is preferred over
.. code-block:: python
self.assertTrue(2 > volume.size)
However, assertFalse() behavior is not obvious in this regard. Since
``None`` evaluates to ``False`` in Python, the following check will pass when
x is ``False`` or ``None``.
.. code-block:: python
self.assertFalse(x)
Therefore, it is preferable to use:
.. code-block:: python
self.assertEqual(x, False)
.. rubric:: Footnotes
.. [#f1] See :doc:`jenkins`.