Pytest-Bdd-Playwright 系列教程(2):支持在多浏览器、多环境中执行测试

Pytest-Bdd-Playwright 系列教程(2):支持在多浏览器、多环境中执行测试

前言

学会本文教程内容后,你将掌握:

通过本文的学习,你将能够:

  • 使用命令行参数 灵活配置测试环境浏览器选项
  • 实现多环境测试;
  • 掌握Pytest fixture的高级用法;
  • 学会使用配置文件管理测试参数;
  • 优化项目结构,提高代码复用性可维护性

一、 修改 conftest.py 文件

conftest.py是Pytest的一个特殊文件,用于存放共享的fixture和hook函数。

我们对 conftest.py 进行以下修改:

  • 添加命令行选项解析
  • 实现动态浏览器选择
  • 支持无头模式运行
  • 引入环境配置
python 复制代码
# conftest.py
# Author: blues_C

import pytest
import logging

from pathlib import Path
from utils.config import Config
from playwright.sync_api import sync_playwright

log = logging.getLogger(__name__)
root_path = Path(__file__).resolve().parent

def pytest_addoption(parser):
    parser.addoption("--browser", action="store", default="chromium", help="要使用的浏览器: chromium, firefox, or webkit")
    parser.addoption("--headless", action="store_true", default=False, help="运行浏览器无头模式")
    parser.addoption("--env", action="store", default=Config.DEFAULT_ENV, help="要测试的环境: test, staging, or prod")

@pytest.fixture(scope="function")
def playwright():
    with sync_playwright() as playwright:
        yield playwright

@pytest.fixture(scope="function")
def browser_type(playwright, request):
    browser_name = request.config.getoption("--browser")
    if browser_name == "chromium":
        return playwright.chromium
    elif browser_name == "firefox":
        return playwright.firefox
    elif browser_name == "webkit":
        return playwright.webkit
    else:
        raise ValueError(f"不支持的浏览器: {browser_name}")

@pytest.fixture(scope="function")
def browser(browser_type, request):
    headless = request.config.getoption("--headless")
    browser = browser_type.launch(headless=headless)
    log.info(f"启动浏览器: {browser_type.name}, 无头模式: {headless}")
    yield browser
    browser.close()

@pytest.fixture(scope="function")
def base_url(request):
    env = request.config.getoption("--env")
    if env not in Config.ENVIRONMENTS:
        raise ValueError(f"不支持的环境: {env}")
    return Config.ENVIRONMENTS[env]

@pytest.fixture(scope="function")
def page(browser):
    page = browser.new_page()
    yield page
    page.close()

代码修改说明如下

  • pytest_addoption: 添加自定义命令行选项
  • browser_type: 根据命令行参数动态选择浏览器
  • browser: 支持无头模式运行
  • base_url: 根据环境参数选择测试URL

二、创建配置文件

为了更好地管理测试参数,我们创建一个专门的配置文件。

utils/中创建一个config.py文件:

项目结构如下:

复制代码
│
├── features/                # BDD特性文件
│   └── search.feature       # 搜索功能的特性文件
│
├── pages/                   # 页面对象
│   └── search_page.py       # 搜索页面对象
│
├── steps/                   # 步骤定义
│   └── search_steps.py      # 搜索相关步骤定义
│
├── tests/                   # 测试脚本
│   └── test_search.py
│
├── reports/                 # 测试报告(自动生成)
│   ├── logs/                # 日志文件目录(自动生成)
│   │   └── test_log.log     # 测试日志文件(自动生成)
│   └── test_report.html     # HTML格式的测试报告(自动生成)
│
├── utils/          # 工具函数
│   └── config.py   # 配置管理
│
├── conftest.py              # Pytest fixtures和全局配置
├── pytest.ini               # Pytest配置文件
├── requirements.txt         # 项目依赖
└── README.md                # 项目说明文档
python 复制代码
# config.py

class Config:
    ENVIRONMENTS = {
        'test': 'https://www.baidu.com',
        'stage': 'https://example.com',
        'prod': 'https://blog.csdn.net/weixin_48321392'
    }
    DEFAULT_ENV = 'test'

config = Config()

三、修改search_steps.py文件

我们需要修改步骤定义文件以适应新的配置:

python 复制代码
@given('我在百度搜索页面')
def navigate_to_search_page(search_page, base_url):
    search_page.navigate(base_url)

代码说明如下

  • conftest.py 文件中定义了一个名为 base_url 的 fixture,它会根据命令行参数 --env 来选择不同的 URL;
  • navigate_to_search_page 函数中base_url 作为参数传入,来获取当前环境的URL,让测试可以在不同环境中运行。

四、运行测试

现在,我们可以使用不同的命令行参数来运行测试:

bash 复制代码
pytest # 默认使用chromium浏览器,非无头模式,测试环境
pytest --browser firefox --env stage # 使用Firefox浏览器,测试预发布环境
pytest --browser webkit --env prod --headless # 使用WebKit浏览器,无头模式,测试生产环境
相关推荐
姚青&20 小时前
Pytest 测试用例编写
测试用例·pytest
Warren9821 小时前
Pytest Fixture 作用域与接口测试 Token 污染问题实战解析
功能测试·面试·单元测试·集成测试·pytest·postman·模块测试
测试秃头怪1 天前
面试大厂就靠这份软件测试八股文了【含答案】
自动化测试·软件测试·python·功能测试·面试·职场和发展·单元测试
测试杂货铺1 天前
软件测试面试题大全,你要的都在这。。
自动化测试·软件测试·python·功能测试·面试·职场和发展·测试用例
程序员小远2 天前
UI自动化测试用例管理平台搭建
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
serve the people2 天前
python环境搭建 (七) pytest、pytest-asyncio、pytest-cov 试生态的核心组合
开发语言·python·pytest
真智AI3 天前
用 LLM 辅助生成可跑的 Python 单元测试:pytest + coverage 覆盖率报告(含运行指令与排坑)
python·单元测试·pytest
Warren983 天前
Allure 常用装饰器:实战用法 + 最佳实践(接口自动化)
运维·服务器·git·python·单元测试·自动化·pytest
feasibility.4 天前
playwright爬虫采集京东商品主页数据(含xpath定位示例)
爬虫·playwright