mercredi 27 janvier 2016

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!

Aucun commentaire:

Enregistrer un commentaire