最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python利用pytest和selenium實現(xiàn)自動化測試完整指南

 更新時間:2025年08月28日 09:19:49   作者:天天進步2015  
自動化測試是現(xiàn)代軟件開發(fā)中不可或缺的一環(huán),Python作為一門簡潔優(yōu)雅的編程語言,配合pytest測試框架和selenium自動化工具,為我們提供了強大的自動化測試解決方案,下面小編就來和大家簡單介紹一下吧

前言

自動化測試是現(xiàn)代軟件開發(fā)中不可或缺的一環(huán)。Python作為一門簡潔優(yōu)雅的編程語言,配合pytest測試框架和selenium自動化工具,為我們提供了強大的自動化測試解決方案。

本教程將從零開始,帶領大家掌握Python自動化測試的核心技能,通過實戰(zhàn)項目學會如何構建穩(wěn)定、高效的自動化測試體系。

環(huán)境搭建

安裝Python和依賴包

# 創(chuàng)建虛擬環(huán)境
python -m venv test_env
source test_env/bin/activate  # Windows: test_env\Scripts\activate

# 安裝核心依賴
pip install pytest selenium webdriver-manager pytest-html allure-pytest

瀏覽器驅動配置

# 使用webdriver-manager自動管理驅動
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

def setup_driver():
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service)
    return driver

項目結構搭建

automation_project/
├── tests/
│   ├── __init__.py
│   ├── test_login.py
│   └── test_search.py
├── pages/
│   ├── __init__.py
│   ├── base_page.py
│   └── login_page.py
├── utils/
│   ├── __init__.py
│   └── config.py
├── drivers/
├── reports/
├── conftest.py
├── pytest.ini
└── requirements.txt

pytest基礎教程

pytest核心概念

pytest是Python中最流行的測試框架,具有以下特點:

  • 簡單易用的斷言語法
  • 豐富的插件生態(tài)系統(tǒng)
  • 強大的fixture機制
  • 靈活的測試發(fā)現(xiàn)和執(zhí)行

基礎測試示例

# test_basic.py
import pytest

def test_simple_assert():
    """基礎斷言測試"""
    assert 1 + 1 == 2

def test_string_operations():
    """字符串操作測試"""
    text = "Hello, World!"
    assert "Hello" in text
    assert text.startswith("Hello")
    assert text.endswith("!")

class TestCalculator:
    """測試類示例"""
    
    def test_addition(self):
        assert 2 + 3 == 5
    
    def test_division(self):
        assert 10 / 2 == 5
    
    def test_division_by_zero(self):
        with pytest.raises(ZeroDivisionError):
            10 / 0

fixture機制深入

# conftest.py
import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

@pytest.fixture(scope="session")
def driver():
    """會話級別的瀏覽器驅動"""
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")  # 無頭模式
    driver = webdriver.Chrome(
        service=Service(ChromeDriverManager().install()),
        options=options
    )
    yield driver
    driver.quit()

@pytest.fixture
def test_data():
    """測試數(shù)據(jù)fixture"""
    return {
        "username": "test@example.com",
        "password": "password123"
    }

參數(shù)化測試

# test_parametrize.py
import pytest

@pytest.mark.parametrize("a,b,expected", [
    (2, 3, 5),
    (1, 1, 2),
    (0, 5, 5),
    (-1, 1, 0)
])
def test_addition(a, b, expected):
    assert a + b == expected

@pytest.mark.parametrize("url", [
    "https://www.baidu.com",
    "https://www.google.com"
])
def test_website_accessibility(driver, url):
    driver.get(url)
    assert driver.title

selenium基礎教程

元素定位策略

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class ElementLocator:
    """元素定位封裝類"""
    
    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)
    
    def find_element_safely(self, locator):
        """安全查找元素"""
        try:
            element = self.wait.until(EC.presence_of_element_located(locator))
            return element
        except TimeoutException:
            print(f"元素定位失敗: {locator}")
            return None
    
    def click_element(self, locator):
        """點擊元素"""
        element = self.wait.until(EC.element_to_be_clickable(locator))
        element.click()
    
    def input_text(self, locator, text):
        """輸入文本"""
        element = self.find_element_safely(locator)
        if element:
            element.clear()
            element.send_keys(text)

常用操作封裝

# utils/selenium_helper.py
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

class SeleniumHelper:
    """Selenium操作助手類"""
    
    def __init__(self, driver):
        self.driver = driver
    
    def scroll_to_element(self, element):
        """滾動到指定元素"""
        self.driver.execute_script("arguments[0].scrollIntoView();", element)
    
    def select_dropdown_by_text(self, locator, text):
        """通過文本選擇下拉框"""
        select = Select(self.driver.find_element(*locator))
        select.select_by_visible_text(text)
    
    def hover_element(self, element):
        """鼠標懸停"""
        actions = ActionChains(self.driver)
        actions.move_to_element(element).perform()
    
    def switch_to_iframe(self, iframe_locator):
        """切換到iframe"""
        iframe = self.driver.find_element(*iframe_locator)
        self.driver.switch_to.frame(iframe)
    
    def take_screenshot(self, filename):
        """截圖"""
        self.driver.save_screenshot(f"screenshots/{filename}")

pytest + selenium實戰(zhàn)項目

實戰(zhàn)項目:電商網(wǎng)站測試

讓我們以一個電商網(wǎng)站為例,構建完整的自動化測試項目。

配置文件設置

# utils/config.py
class Config:
    """測試配置類"""
    
    BASE_URL = "https://example-shop.com"
    TIMEOUT = 10
    BROWSER = "chrome"
    HEADLESS = False
    
    # 測試賬戶信息
    TEST_USER = {
        "email": "test@example.com",
        "password": "password123"
    }
    
    # 測試數(shù)據(jù)
    TEST_PRODUCT = {
        "name": "iPhone 14",
        "price": "999.99"
    }

基礎頁面類

# pages/base_page.py
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

class BasePage:
    """基礎頁面類"""
    
    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)
    
    def open(self, url):
        """打開頁面"""
        self.driver.get(url)
    
    def find_element(self, locator):
        """查找元素"""
        return self.wait.until(EC.presence_of_element_located(locator))
    
    def click(self, locator):
        """點擊元素"""
        element = self.wait.until(EC.element_to_be_clickable(locator))
        element.click()
    
    def input_text(self, locator, text):
        """輸入文本"""
        element = self.find_element(locator)
        element.clear()
        element.send_keys(text)
    
    def get_text(self, locator):
        """獲取元素文本"""
        element = self.find_element(locator)
        return element.text
    
    def is_element_visible(self, locator):
        """檢查元素是否可見"""
        try:
            self.wait.until(EC.visibility_of_element_located(locator))
            return True
        except:
            return False

登錄頁面類

# pages/login_page.py
from selenium.webdriver.common.by import By
from pages.base_page import BasePage

class LoginPage(BasePage):
    """登錄頁面"""
    
    # 頁面元素定位
    EMAIL_INPUT = (By.ID, "email")
    PASSWORD_INPUT = (By.ID, "password")
    LOGIN_BUTTON = (By.XPATH, "http://button[@type='submit']")
    ERROR_MESSAGE = (By.CLASS_NAME, "error-message")
    SUCCESS_MESSAGE = (By.CLASS_NAME, "success-message")
    
    def login(self, email, password):
        """執(zhí)行登錄操作"""
        self.input_text(self.EMAIL_INPUT, email)
        self.input_text(self.PASSWORD_INPUT, password)
        self.click(self.LOGIN_BUTTON)
    
    def get_error_message(self):
        """獲取錯誤信息"""
        if self.is_element_visible(self.ERROR_MESSAGE):
            return self.get_text(self.ERROR_MESSAGE)
        return None
    
    def is_login_successful(self):
        """檢查登錄是否成功"""
        return self.is_element_visible(self.SUCCESS_MESSAGE)

登錄測試用例

# tests/test_login.py
import pytest
from pages.login_page import LoginPage
from utils.config import Config

class TestLogin:
    """登錄功能測試類"""
    
    @pytest.fixture(autouse=True)
    def setup(self, driver):
        """測試前置條件"""
        self.driver = driver
        self.login_page = LoginPage(driver)
        self.login_page.open(f"{Config.BASE_URL}/login")
    
    def test_valid_login(self):
        """測試有效登錄"""
        self.login_page.login(
            Config.TEST_USER["email"],
            Config.TEST_USER["password"]
        )
        assert self.login_page.is_login_successful()
    
    @pytest.mark.parametrize("email,password,expected_error", [
        ("", "password123", "郵箱不能為空"),
        ("invalid-email", "password123", "郵箱格式不正確"),
        ("test@example.com", "", "密碼不能為空"),
        ("wrong@example.com", "wrongpass", "用戶名或密碼錯誤")
    ])
    def test_invalid_login(self, email, password, expected_error):
        """測試無效登錄"""
        self.login_page.login(email, password)
        error_message = self.login_page.get_error_message()
        assert expected_error in error_message
    
    def test_login_form_elements(self):
        """測試登錄表單元素存在性"""
        assert self.login_page.is_element_visible(self.login_page.EMAIL_INPUT)
        assert self.login_page.is_element_visible(self.login_page.PASSWORD_INPUT)
        assert self.login_page.is_element_visible(self.login_page.LOGIN_BUTTON)

商品搜索測試

# pages/search_page.py
from selenium.webdriver.common.by import By
from pages.base_page import BasePage

class SearchPage(BasePage):
    """搜索頁面"""
    
    SEARCH_INPUT = (By.NAME, "search")
    SEARCH_BUTTON = (By.CLASS_NAME, "search-btn")
    SEARCH_RESULTS = (By.CLASS_NAME, "product-item")
    NO_RESULTS_MESSAGE = (By.CLASS_NAME, "no-results")
    PRODUCT_TITLE = (By.CLASS_NAME, "product-title")
    
    def search_product(self, keyword):
        """搜索商品"""
        self.input_text(self.SEARCH_INPUT, keyword)
        self.click(self.SEARCH_BUTTON)
    
    def get_search_results_count(self):
        """獲取搜索結果數(shù)量"""
        results = self.driver.find_elements(*self.SEARCH_RESULTS)
        return len(results)
    
    def get_first_product_title(self):
        """獲取第一個商品標題"""
        return self.get_text(self.PRODUCT_TITLE)

# tests/test_search.py
import pytest
from pages.search_page import SearchPage
from utils.config import Config

class TestSearch:
    """搜索功能測試類"""
    
    @pytest.fixture(autouse=True)
    def setup(self, driver):
        self.driver = driver
        self.search_page = SearchPage(driver)
        self.search_page.open(Config.BASE_URL)
    
    def test_valid_search(self):
        """測試有效搜索"""
        self.search_page.search_product("iPhone")
        assert self.search_page.get_search_results_count() > 0
    
    def test_search_no_results(self):
        """測試無結果搜索"""
        self.search_page.search_product("不存在的商品")
        assert self.search_page.is_element_visible(self.search_page.NO_RESULTS_MESSAGE)
    
    @pytest.mark.parametrize("keyword", [
        "iPhone", "Samsung", "小米", "華為"
    ])
    def test_multiple_searches(self, keyword):
        """測試多個關鍵詞搜索"""
        self.search_page.search_product(keyword)
        results_count = self.search_page.get_search_results_count()
        assert results_count >= 0  # 至少返回0個結果

頁面對象模式(POM)

頁面對象模式是自動化測試中的重要設計模式,它將頁面元素和操作封裝在獨立的類中。

完整的POM實現(xiàn)

# pages/product_page.py
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from pages.base_page import BasePage

class ProductPage(BasePage):
    """商品詳情頁"""
    
    # 商品信息元素
    PRODUCT_TITLE = (By.H1, "product-title")
    PRODUCT_PRICE = (By.CLASS_NAME, "price")
    PRODUCT_DESCRIPTION = (By.CLASS_NAME, "description")
    
    # 購買相關元素
    QUANTITY_SELECT = (By.NAME, "quantity")
    ADD_TO_CART_BUTTON = (By.ID, "add-to-cart")
    CART_SUCCESS_MESSAGE = (By.CLASS_NAME, "cart-success")
    
    # 評論相關元素
    REVIEWS_SECTION = (By.ID, "reviews")
    REVIEW_INPUT = (By.NAME, "review")
    SUBMIT_REVIEW_BUTTON = (By.ID, "submit-review")
    
    def get_product_info(self):
        """獲取商品信息"""
        return {
            "title": self.get_text(self.PRODUCT_TITLE),
            "price": self.get_text(self.PRODUCT_PRICE),
            "description": self.get_text(self.PRODUCT_DESCRIPTION)
        }
    
    def add_to_cart(self, quantity=1):
        """添加到購物車"""
        # 選擇數(shù)量
        quantity_select = Select(self.find_element(self.QUANTITY_SELECT))
        quantity_select.select_by_value(str(quantity))
        
        # 點擊添加到購物車
        self.click(self.ADD_TO_CART_BUTTON)
        
        # 等待成功消息
        return self.is_element_visible(self.CART_SUCCESS_MESSAGE)
    
    def submit_review(self, review_text):
        """提交評論"""
        self.input_text(self.REVIEW_INPUT, review_text)
        self.click(self.SUBMIT_REVIEW_BUTTON)

購物車頁面測試

# tests/test_cart.py
import pytest
from pages.product_page import ProductPage
from pages.cart_page import CartPage
from utils.config import Config

class TestShoppingCart:
    """購物車功能測試"""
    
    @pytest.fixture(autouse=True)
    def setup(self, driver):
        self.driver = driver
        self.product_page = ProductPage(driver)
        self.cart_page = CartPage(driver)
    
    def test_add_single_product_to_cart(self):
        """測試添加單個商品到購物車"""
        # 打開商品頁面
        self.product_page.open(f"{Config.BASE_URL}/product/1")
        
        # 添加到購物車
        success = self.product_page.add_to_cart(quantity=1)
        assert success
        
        # 驗證購物車
        self.cart_page.open(f"{Config.BASE_URL}/cart")
        assert self.cart_page.get_cart_items_count() == 1
    
    def test_add_multiple_quantities(self):
        """測試添加多數(shù)量商品"""
        self.product_page.open(f"{Config.BASE_URL}/product/1")
        
        success = self.product_page.add_to_cart(quantity=3)
        assert success
        
        self.cart_page.open(f"{Config.BASE_URL}/cart")
        total_quantity = self.cart_page.get_total_quantity()
        assert total_quantity == 3
    
    def test_cart_total_calculation(self):
        """測試購物車總價計算"""
        # 添加多個商品
        products = [
            {"id": 1, "quantity": 2, "price": 99.99},
            {"id": 2, "quantity": 1, "price": 149.99}
        ]
        
        expected_total = 0
        for product in products:
            self.product_page.open(f"{Config.BASE_URL}/product/{product['id']}")
            self.product_page.add_to_cart(product["quantity"])
            expected_total += product["price"] * product["quantity"]
        
        self.cart_page.open(f"{Config.BASE_URL}/cart")
        actual_total = self.cart_page.get_total_price()
        assert actual_total == expected_total

測試報告生成

HTML報告配置

# pytest.ini
[tool:pytest]
minversion = 6.0
addopts = -v --strict-markers --html=reports/report.html --self-contained-html
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
markers =
    smoke: 冒煙測試
    regression: 回歸測試
    slow: 慢速測試

Allure報告集成

# conftest.py 添加allure配置
import allure
import pytest
from selenium import webdriver

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """生成測試報告鉤子"""
    outcome = yield
    report = outcome.get_result()
    
    if report.when == "call" and report.failed:
        # 測試失敗時自動截圖
        driver = item.funcargs.get('driver')
        if driver:
            allure.attach(
                driver.get_screenshot_as_png(),
                name="失敗截圖",
                attachment_type=allure.attachment_type.PNG
            )

# 在測試中使用allure裝飾器
import allure

class TestLoginWithAllure:
    """帶Allure報告的登錄測試"""
    
    @allure.epic("用戶管理")
    @allure.feature("用戶登錄")
    @allure.story("正常登錄流程")
    @allure.severity(allure.severity_level.CRITICAL)
    def test_valid_login_with_allure(self, driver):
        """測試有效登錄 - Allure版本"""
        with allure.step("打開登錄頁面"):
            login_page = LoginPage(driver)
            login_page.open(f"{Config.BASE_URL}/login")
        
        with allure.step("輸入登錄憑證"):
            login_page.login(
                Config.TEST_USER["email"],
                Config.TEST_USER["password"]
            )
        
        with allure.step("驗證登錄結果"):
            assert login_page.is_login_successful()
            allure.attach(
                driver.get_screenshot_as_png(),
                name="登錄成功截圖",
                attachment_type=allure.attachment_type.PNG
            )

持續(xù)集成配置

GitHub Actions配置

# .github/workflows/test.yml
name: 自動化測試

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v3
    
    - name: 設置Python環(huán)境
      uses: actions/setup-python@v3
      with:
        python-version: '3.9'
    
    - name: 安裝Chrome
      uses: browser-actions/setup-chrome@latest
    
    - name: 安裝依賴
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements.txt
    
    - name: 運行測試
      run: |
        pytest tests/ --html=reports/report.html --alluredir=allure-results
    
    - name: 生成Allure報告
      uses: simple-elf/allure-report-action@master
      if: always()
      with:
        allure_results: allure-results
        allure_history: allure-history
    
    - name: 上傳測試報告
      uses: actions/upload-artifact@v3
      if: always()
      with:
        name: test-reports
        path: |
          reports/
          allure-report/

Docker配置

# Dockerfile
FROM python:3.9-slim

# 安裝系統(tǒng)依賴
RUN apt-get update && apt-get install -y \
    wget \
    gnupg \
    unzip \
    curl

# 安裝Chrome
RUN wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list \
    && apt-get update \
    && apt-get install -y google-chrome-stable

# 設置工作目錄
WORKDIR /app

# 復制項目文件
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

# 運行測試
CMD ["pytest", "tests/", "--html=reports/report.html"]

最佳實踐和進階技巧

測試數(shù)據(jù)管理

# utils/test_data.py
import json
import yaml
from pathlib import Path

class TestDataManager:
    """測試數(shù)據(jù)管理器"""
    
    def __init__(self, data_dir="test_data"):
        self.data_dir = Path(data_dir)
    
    def load_json_data(self, filename):
        """加載JSON測試數(shù)據(jù)"""
        file_path = self.data_dir / f"{filename}.json"
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    
    def load_yaml_data(self, filename):
        """加載YAML測試數(shù)據(jù)"""
        file_path = self.data_dir / f"{filename}.yaml"
        with open(file_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)

# test_data/login_data.yaml
valid_users:
  - email: "user1@example.com"
    password: "password123"
    expected_result: "success"
  - email: "user2@example.com"
    password: "password456"
    expected_result: "success"

invalid_users:
  - email: ""
    password: "password123"
    expected_error: "郵箱不能為空"
  - email: "invalid-email"
    password: "password123"
    expected_error: "郵箱格式不正確"

失敗重試機制

# conftest.py
import pytest

@pytest.fixture(autouse=True)
def retry_failed_tests(request):
    """失敗測試重試機制"""
    if request.node.rep_call.failed:
        # 重試邏輯
        pass

# 使用pytest-rerunfailures插件
# pip install pytest-rerunfailures
# pytest --reruns 3 --reruns-delay 2

并行測試執(zhí)行

# 安裝pytest-xdist
# pip install pytest-xdist

# 并行執(zhí)行測試
# pytest -n auto  # 自動檢測CPU核心數(shù)
# pytest -n 4     # 使用4個進程

測試環(huán)境管理

# utils/environment.py
import os
from enum import Enum

class Environment(Enum):
    DEV = "dev"
    TEST = "test"
    STAGING = "staging"
    PROD = "prod"

class EnvironmentConfig:
    """環(huán)境配置管理"""
    
    def __init__(self):
        self.current_env = Environment(os.getenv('TEST_ENV', 'test'))
        
    def get_base_url(self):
        """獲取當前環(huán)境的基礎URL"""
        urls = {
            Environment.DEV: "http://dev.example.com",
            Environment.TEST: "http://test.example.com",
            Environment.STAGING: "http://staging.example.com",
            Environment.PROD: "http://example.com"
        }
        return urls[self.current_env]
    
    def get_database_config(self):
        """獲取數(shù)據(jù)庫配置"""
        configs = {
            Environment.TEST: {
                "host": "test-db.example.com",
                "database": "test_db"
            },
            Environment.STAGING: {
                "host": "staging-db.example.com",
                "database": "staging_db"
            }
        }
        return configs.get(self.current_env, {})

性能測試集成

# tests/test_performance.py
import time
import pytest
from selenium.webdriver.support.ui import WebDriverWait

class TestPerformance:
    """性能測試"""
    
    def test_page_load_time(self, driver):
        """測試頁面加載時間"""
        start_time = time.time()
        
        driver.get("https://example.com")
        WebDriverWait(driver, 10).until(
            lambda d: d.execute_script("return document.readyState") == "complete"
        )
        
        load_time = time.time() - start_time
        assert load_time < 5.0, f"頁面加載時間過長: {load_time}秒"
    
    def test_search_response_time(self, driver, search_page):
        """測試搜索響應時間"""
        search_page.open("https://example.com")
        
        start_time = time.time()
        search_page.search_product("iPhone")
        
        # 等待搜索結果出現(xiàn)
        WebDriverWait(driver, 10).until(
            lambda d: len(d.find_elements(*search_page.SEARCH_RESULTS)) > 0
        )
        
        response_time = time.time() - start_time
        assert response_time < 3.0, f"搜索響應時間過長: {response_time}秒"

數(shù)據(jù)庫驗證

# utils/database.py
import sqlite3
import pymongo
from contextlib import contextmanager

class DatabaseHelper:
    """數(shù)據(jù)庫操作助手"""
    
    def __init__(self, db_config):
        self.config = db_config
    
    @contextmanager
    def get_connection(self):
        """獲取數(shù)據(jù)庫連接"""
        if self.config['type'] == 'sqlite':
            conn = sqlite3.connect(self.config['path'])
        elif self.config['type'] == 'mysql':
            import mysql.connector
            conn = mysql.connector.connect(**self.config)
        
        try:
            yield conn
        finally:
            conn.close()
    
    def verify_user_created(self, email):
        """驗證用戶是否創(chuàng)建成功"""
        with self.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM users WHERE email = ?", (email,))
            result = cursor.fetchone()
            return result is not None

# 在測試中使用數(shù)據(jù)庫驗證
def test_user_registration_with_db_verification(driver, db_helper):
    """測試用戶注冊并驗證數(shù)據(jù)庫"""
    # 執(zhí)行注冊操作
    registration_page = RegistrationPage(driver)
    test_email = f"test_{int(time.time())}@example.com"
    
    registration_page.register_user(
        email=test_email,
        password="password123"
    )
    
    # 驗證UI顯示成功
    assert registration_page.is_registration_successful()
    
    # 驗證數(shù)據(jù)庫中確實創(chuàng)建了用戶
    assert db_helper.verify_user_created(test_email)

總結

本教程全面介紹了使用pytest和selenium進行Python自動化測試的完整流程,從環(huán)境搭建到高級技巧,涵蓋了實際項目中的各個方面。

關鍵要點回顧

  • 環(huán)境搭建: 正確配置Python環(huán)境、瀏覽器驅動和項目結構
  • pytest框架: 掌握基礎測試、fixture機制和參數(shù)化測試
  • selenium操作: 學會元素定位、常用操作和等待機制
  • 頁面對象模式: 使用POM提高代碼復用性和維護性
  • 測試報告: 生成專業(yè)的HTML和Allure測試報告
  • 持續(xù)集成: 配置CI/CD流程實現(xiàn)自動化測試
  • 最佳實踐: 應用進階技巧提升測試質量和效率

以上就是Python利用pytest和selenium實現(xiàn)自動化測試完整指南的詳細內容,更多關于Python自動化測試的資料請關注腳本之家其它相關文章!

相關文章

  • python分批定量讀取文件內容,輸出到不同文件中的方法

    python分批定量讀取文件內容,輸出到不同文件中的方法

    今天小編就為大家分享一篇python分批定量讀取文件內容,輸出到不同文件中的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • 基于Python數(shù)據(jù)結構之遞歸與回溯搜索

    基于Python數(shù)據(jù)結構之遞歸與回溯搜索

    今天小編就為大家分享一篇基于Python數(shù)據(jù)結構之遞歸與回溯搜索,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • Python將MP4視頻轉換為GIF圖像的三種方法

    Python將MP4視頻轉換為GIF圖像的三種方法

    在數(shù)字時代,將視頻轉換為GIF圖像已成為一種流行的內容創(chuàng)作方式,在Python中,有多種庫可以幫助你將MP4視頻轉換為GIF圖像,本文將介紹三種常用的方法:使用moviepy庫、imageio庫以及結合opencv和PIL庫,需要的朋友可以參考下
    2024-12-12
  • Python可視化神器pyecharts繪制漏斗圖

    Python可視化神器pyecharts繪制漏斗圖

    這篇文章主要介紹了Python可視化神器pyecharts繪制漏斗圖,漏斗圖是由Light等在1984年提出,一般以單個研究的效應量為橫坐標,樣本含量為縱坐標做的散點圖
    2022-07-07
  • Python中self用法示例詳解

    Python中self用法示例詳解

    在Python中,類方法定義中的self是一個??約定俗成的參數(shù)名??,代表??類的實例對象本身??,下面這篇文章主要介紹了Python中self用法示例詳解的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2026-01-01
  • Python實現(xiàn)讀取HTML表格 pd.read_html()

    Python實現(xiàn)讀取HTML表格 pd.read_html()

    這篇文章主要介紹了Python實現(xiàn)讀取HTML表格 pd.read_html(),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • python socket發(fā)送TCP數(shù)據(jù)方式

    python socket發(fā)送TCP數(shù)據(jù)方式

    這篇文章主要介紹了python socket發(fā)送TCP數(shù)據(jù)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Python 多線程實例詳解

    Python 多線程實例詳解

    這篇文章主要介紹了Python 多線程實例詳解的相關資料,需要的朋友可以參考下
    2017-03-03
  • Python虛擬環(huán)境項目實例

    Python虛擬環(huán)境項目實例

    這篇文章主要介紹了Python虛擬環(huán)境項目實例步驟,以及遇到的問題解決辦法。
    2017-11-11
  • Python實現(xiàn)PyPDF2處理PDF文件的方法示例

    Python實現(xiàn)PyPDF2處理PDF文件的方法示例

    這篇文章主要介紹了Python實現(xiàn)PyPDF2處理PDF文件的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-09-09

最新評論

周至县| 遵义县| 喀喇| 永昌县| 鄄城县| 宁强县| 河北区| 民权县| 沙洋县| 康乐县| 兴化市| 绍兴县| 乐昌市| 濮阳市| 常宁市| 长岛县| 明溪县| 克山县| 故城县| 科尔| 柞水县| 林西县| 北辰区| 育儿| 泽普县| 麻栗坡县| 朔州市| 景东| 维西| 呈贡县| 桂平市| 屯门区| 乐安县| 明光市| 山丹县| 佛山市| 东源县| 斗六市| 蒲江县| 靖宇县| 汶川县|