• Automation, Selenium, Python, Tutorial
  • Home
  • /
  • Learning Hub
  • /
  • Python Assert Keyword: A Complete Guide
  • -
  • August 09, 2024

Python Assert Keyword: A Complete Guide

Learn how to use Python assert statements for debugging and testing by ensuring conditions hold true in your code, improving reliability and quality.

OVERVIEW

Python assert keyword verifies expected outcomes or certain true conditions within specific points during code execution. For example, in web automation testing, the assert statement can be used to validate elements and functionalities of a web application.

Assertions are useful for documenting, debugging, and testing code during development. After using assertions to debug and test your code, you can disable them after moving the code to the live environment.

What Are Asserts in Python?

An assert statement in Python determines if a particular condition in your code returns true; otherwise, it will throw an AssertionError. Python assert is a built-in construct that is supposed to be accurate and to continue the execution of the code; otherwise, it stops execution and throws an error.

Syntax:

assert condition, message

Condition: The condition is the value you are trying to evaluate. When the condition evaluates as true, no action is taken. If it evaluates to false, an AssertionError is raised.

Message: The message displays when the assert statement is evaluated as false.

assert-statement-is-evaluated-as-false

In this code example, the AssertExamples class fetches the page, compares the page titles to ensure they are correct, and raises an AssertionError if it is not:

class AssertExamples(SampleTest):
  def test_page_title(self):
      driver = self.driver
      driver.get("https://lambdatest.github.io/sample-todo-app/")

          # Use the `assert` statement to verify if the page title is correct
      if driver.title == "To-do app":
          self.assertFalse(False, "Page title is correct")
      else:
          self.assertFalse(True, "Page title is incorrect")

      driver.close()

This example fetches the LambdaTest Sample App. Here, the title on the web page is LambdaTest Sample App instead of the todo app, which will cause an AssertionError.

assertionerror-pytest

Use Cases of Python Asserts With Selenium

In this section, let’s explore real-world use cases of Python asserts with the Selenium Remote WebDriver using online Selenium Grid. While testers commonly use asserts for debugging and writing unit tests, several use cases exist. They can verify the accuracy of website data, validate data submitted to a website, and fulfill various other functions.

To demonstrate use cases on Remote WebDriver, let’s use the online Selenium Grid offered by cloud testing platforms like LambdaTest. It is an AI-powered test execution platform that lets you perform Selenium Python testing across numerous desktop browsers. For this, we will use the LambdaTest eCommerce Playground.

...

With the LambdaTest platform, you do not need to be locally installed; instead, you can use the LambdaTest Automation Capabilities Generator to configure the test settings on the LambdaTest cloud grid.

To test these use cases on the LambdaTest cloud grid, you can add the code to a base.py file within your project’s directory.

import os
import unittest
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.edge.options import Options as EdgeOptions
from selenium.webdriver.common.by import By

username = os.environ.get("LT_USERNAME")
access_key = os.environ.get("LT_ACCESS_KEY")


class SampleTest(unittest.TestCase):

    # setUp runs before each test case
    def setUp(self):
        lt_options = {
            "user": username,
            "accessKey": access_key,
            "build": "Python Asserts Tests with Selenium",
            "name": "Python Asserts Tests with Selenium",
            "platformName": "Windows 11",
            "w3c": True,
            "browserName": "Chrome",
            "browserVersion": "latest",
            "selenium_version": "latest",
        }
        
        browser_options = ChromeOptions()
        browser_options.set_capability('LT:Options', lt_options)

        self.driver = webdriver.Remote(
            command_executor=f"https://{username}:{access_key}@hub.lambdatest.com/wd/hub",
            options=browser_options)


if __name__ == "__main__":
    unittest.main()
LambdaTest

To get the Username and Access Key, go to the LambdaTest Dashboard, then navigate to Settings > Account Settings > Password & Security and add these credentials to your .env file.

Input Validation Using Python Asserts

In this use case, we will verify the correctness of input data to ensure it passes the validation criteria in the assert statements.

Test Scenario:

  • Launch the LambdaTest eCommerce Playground website.
  • Locate the email and password fields.
  • Click on the Login button to send the data.

Implementation:

In the validation process, certain conditions, such as data type, format, and range, must adhere to specific rules. If the input fails to meet these requirements, the test script raises an AssertionError.

For instance, providing non-email data to an email address data type would trigger an AssertionError. This process ensures the integrity and accuracy of the data.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

from base import SampleTest
import unittest


class InputValidation(SampleTest):
   def test_email_password(self):

       driver = self.driver
       driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=account/login")

       try:
           # Find the email and password fields
           email = driver.find_element(By.ID, "input-email")
           password = driver.find_element(By.ID, "input-password")

           # Input some test data
           email.send_keys("testexample.com")
           password.send_keys("testpassword")

           # Validate the input
           assert "@" in email.get_attribute("value"), "Invalid email address"
           assert len(password.get_attribute("value")) > 0, "Password field is empty"

           # Find and click the login button
           login_button = driver.find_element(By.CSS_SELECTOR, "input.btn.btn-primary")
           login_button.click()

       except NoSuchElementException as e:
           print(f"An error occurred: {e}")

       finally:
           driver.quit()

if __name__ == "__main__":
   unittest.main()

    driver.quit()

Code Walkthrough:

Once the document under test has loaded, we use the find_element() method in Selenium to locate the email address and password fields; then, we pass the data to these fields using the ID locator to the send_keys() method.

send-keys-method

The assert statement uses the get_attribute() method to validate the inputted data and raises an AssertionError when the data is incorrect.

get_attribute()-pytest

Finally, it uses the CSS_Selector within the find_element() method to log in and send the data. Since an “@” was omitted in the code, it will raise an AssertionError.

CSS_Selector within the find_element-pytest

Test Execution:

As explained earlier, this is the AssertionError obtained from the test case. It indicates that the email address is not valid.

assertionerror-obtained-from-the-test-case

Since we run tests on the LambdaTest platform, go to the Web Automation Dashboard to view the test execution results.

LambdaTest-platform-pytest

Data Integrity Checks Using Python Asserts

In this use case, we will check if the element or data defined within the website is as it should be; this ensures it meets the check's accuracy of the data in the assert statements.

Test Scenario:

  • Launch the LambdaTest eCommerce Playground website
  • Validate the title on the eCommerce Playground website.

Implementation:

For instance, this use case checks if the website title is the same as the string defined within the code by passing data, “Your Store” to compare the website title to ensure data integrity.

from selenium import webdriver
from base import SampleTest
import unittest


class DataIntegrityTest(SampleTest):
  def test_data_integration(self):
    driver = self.driver
      driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=common/home")

    assert "Your Store" in driver.title, "Website title is not as expected"

if __name__ == "__main__":
    unittest.main()


Code Walkthrough:

Once the document under test is fully loaded, we get the website title and use the assert statement to validate that the website title is the same as defined on the code, “Your Store”.

Python script validating website title for data integrity using asserts

Test Execution:

Validating eCommerce website title with assert statement

Debugging Using Python Asserts

Python assert statements let developers include self-checking within the statements, which helps identify errors during the test process by raising an AssertionError when the specific condition is unmet.

Test Scenario:

  • Launch the LambdaTest eCommerce Playground website.
  • Locate the element using an ID locator.
  • Validate the element that exists within the eCommerce Playground website.

Implementation:

The below test script automates a browser to open a specific web page of the LambdaTest eCommerce Playground and verify the presence and content of a specific element.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from base import SampleTest
import unittest

class DebugTest(SampleTest):
    def test_element_exists(self):
        self.driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=common/home")

        try:
            element = self.driver.find_element(By.ID, "mz-component")
            self.assertIn("expected text", element.text)
        except NoSuchElementException:
            assert False, "Element not found"

if __name__ == "__main__":
    unittest.main()

Code Walkthrough:

Once the website under test is fully loaded, we use the ID locator within the find_element() method to search for an ID.

Selenium test script for verifying element on LambdaTest eCommerce site

Next, pass the ID as a text using the assertIn() function; then, we use the NoSuchElementException method to validate that the ID exists on the website.

assertIn() and NoSuchElementException code example

If the ID exists, the test passes; otherwise, it raises an AssertionError or an assert False statement.

Test Execution:

Test Execution Assertion Check Image

Unit Testing Using Python Asserts

You can also use assert statements while performing Python unit testing to verify methods and functions that execute a specific output for a given input.

Test Scenario:

  • Launch the LambdaTest eCommerce Playground website.
  • Validate the title of the eCommerce Playground website.
  • Relaunch the eCommerce Playground website.
  • Locate an ID.
  • Validate that the ID exists.

Implementation:

The below test script is a unit test for a web page to automate the browser. It includes tests for the page title and the presence of a specific element.

import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

from base import SampleTest

class TestHomePage(SampleTest):

    def test_title(self):
        driver = self.driver
        driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=common/home")
        assert "Your Store" in self.driver.title, "Website title is not as expected"
    
    def test_element_presence(self):

      driver = self.driver

      driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=common/home")

      try:
          element = self.driver.find_element(By.ID, "cart-total-drawer")
          self.assertTrue(element is not None, "Element not found")
      except NoSuchElementException:
          assert False, "Element not found"

    def tearDown(self):
        self.driver.quit()

if __name__ == "__main__":
    unittest.main()

Code Walkthrough:

Once the website under test has loaded, we get the website title and use the assert statement to validate that the website title is the same as defined on the code, “Your Store”.

Python unit test script example using assert statements to validate page title and element presence on a web page.

The test_element_presence() function uses the ID locator within the find_element() method to search for the cart-total-drawer ID.

search-cart-total-drawer-id-using-find-element-method

We use the assertTrue() method to validate that if the element ID is not none, then we use the NoSuchElementException method to validate that the ID exists on the website. If it does, it passes; if not, it raises an AssertionError or an assert False statement.

assertTrue method validating element ID existence

Test Execution:

assertTrue ID validation test execution
Note

Note : Run Python unit tests across 3000+ real environments. Try LambdaTest Now!

When Should You Use Assertions?

Assertions can not be used in every scenario; specific scenarios include debugging, validating data, or test cases.

Following are some of the scenarios when you should use assertions:

Debugging or Troubleshooting

During the development phase, Python assert statements can detect issues within the codebase. Using these statements in your code lets you quickly pinpoint or identify problematic functions, diagnose a bug, and resolve the issue easily. Once the issue has been resolved, you can remove the assert statements.

Pre-Conditions/Post-Conditions

Preconditions and postconditions are conditions or requirements that must be true for a function or method to execute correctly. Preconditions enforce a state where the conditions must be satisfied before the function or method is executed, while postconditions are the opposite of preconditions; they guarantee the outcome of the function or method once executed successfully.

Implementation:

Consider a scenario where we navigate Google’s homepage and make a search query.

In this scenario, we would have two functions: set_up_browser_precondition(), which resizes the browser window to meet a specific dimension, and the validate_searched_term_postcondition(), which confirms the search query matches the expectation query.

# Function to handle the precondition of having the browser maximized

def set_up_browser_precondition():
    driver = webdriver.Chrome()
    driver.maximize_window()
    width = driver.get_window_size().get("width")
    height = driver.get_window_size().get("height")
    while width < 1024 or height < 768:
        driver.maximize_window()
        width = driver.get_window_size().get("width")
        height = driver.get_window_size().get("height")
    print("Browser Window Resolution Verified.")
    return driver

# Function to handle the postcondition of validating the searched term
def validate_searched_term_postcondition(driver, search_term):
    driver.get("https://www.google.com")
    search_box = driver.find_element(By.NAME, 'q')
    search_box.clear()
    search_box.send_keys(search_term)
    search_box.submit()  # Submit the form
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//h3[contains(., '{}')]".format(search_term))))
    print(f"Searched term '{search_term}' verified.")

if __name__ == "__main__":
    driver = set_up_browser_precondition()
    validate_searched_term_postcondition(driver, "Python Programming Language")
    driver.quit()

Code Walkthrough:

The set_up_browser_precondition() function opens the Google web page and resizes it to fit a 1024 x 768 pixels display before carrying out the search query. It ensures that it fulfills the requirements needed for the search interaction.

The validate_searched_term_postcondition() function loads the Google homepage, retrieves a search box element using an attribute, ‘q’, and clears the search context. Next, it waits ten seconds for an h3 tag containing the search term using WebDriverWait and an explicit wait condition. Once the element is found, it prints the success message, which tells us that the postcondition has passed.

Test Execution:

preconditions-and-postconditions

Assertions can also be used to write preconditions and postconditions during the development of your code. Developers often place preconditions at the beginning of functions to validate inputs into the function and postconditions before the function's return value to ensure the output corresponds to the required.

Validation of Test Scenarios

Assert statements also come in handy for writing test cases in your code during development. You can write precise test cases because assertions provide a way to test whether a condition checks out.

Although assertions are very helpful during development, relying on them for error handling in production is not advisable because assertions can be enabled or disabled dynamically depending on command line options; consider implementing unique error-handling mechanisms throughout your application.

To learn more about assertions, check out this blog on assert and verify in Selenium WebDriver.

You can also subscribe to the LambdaTest YouTube Channel to get tutorials around assertions.

Conclusion

To sum it up, Python asserts can be used for debugging, ensuring correct value inputs, unit test cases, and verifying the accuracy of the data sent. This blog discussed the use cases of Python assert, when and when not to use assert statements, and its different types using real-world examples.

Frequently asked questions

  • General ...
What is assert() in Python?
The assert() method is used for debugging that tests a condition. If the condition is false, it raises an AssertionError with an optional error message.
Should I use assert in Python?
Yes, you can use assert for debugging purposes, but avoid using it for runtime error handling in production code.
What does assert() do?
The assert() method checks if a given condition is true and if not, it raises an AssertionError, optionally displaying a custom error message.

Did you find this page helpful?

Helpful

NotHelpful

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud