杰瑞科技汇

Appium Python中assert断言如何正确使用?

Of course! Using assert statements is a fundamental part of writing robust and maintainable Appium tests with Python. They act as checkpoints in your test script, verifying that the application's state or behavior matches your expectations.

Appium Python中assert断言如何正确使用?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the basics, best practices, and advanced examples.


The Core Idea: Why Use assert?

An assert statement is a sanity check. It checks if a given condition is True. If it is, the code continues to run. If it's False, the test script immediately stops and raises an AssertionError, which your test runner (like pytest or unittest) will flag as a FAILED test.

Basic Syntax:

assert condition, "Optional error message"
  • condition: An expression that evaluates to True or False.
  • "Optional error message": A string that is displayed in the traceback if the assertion fails. This is incredibly helpful for debugging.

Basic assert Examples in Appium Tests

Let's imagine you have a standard Appium test setup.

Appium Python中assert断言如何正确使用?-图2
(图片来源网络,侵删)
# conftest.py or a common setup file
from appium import webdriver
from appium.options.android import UiAutomator2Options
def setup_driver():
    capabilities = {
        "platformName": "Android",
        "deviceName": "Pixel_4_API_30",
        "app": "/path/to/your/app.apk",
        "automationName": "UiAutomator2"
    }
    options = UiAutomator2Options().load_capabilities(capabilities)
    driver = webdriver.Remote("http://localhost:4723/wd/hub", options)
    return driver
# test_example.py
import pytest
from appium.webdriver.common.appiumby import AppiumBy
# Assuming setup_driver is available
# driver = setup_driver()
def test_login_screen_elements(driver):
    """
    Test that all elements on the login screen are present.
    """
    # --- Example 1: Assert an element is found ---
    # This is the most common use case. We find an element and assert it's not None.
    # Find the username field
    username_field = driver.find_element(AppiumBy.ID, "com.example.app:id/username_field")
    assert username_field is not None, "Username field was not found on the login screen!"
    # Find the password field
    password_field = driver.find_element(AppiumBy.ID, "com.example.app:id/password_field")
    assert password_field is not None, "Password field was not found on the login screen!"
    # Find the login button
    login_button = driver.find_element(AppiumBy.ID, "com.example.app:id/login_button")
    assert login_button is not None, "Login button was not found on the login screen!"
    print("All login screen elements are present.")
def test_successful_login(driver):
    """
    Test a successful login flow and assert the result.
    """
    # 1. Find elements and interact with them
    username_field = driver.find_element(AppiumBy.ID, "com.example.app:id/username_field")
    password_field = driver.find_element(AppiumBy.ID, "com.example.app:id/password_field")
    login_button = driver.find_element(AppiumBy.ID, "com.example.app:id/login_button")
    username_field.send_keys("standard_user")
    password_field.send_keys("secret_sauce")
    login_button.click()
    # 2. Assert that we have navigated to the correct screen
    # We can do this by checking for a unique element on the home/dashboard screen.
    # Wait for the home screen to be visible (best practice!)
    from appium.webdriver.common.by import By
    from appium.webdriver.support.ui import WebDriverWait
    from appium.webdriver.support import expected_conditions as EC
    home_page_title = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((AppiumBy.ID, "com.example.app:id/home_page_title"))
    )
    # --- Example 2: Assert an element's text ---
    expected_title = "Welcome"
    actual_title = home_page_title.text
    assert actual_title == expected_title, f"Expected title to be '{expected_title}', but got '{actual_title}'"
    # --- Example 3: Assert an element's attribute ---
    # For example, check if the home page title is displayed
    assert home_page_title.is_displayed(), "Home page title is not displayed after login."
    # --- Example 4: Assert a condition based on element presence ---
    # Check that the logout button is now visible
    logout_button = driver.find_element(AppiumBy.ID, "com.example.app:id/logout_button")
    assert logout_button.is_displayed(), "Logout button is not visible on the home page."
    print("Login successful and home page is verified.")

Best Practices for Using assert in Appium

a. Use Explicit Waits with assert

Never assert on an element that you just found without waiting. The element might be in the process of loading, leading to a flaky test that fails intermittently.

Bad (Flaky):

login_button.click()
# The dashboard might not be ready yet!
dashboard_title = driver.find_element(By.ID, "dashboard_title")
assert dashboard_title.text == "Dashboard" # Might fail

Good (Robust):

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
login_button.click()
# Wait up to 10 seconds for the element to be visible
dashboard_title = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.ID, "dashboard_title"))
)
# Now you can safely assert
assert dashboard_title.text == "Dashboard"

b. Provide Clear, Descriptive Error Messages

When an assert fails, the default message can be cryptic. A custom message tells you exactly what went wrong.

Appium Python中assert断言如何正确使用?-图3
(图片来源网络,侵删)

Bad:

assert dashboard_title.text == "Dashboard"
# Failure: AssertionError

Good:

assert dashboard_title.text == "Dashboard", f"Expected dashboard title to be 'Dashboard', but the element's actual text was '{dashboard_title.text}'."
# Failure: AssertionError: Expected dashboard title to be 'Dashboard', but the element's actual text was 'Home'.

c. Use Page Object Model (POM) for Readability

Instead of hard-coding By locators in your test files, use the Page Object Model. This separates locators and test logic, making tests easier to read and maintain.

login_page.py

class LoginPage:
    def __init__(self, driver):
        self.driver = driver
    # Locators
    USERNAME_FIELD = (AppiumBy.ID, "com.example.app:id/username_field")
    PASSWORD_FIELD = (AppiumBy.ID, "com.example.app:id/password_field")
    LOGIN_BUTTON = (AppiumBy.ID, "com.example.app:id/login_button")
    ERROR_MESSAGE = (AppiumBy.ID, "com.example.app:id/error_message")
    def login(self, username, password):
        self.driver.find_element(*self.USERNAME_FIELD).send_keys(username)
        self.driver.find_element(*self.PASSWORD_FIELD).send_keys(password)
        self.driver.find_element(*self.LOGIN_BUTTON).click()
    def get_error_text(self):
        return self.driver.find_element(*self.ERROR_MESSAGE).text

test_login.py

def test_invalid_login_shows_error(driver):
    login_page = LoginPage(driver)
    login_page.login("bad_user", "bad_password")
    error_text = login_page.get_error_text()
    assert "Invalid credentials" in error_text, f"Expected error message to contain 'Invalid credentials', but got: '{error_text}'"

Advanced assert Techniques

Sometimes, a simple comparison isn't enough. Here are some more advanced assertions.

a. Asserting on Multiple Elements

What if you want to check that a list of all items on a screen matches an expected list?

# Get all product name elements
product_elements = driver.find_elements(AppiumBy.ID, "com.example.app:id/product_name")
actual_products = [el.text for el in product_elements]
# Define the expected list
expected_products = ["Sauce Labs Backpack", "Sauce Labs Bike Light", "Sauce Labs Bolt T-Shirt"]
# Assert the lists are equal
assert actual_products == expected_products, \
    f"Product list mismatch.\nExpected: {expected_products}\nActual: {actual_products}"

b. Asserting on Element Attributes (other than text)

You can check any attribute of a web element, like enabled, selected, or even content-desc.

# Assume we have a checkbox
checkbox = driver.find_element(AppiumBy.ID, "terms_and_conditions_checkbox")
# Assert that the checkbox is NOT enabled (disabled)
assert not checkbox.is_enabled(), "The checkbox should be disabled initially."
# Click it and assert it's now enabled
checkbox.click()
assert checkbox.is_enabled(), "The checkbox should be enabled after being clicked."

c. Using pytest.raises for Negative Testing

Sometimes you want to assert that an error occurs. For example, you expect an app to crash or an invalid action to be prevented. pytest makes this easy.

import pytest
def test_app
分享:
扫描分享到社交APP
上一篇
下一篇