问题
Why does assertFalse
succeed on None
?
import unittest
class TestNoneIsFalse(unittest.TestCase):
def test_none_is_false(self):
self.assertFalse(None)
Results:
> python -m unittest temp
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
It seems as if this behaviour invites errors where a function does not always return a value. For example:
def is_lower_than_5(x):
if x < 5:
return True
elif x > 5:
return False
....
def test_5_is_not_lower_than_5(self):
self.assertFalse(is_lower_than_5(5))
The above test would pass even though it should fail. It is missing an error in the code that should be caught.
How should we assert that the value is literally False
and not merely false in a boolean context? e.g.
self.assertEquals(False, None) # assert fails. good!
回答1:
None
is falsy, as well as 0
, ""
, []
, ...
assertFalse
does not check whether the given value is False
by identity. This behavior is consistent with the if
statement:
if not None:
print('falsy value!')
Similarly, assertTrue
does not check whether a value is True
, and as such values like 1
, "abc"
, [1, 2, 3]
pass the test. See Truth Value Testing for more information.
This behavior is also explicitly documented:
assertTrue(expr, msg=None) assertFalse(expr, msg=None)Test that expr is true (or false).
Note that this is equivalent to
bool(expr) is True
and not toexpr is True
If you really want to be sure that a value is True
or False
, use assertIs.
回答2:
Your case is actually pointed out in the documentation:
Note that this is equivalent to bool(expr) is True and not to expr is True (use assertIs(expr, True) for the latter).
Source: https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertFalse
回答3:
Python default return value for functions is None
.
Python also implements Duck typing, so some values are threated as falsey, those are
- empty string
- integer zero
- boolean False
- empty list
- empty tuple
So yes, you should implement it as self.assertEquals(False, None)
if you want to explicitly check the False
boolean value. This is not a good idea, in python you can just do
if my_value:
print 'truthy value'
else:
print 'falsey value'
You could design your test cases using boundary-value analysis to check your corner cases.
来源:https://stackoverflow.com/questions/35038519/python-unittest-successfully-asserts-none-is-false