Python: Automated testing
Theory: Assertions
Each check we have written for the capitalize() function is commonly referred to in testing as a statement. We'll learn more about this concept in this lesson.
What is a statement
Assertions are an integral part of tests. They are the ones that check the functionality of your code:
You may notice that all the checks follow the same structure — they have two components:
- Condition
- Exception if the condition isn't true
The function suggests calling itself here, but you don't have to. Python already includes a dedicated `assert' construct that does the same thing.
The assert construct looks like a function, but it isn't. It is a specific language statement that takes as input an expression whose value must be True, or else an exception occurs. Therefore, all the checks in the tests are inverted:
In such tests, assert true means everything is fine, and assert false indicates an error. The latter is that if the capitalize() function doesn't work correctly, it throws an exception with the following message:
Here's the actual statement that threw the exception. Besides the message, there is a backtrace that you can use to find the statement.