-2

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
AMC
  • 2,642
  • 7
  • 13
  • 35
surya098
  • 11
  • 1
  • 1
    Does this answer your question? [What is the use of "assert" in Python?](https://stackoverflow.com/questions/5142418/what-is-the-use-of-assert-in-python) – AMC Aug 28 '20 at 07:49

2 Answers2

2

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.

Magnilex
  • 11,584
  • 9
  • 62
  • 84
0

The assert keyword is used to compare the actual result with expected result. Mostly comes in use for validating.

For eg : If you are testing some URL, you may validate the title

assert actual_title == expected_title

If the value matches then test case passes, otherwise test case fails giving you an AssertionError