Register to get access to free programming courses with interactive exercises

Assertions Python: Automated testing

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:

from capitalize import capitalize

if capitalize('hello') != 'Hello':
    raise Exception('The function is not working correctly!')

if capitalize('') != '':
    raise Exception('The function is not working correctly!')

print('All tests are passed!')

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:

from capitalize import capitalize

assert capitalize('') == ''
assert capitalize('hello') == 'Hello'

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:

    Traceback (most recent call last):
      File "main.py", line 11, in <module>
        assert capitalize('hello') == 'Hello'
    AssertionError

Here's the actual statement that threw the exception. Besides the message, there is a backtrace that you can use to find the statement.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY