如何根据被测站点自动自定义pytest HTML报告标题?
解决方案
1. 添加站点选择的命令行参数
先在pytest_addoption中新增--site参数,用来指定要测试的目标站点:
def pytest_addoption(parser): parser.addoption("--browser", action="store", default="chrome") # 新增站点参数,可选值为admin(对应Site A)或hr(对应Site B) parser.addoption("--site", action="store", default="admin", choices=["admin", "hr"])
2. 动态设置HTML报告标题
修改pytest_html_report_title函数,根据--site参数的取值自动切换报告标题:
def pytest_html_report_title(report): site_type = report.config.getoption("--site") if site_type == "admin": report.title = "Site A" elif site_type == "hr": report.title = "Site B"
3. 重构fixture减少冗余(可选但推荐)
原代码中两个fixture的浏览器初始化逻辑重复,可抽为公共函数,再根据站点参数执行对应登录流程:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.edge.service import Service as EdgeService driver = None def _init_browser(browser_name): """公共浏览器初始化逻辑""" if browser_name == "chrome": service = ChromeService() options = webdriver.ChromeOptions() return webdriver.Chrome(service=service, options=options) elif browser_name == "edge": service = EdgeService() options = webdriver.EdgeOptions() return webdriver.Edge(service=service, options=options) elif browser_name == "firefox": print("Firefox") return webdriver.Firefox() else: raise ValueError(f"不支持的浏览器类型:{browser_name}") @pytest.fixture(scope="class") def setup(request): global driver browser_name = request.config.getoption("--browser") site_type = request.config.getoption("--site") driver = _init_browser(browser_name) driver.maximize_window() driver.implicitly_wait(10) # 根据站点执行对应登录流程 if site_type == "admin": driver.get("https://test-admin.mednefits.com/login") driver.find_element(By.XPATH, "//input[@id='login_email']").send_keys("") driver.find_element(By.XPATH, "//input[@id='login_password']").send_keys("") driver.find_element(By.XPATH, "//button[@id='kt_login_signin_submit']").click() elif site_type == "hr": driver.get("https://test-hr.mednefits.com/login") driver.find_element(By.XPATH, "//input[@placeholder='Email']").send_keys("") driver.find_element(By.XPATH, "//button[normalize-space()='Continue']").click() driver.find_element(By.XPATH, "//input[@placeholder='Password']").send_keys("") driver.find_element(By.XPATH, "//button[@id='kt_login_signin_submit']").click() request.cls.driver = driver yield driver.quit()
使用方式
- 测试Site A时执行命令:
pytest --browser chrome --site admin --html=report.html
- 测试Site B时执行命令:
pytest --browser chrome --site hr --html=report.html
运行后生成的HTML报告标题会自动匹配所选站点。
内容的提问来源于stack exchange,提问作者Kris -
相关产品推荐
相关产品推荐

