Search code examples
pythonassert

What does the assert statement do?


I am new to Selenium. I am trying to understand what an assert statement does.

In the code mentioned below, I could not point out the reasons for its existence (the third line).

driver = webdriver.Chrome('./data/chromedriver.exe') 
driver.get("http://www.python.org") 
assert "Python" in driver.title

Solution

  • You are obviously using Selenium together with Python. Anyway, the assert keyword can be found in many programming languages.

    For a language independent explanation of assert, have a look at Wikipedia:

    In computer programming, specifically when using the imperative programming paradigm, an assertion is a predicate (a Boolean-valued function over the state space, usually expressed as a logical proposition using the variables of a program) connected to a point in the program, that always should evaluate to true at that point in code execution. Assertions can help a programmer read the code, help a compiler compile it, or help the program detect its own defects.

    For the latter, some programs check assertions by actually evaluating the predicate as they run. Then, if it is not in fact true – an assertion failure –, the program considers itself to be broken and typically deliberately crashes or throws an assertion failure exception.

    The official Python documentation for assert can be found here:

    https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement

    assert is in fact not a function, but a statement. It is a check that a certain condition holds. If not, the program will fail to run in some way. In the Python case, an AssertionError will be raised:

    if __debug__:
        if not expression: raise AssertionError
    

    More specifically, the assertion in your question will fail if Python can not be found in the title of the http://www.python.org page.