Operations 13 min read

Can AI‑Generated Scripts Run Your Tests? 4 Real‑World Python Scenarios

This guide shows how to quickly set up a Python environment and use AI‑generated prompts to create fully functional test scripts for web login, API order creation, mobile settings navigation, and database verification, complete with installation commands, code snippets, execution steps, and debugging tips.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Can AI‑Generated Scripts Run Your Tests? 4 Real‑World Python Scenarios

Introduction

This article demonstrates how to use AI‑generated prompts to produce ready‑to‑run Python test scripts for four common testing scenarios: web UI login, API order creation, mobile app interaction, and database verification. Each script is accompanied by setup instructions, execution commands, and troubleshooting advice.

1. Environment Setup (5 minutes)

All scripts are Python‑based. Install Python 3.9+ from the official site, open a terminal, and install the required packages for the scenario you need.

# Web UI automation (Selenium)
pip install selenium pytest webdriver-manager
# API testing (Requests + Pytest)
pip install requests pytest
# Mobile (Appium – optional)
pip install Appium-Python-Client
# Database (MySQL)
pip install pymysql

Tip: if pip is not found, run python -m ensurepip.

2. Scenario 1 – Web UI Login (Selenium + Pytest)

Prompt used to generate the script:

You are an e‑commerce test engineer, generate a Pytest + Selenium script for the “User Login” feature.
- Test site: https://practice.sdet.club/login
- Account: admin / password
- Username field ID: "username"
- Password field ID: "password"
- Login button XPath: "//button[@type='submit']"
- Success: URL contains "/dashboard" and page shows "Welcome admin"
- Requirements: use a pytest fixture for the browser, explicit wait (max 10 s), capture screenshot on failure, Chinese comments, fully runnable code.

Generated script (tested and working):

# test_web_login.py
import os, pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

os.makedirs("screenshots", exist_ok=True)

@pytest.fixture
def driver():
    """Start and quit the browser"""
    service = Service(ChromeDriverManager().install())
    options = webdriver.ChromeOptions()
    # options.add_argument("--headless")  # uncomment for headless mode
    driver = webdriver.Chrome(service=service, options=options)
    driver.maximize_window()
    yield driver
    driver.quit()

def take_screenshot(driver, name):
    """Save screenshot on failure"""
    path = f"screenshots/{name}.png"
    driver.save_screenshot(path)
    print(f"Screenshot saved: {path}")

def test_login_success(driver):
    """Verify successful login"""
    try:
        driver.get("https://practice.sdet.club/login")
        username_field = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "username"))
        )
        username_field.send_keys("admin")
        driver.find_element(By.ID, "password").send_keys("password")
        login_btn = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//button[@type='submit']"))
        )
        login_btn.click()
        WebDriverWait(driver, 10).until(EC.url_contains("/dashboard"))
        welcome_text = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.TAG_NAME, "body"))
        ).text
        assert "Welcome admin" in welcome_text, "Welcome text not found"
        print("✅ Login test passed!")
    except Exception as e:
        take_screenshot(driver, "login_fail")
        raise e

Run with:

pytest test_web_login.py -v

The public site requires no internal network; successful execution prints “✅ Login test passed!”.

3. Scenario 2 – API Order Creation (Requests + Pytest)

Prompt:

Please generate a Pytest script for creating an order via API.
- Endpoint: POST https://reqres.in/api/orders
- Headers: {"Content-Type": "application/json"}
- Body: {"product_id": 1001, "quantity": 2}
- Success: status_code 201, response contains "order_id" and "status":"created"
- Failure case: quantity 0 should return 400
- Use pytest parametrize and detailed assertions.

Generated script:

# test_api_order.py
import requests, pytest

BASE_URL = "https://reqres.in/api"

@pytest.mark.parametrize("quantity, expected_status", [
    (2, 201),   # positive case
    (0, 400),   # error case
])
def test_create_order(quantity, expected_status):
    """Test order creation API"""
    url = f"{BASE_URL}/orders"
    payload = {"product_id": 1001, "quantity": quantity}
    headers = {"Content-Type": "application/json"}
    response = requests.post(url, json=payload, headers=headers)
    assert response.status_code == expected_status, f"Expected {expected_status}, got {response.status_code}"
    if expected_status == 201:
        data = response.json()
        assert "order_id" in data, "Missing order_id"
        assert data["status"] == "created", "Incorrect status"
        print(f"✅ Order created, ID: {data['order_id']}")
    else:
        print("✅ Error case validated")

Run with:

pytest test_api_order.py -v

The mock API at reqres.in is stable and publicly reachable.

4. Scenario 3 – Mobile Settings Click (Appium)

Prompt:

Generate an Appium script for the Android Settings app to click “About phone”.
- App package: com.android.settings
- Activity: .Settings
- Target element text: "关于手机"
- Use uiautomator2, add retry, print page_source on failure.

Generated script:

# test_mobile_settings.py
from appium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

def test_click_about_phone():
    caps = {
        "platformName": "Android",
        "appium:platformVersion": "13",
        "appium:deviceName": "emulator-5554",
        "appium:appPackage": "com.android.settings",
        "appium:appActivity": ".Settings",
        "appium:automationName": "uiautomator2"
    }
    driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
    try:
        about = WebDriverWait(driver, 15).until(
            EC.element_to_be_clickable((By.ANDROID_UIAUTOMATOR, 'new UiSelector().text("关于手机")'))
        )
        about.click()
        print("✅ Successfully clicked ‘关于手机’")
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ANDROID_UIAUTOMATOR, 'new UiSelector().textContains("型号")'))
        )
    except Exception as e:
        print("❌ Operation failed, current page source:")
        print(driver.page_source)
        raise e
    finally:
        driver.quit()

Tip: first master web or API scenarios before attempting mobile.

5. Scenario 4 – Database Verification (MySQL)

Prompt:

Write a script to verify that a newly registered user is stored in MySQL.
- Docker MySQL (host=localhost, port=3306, user=root, password=rootpassword, db=test_db)
- Table users(email VARCHAR, status TINYINT, created_at DATETIME)
- Assume UI registration created email [email protected]
- Verify record exists, status=1, created_at within 10 minutes
- Use fixture for connection, delete test data after verification.

Generated script:

# test_db_user.py
import pymysql, pytest
from datetime import datetime, timedelta

TEST_EMAIL = "[email protected]"

@pytest.fixture
def db_connection():
    conn = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        password='rootpassword',
        database='test_db',
        charset='utf8mb4'
    )
    yield conn
    conn.close()

def test_user_registered_in_db(db_connection):
    """Validate user registration data in DB"""
    cursor = db_connection.cursor()
    cursor.execute(
        "SELECT email, status, created_at FROM users WHERE email = %s",
        (TEST_EMAIL,)
    )
    result = cursor.fetchone()
    assert result is not None, "User record not found"
    email, status, created_at = result
    assert status == 1, f"Expected status 1, got {status}"
    now = datetime.now()
    assert created_at >= now - timedelta(minutes=10), "Creation time older than 10 minutes"
    print(f"✅ User {email} data verification passed")
    # Clean up test data
    cursor.execute("DELETE FROM users WHERE email = %s", (TEST_EMAIL,))
    db_connection.commit()
    cursor.close()

Start the MySQL container first:

docker run --name test-mysql -e MYSQL_ROOT_PASSWORD=rootpassword -e MYSQL_DATABASE=test_db -p 3306:3306 -d mysql:8

6. Debugging Tips

Problem:

WebDriverException: 'chromedriver' executable needs to be in PATH

– Solution: webdriver‑manager handles the driver automatically; no manual download required.

Problem: requests.exceptions.ConnectionError – Solution: check network connectivity or switch to another public API such as https://httpbin.org/post.

Problem:

pymysql.err.OperationalError: (2003, "Can't connect to MySQL server")

– Solution: ensure the Docker MySQL container is running ( docker ps).

Problem: Script hangs – Solution: add an explicit .until(...) after WebDriverWait and avoid implicit waits.

Ultimate tip: copy the full traceback and ask an AI “How do I fix this error?”

7. Bonus: Complete Code Package

The repository includes all scripts, a requirements.txt for one‑click dependency installation, and a docker‑compose.yml for the MySQL service.

test_web_login.py
test_api_order.py
test_mobile_settings.py (with Appium setup)
test_db_user.py + docker-compose.yml
requirements.txt

With these resources, even a beginner can run the first test script and become an “automated” test engineer.

PythonMySQLappiumseleniumAI prompt
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.