Selenium + Python + Pytest + Yaml + POM

发布于:2025-08-09 ⋅ 阅读:(11) ⋅ 点赞:(0)

以下是基于 Selenium + Python + Pytest + Yaml + POM 搭建 WebUI 自动化测试框架,并通过 Jenkins 实现持续集成、自动部署和定时任务的具体操作步骤:

一、搭建 WebUI 自动化测试框架

1. 项目结构

创建以下项目目录结构:

WebUITestFramework/
├── config/                # 配置文件目录
├── page/                  # 页面对象目录
├── page_element/          # 页面元素定位文件目录
├── scripts/               # 测试脚本目录
├── utils/                 # 工具类目录
├── conftest.py            # Pytest 配置文件
├── pytest.ini             # Pytest 配置文件
├── test_case.py           # 测试用例文件
2. 配置文件管理

config 目录下创建 conf.pyconfig.ini 文件。

conf.py

import os
from selenium.webdriver.common.by import By
from utils.times import dt_strftime

class ConfigManager(object):
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    ELEMENT_PATH = os.path.join(BASE_DIR, 'page_element')
    REPORT_FILE = os.path.join(BASE_DIR, 'report.html')
    LOCATE_MODE = {
        'css': By.CSS_SELECTOR,
        'xpath': By.XPATH,
        'name': By.NAME,
        'id': By.ID,
        'class': By.CLASS_NAME
    }
    EMAIL_INFO = {
        'username': 'your_email@example.com',
        'password': 'your_password',
        'smtp_host': 'smtp.example.com',
        'smtp_port': 465
    }
    ADDRESSEE = ['recipient@example.com']

    @property
    def log_file(self):
        log_dir = os.path.join(self.BASE_DIR, 'logs')
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        return os.path.join(log_dir, '{}.log'.format(dt_strftime()))

    @property
    def ini_file(self):
        ini_file = os.path.join(self.BASE_DIR, 'config', 'config.ini')
        if not os.path.exists(ini_file):
            raise FileNotFoundError("配置文件%s不存在!" % ini_file)
        return ini_file

cm = ConfigManager()

config.ini

ini复制

[HOST]
HOST = https://www.example.com
3. 页面对象管理

page_element 目录下创建 search.yaml 文件:

yaml复制

搜索框: id==kw
搜索按钮: id==su
4. 封装 Selenium 基类

page 目录下创建 webpage.py 文件:

Python复制

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from config.conf import cm
from utils.logger import log

class WebPage(object):
    def __init__(self, driver):
        self.driver = driver
        self.timeout = 20
        self.wait = WebDriverWait(self.driver, self.timeout)

    def find_element(self, locator):
        return self.wait.until(EC.presence_of_element_located(locator))

    def input_text(self, locator, txt):
        ele = self.find_element(locator)
        ele.clear()
        ele.send_keys(txt)
        log.info(f"输入文本:{txt}")

    def click(self, locator):
        self.find_element(locator).click()
        log.info(f"点击元素:{locator}")
5. 编写测试用例

在项目根目录下创建 test_case.py 文件:

Python复制

import pytest
from selenium import webdriver
from page.webpage import WebPage
from page_object.searchpage import SearchPage

@pytest.fixture(scope='session')
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

def test_search(driver):
    page = SearchPage(driver)
    page.search("Moonshot AI")
    assert "Moonshot AI" in driver.title

二、集成 Jenkins 实现持续集成

1. 安装 Jenkins
  • 下载并安装 Jenkins。

  • 启动 Jenkins 并完成初始配置。

2. 创建 Jenkins 任务
  • 在 Jenkins 中创建一个新的自由风格项目。

  • 配置源码管理(如 Git),指定项目代码仓库地址。

  • 配置构建触发器(如定时任务或代码提交触发)。

3. 配置构建环境
  • 在 Jenkins 任务的构建步骤中,添加执行 Shell 脚本:

bash复制

pip install -r requirements.txt
pytest --html=report.html
4. 配置邮件通知
  • 安装 Jenkins 的邮件扩展插件。

  • 在项目配置中设置邮件通知,指定收件人和邮件内容。

5. 设置定时任务
  • 在 Jenkins 任务的构建触发器中,选择“定时构建”。

  • 配置定时任务的 Cron 表达式,例如:

    0 0 * * * # 每天凌晨 0 点触发

三、适配企业需求

  1. 多环境适配

    • config.ini 中添加不同环境的配置。

    • 通过 Jenkins 参数化构建,动态选择测试环境。

  2. 测试报告

    • 使用 pytest-html 插件生成测试报告。

    • 将报告上传到 Jenkins 的工作空间,方便查看。

  3. 自动部署

    • 在 Jenkins 中配置部署脚本,将测试结果或相关文件部署到指定服务器。

通过以上步骤,你可以完成一个完整的 WebUI 自动化测试框架搭建,并通过 Jenkins 实现持续集成、自动部署和定时任务,满足企业级测试需求。


网站公告

今日签到

点亮在社区的每一天
去签到