Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unittest successfully asserts None is False

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!
like image 261
icedtrees Avatar asked Jan 27 '16 13:01

icedtrees


People also ask

What does unittest main () do?

Internally, unittest. main() is using a few tricks to figure out the name of the module (source file) that contains the call to main() . It then imports this modules, examines it, gets a list of all classes and functions which could be tests (according the configuration) and then creates a test case for each of them.

Is PyUnit the same as unittest?

Yes. unittest is a xUnit style frameworkfor Python, it was previously called PyUnit.

How do you assert an empty list in Python?

Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument. Other methods you can use to check if a list is empty are placing it inside an if statement, using the len() methods, or comparing it with an empty list.


1 Answers

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 to expr is True

If you really want to be sure that a value is True or False, use assertIs.

like image 65
Andrea Corbellini Avatar answered Sep 22 '22 13:09

Andrea Corbellini