Python assertTrue() Function
The assertTrue() function is part of the unittest module. As the name suggests, it allows you to test if an expression is True or false.
The function syntax is as shown:
If the expression evaluates to True, the test is considered passed; otherwise, the test is considered fail.
You can also include the optional message parameter which defines a custom message if the test fails.
Example 1
The following example shows how to test if the value of a given string value is in ASCII.
class TestBool(unittest.TestCase):
def test_if_string(self):
var = 'geekbits.io'
self.assertTrue(var.isascii())
The code above test if the given input string is an ASCII string. Since the value is true, the test passes as shown:
Output:
-------------------------------------------------------------
Ran 1 test in 0.000s
OK
Example 2
In the example below, the test fails as the input string is not in ASCII characters.
class TestBool(unittest.TestCase):
def test_if_string(self):
var = '大'
self.assertTrue(var.isascii())
Running the test above should fail as shown:
==========================================================
FAIL: test_if_string (bool_test.TestBool)
--------------------------------------------------------------
Traceback (most recent call last):
File “./bool_test.py", line 6, in test_if_string
self.assertTrue(var.isascii())
AssertionError: False is not true
--------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
As we can see, the function returns False as the string is not ASCII characters.
Example 3
We can also include a custom message if the test fails using the msg parameter. An example code is as shown:
class TestBool(unittest.TestCase):
def test_if_string(self):
var = '大'
self.assertTrue(var.isascii(), msg="String is not ASCII")
Running the test above should return:
FAIL: test_if_string (bool_test.TestBool)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./bool_test.py", line 6, in test_if_string
self.assertTrue(var.isascii(), msg="String is not ASCII")
AssertionError: False is not true : String is not ASCII
--------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
Conclusion
In this post, you learned how to use the assertTrue() function to test if a given expression evaluates to True.