assertTrue & assertFalse
assertTrue(expr) checks that an expression is truthy, while
assertFalse(expr) checks that it is falsy. These are useful for boolean
conditions and custom checks.
Basic Usage
import unittest
class TestBoolean(unittest.TestCase):
def test_is_active(self):
user = {"active": True}
self.assertTrue(user["active"])
def test_is_empty(self):
cart = []
self.assertFalse(len(cart) > 0)
def test_string_truthy(self):
self.assertTrue("non-empty string")
def test_none_falsy(self):
self.assertFalse(None)
def test_zero_falsy(self):
self.assertFalse(0)
def test_empty_dict_falsy(self):
self.assertFalse({})
With Custom Messages
def test_user_verified(self):
user = get_user("alice")
self.assertTrue(
user.is_verified,
f"User {user.name} should be verified"
)
def test_payment_not_processed(self):
order = create_order()
self.assertFalse(
order.is_paid,
"Order should not be paid until confirmation"
)
Truthy vs True
assertTrue checks for truthiness, not strict equality to True.
Non-empty strings, non-zero numbers, and non-empty collections all evaluate as truthy.
self.assertTrue(1) # passes: 1 is truthy
self.assertTrue("yes") # passes: non-empty string
self.assertTrue([1]) # passes: non-empty list
self.assertTrue(True) # passes: True is truthy
Key Takeaway
Use assertTrue and assertFalse to verify boolean conditions.
They check truthiness, not strict identity with True/False.