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.
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.
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.
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()
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.
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:
|
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.
The assert statement uses the get_attribute() method to validate the inputted data and raises an AssertionError when the data is incorrect.
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.
Test Execution:
As explained earlier, this is the AssertionError obtained from the test case. It indicates that the email address is not valid.
Since we run tests on the LambdaTest platform, go to the Web Automation Dashboard to view the test execution results.
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:
|
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”.
Test Execution:
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:
|
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.
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.
If the ID exists, the test passes; otherwise, it raises an AssertionError or an assert False statement.
Test Execution:
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:
|
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”.
The test_element_presence() function uses the ID locator within the find_element() method to search for the cart-total-drawer ID.
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.
Test Execution:
Note : Run Python unit tests across 3000+ real environments. Try LambdaTest Now!
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:
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.
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.
Did you find this page helpful?
Try LambdaTest Now !!
Get 100 minutes of automation test minutes FREE!!