杰瑞科技汇

Python AirTest如何连接MySQL数据库?

Of course! Using Python, Airtest, and MySQL together is a very powerful combination, especially for automated testing in a CI/CD environment. Here's a comprehensive guide covering the concepts, setup, and a complete practical example.

Python AirTest如何连接MySQL数据库?-图1
(图片来源网络,侵删)

The Big Picture: Why Combine Them?

You typically use this stack for automated UI regression testing where you need to:

  1. Automate UI Testing: Airtest drives a mobile app (Android/iOS) or a desktop application to perform a sequence of user actions (clicks, swipes, text input).
  2. Manage Test Data & Store Results: MySQL acts as a reliable backend to:
    • Store test data (e.g., usernames, passwords, product IDs) that your tests will use.
    • Log test execution results (pass/fail, screenshots, error messages, timestamps) in a structured way.
    • Generate reports by querying the database.

The general workflow looks like this:

Python Script -> (uses airtest.core.api to control the app) -> (uses mysql-connector-python to talk to the database) -> MySQL Database


Step 1: Prerequisites

  1. Python: Installed on your system.
  2. Airtest: Install it via pip.
    pip install airtest
  3. AirtestIDE: Highly recommended for creating and debugging your Airtest scripts visually. Download it from the official Airtest website.
  4. MySQL Server: You need a running MySQL server. You can install it locally or use a cloud service like AWS RDS, Google Cloud SQL, or a Docker container.
  5. MySQL Connector for Python: Install the official driver.
    pip install mysql-connector-python

Step 2: Database Setup

First, let's set up a database and a table to store our test results.

Python AirTest如何连接MySQL数据库?-图2
(图片来源网络,侵删)
  1. Log in to your MySQL server.

  2. Create a database and a user for your tests.

    CREATE DATABASE airtest_reports;
    CREATE USER 'airtest_user'@'localhost' IDENTIFIED BY 'your_strong_password';
    GRANT ALL PRIVILEGES ON airtest_reports.* TO 'airtest_user'@'localhost';
    FLUSH PRIVILEGES;
  3. Switch to the new database and create a table to log test runs.

    USE airtest_reports;
    CREATE TABLE test_results (
        id INT AUTO_INCREMENT PRIMARY KEY,
        test_name VARCHAR(255) NOT NULL,
        status ENUM('PASSED', 'FAILED') NOT NULL,
        start_time DATETIME NOT NULL,
        end_time DATETIME,
        duration_seconds INT,
        error_message TEXT,
        screenshot_path VARCHAR(512)
    );
    • test_name: Name of your test script.
    • status: Whether the test passed or failed.
    • start_time / end_time: To calculate duration.
    • error_message: Details of any assertion failures.
    • screenshot_path: Path to a screenshot taken on failure.

Step 3: The Python Script (Combining Airtest and MySQL)

Here is a complete Python script that demonstrates the full workflow. This script will:

Python AirTest如何连接MySQL数据库?-图3
(图片来源网络,侵删)
  1. Connect to MySQL.
  2. Start a timer.
  3. Use Airtest to perform a simple UI action (open a calculator app and click a button).
  4. Assert a result.
  5. Log the result (pass/fail, duration, etc.) into the MySQL database.
  6. Close the connection.

Important: For this example to work, you need to have an Android Emulator or a physical Android device connected with "USB Debugging" enabled. We'll use the built-in Android Calculator app.

test_mysql_logging.py

import time
import datetime
import airtest.core.api as air
from airtest.core.api import assert_exists, touch
from mysql.connector import Error, connect
# --- MySQL Configuration ---
DB_CONFIG = {
    'host': 'localhost',
    'user': 'airtest_user',
    'password': 'your_strong_password',
    'database': 'airtest_reports'
}
def get_db_connection():
    """Establishes and returns a new database connection."""
    try:
        conn = connect(**DB_CONFIG)
        print("Successfully connected to MySQL database")
        return conn
    except Error as e:
        print(f"Error while connecting to MySQL: {e}")
        return None
def log_test_result(conn, test_name, status, start_time, end_time, error_msg=None, screenshot_path=None):
    """Logs the result of a test run into the MySQL database."""
    if not conn:
        print("Cannot log result: No database connection.")
        return
    cursor = conn.cursor()
    # Calculate duration
    duration = int((end_time - start_time).total_seconds())
    try:
        query = """
        INSERT INTO test_results (test_name, status, start_time, end_time, duration_seconds, error_message, screenshot_path)
        VALUES (%s, %s, %s, %s, %s, %s, %s)
        """
        cursor.execute(query, (test_name, status, start_time, end_time, duration, error_msg, screenshot_path))
        conn.commit()
        print(f"Successfully logged result for '{test_name}' to MySQL.")
    except Error as e:
        print(f"Failed to log result to MySQL: {e}")
    finally:
        cursor.close()
def main():
    # --- Test Configuration ---
    TEST_NAME = "test_calculator_addition"
    DEVICE = "Android" # Connects to the first available Android device/emulator
    # Connect to the database once
    db_connection = get_db_connection()
    if not db_connection:
        return # Exit if we can't connect to the DB
    # --- Start Test Execution ---
    start_time = datetime.datetime.now()
    print(f"--- Starting Test: {TEST_NAME} at {start_time} ---")
    try:
        # 1. Connect to the mobile device using Airtest
        air.connect_device(DEVICE)
        print("Connected to Android device.")
        # 2. Perform UI Actions (Example: Calculator App)
        # Note: You must use the Airtest IDE to get the correct UI coordinates for your device/app
        # For this example, we'll use a generic approach. You'll need to adapt these.
        # Launch the calculator app (you might need the package name)
        # air.start_app("com.android.calculator2")
        # Tap on '5' button
        touch((200, 800)) # Example coordinates for '5'
        # Tap on '+' button
        touch((400, 800)) # Example coordinates for '+'
        # Tap on '3' button
        touch((200, 1000)) # Example coordinates for '3'
        # Tap on '=' button
        touch((600, 1000)) # Example coordinates for '='
        # 3. Assert the result (e.g., check if '8' is displayed)
        # This is a placeholder assertion. In a real scenario, you'd check for the result text.
        # For now, we'll just force a success or failure for demonstration.
        # assert_exists(air.Template("resource/calculator/8.png")) # Use a real image from Airtest IDE
        # Let's simulate a test that passes
        print("Test assertions passed.")
        test_status = "PASSED"
        error_message = None
        screenshot_path = None
    except Exception as e:
        # 4. If an assertion fails or any other error occurs
        print(f"Test FAILED with error: {e}")
        test_status = "FAILED"
        error_message = str(e)
        # Take a screenshot on failure for evidence
        screenshot_filename = f"{TEST_NAME}_failure_{int(time.time())}.png"
        air.screenshot(screenshot_filename)
        screenshot_path = screenshot_filename
        print(f"Screenshot saved to: {screenshot_path}")
    finally:
        # --- End Test Execution ---
        end_time = datetime.datetime.now()
        print(f"--- Ending Test: {TEST_NAME} at {end_time} ---")
        # 5. Log the final result to MySQL
        log_test_result(
            conn=db_connection,
            test_name=TEST_NAME,
            status=test_status,
            start_time=start_time,
            end_time=end_time,
            error_message=error_message,
            screenshot_path=screenshot_path
        )
        # 6. Clean up
        air.disconnect_device()
        if db_connection and db_connection.is_connected():
            db_connection.close()
            print("MySQL connection is closed.")
if __name__ == "__main__":
    main()

How to Run the Script

  1. Adapt Coordinates: The touch() coordinates in the script are examples. You must use the Airtest IDE to connect to your device, click the "Record" button, perform the actions, and then copy the generated Python code. This will give you the correct coordinates or template matching code for your specific screen resolution and app.
  2. Update MySQL Config: Change the DB_CONFIG dictionary in the script with your actual MySQL host, user, password, and database name.
  3. Execute: Run the script from your terminal
分享:
扫描分享到社交APP
上一篇
下一篇