如何为测试函数创建pytest fixture?执行时提示无测试用例
解决pytest + Selenium测试提示“no tests were found an empty suite”及fixture正确实现问题
问题核心问题点
你的代码存在多个不符合pytest规范的问题,直接导致测试无法被识别、fixture失效:
- fixture定义语法完全错误(比如
expected_min_score=4()这种写法不符合Python函数定义规则) - 错误地将测试流程函数
test_open_browser标记为fixture,未将浏览器驱动实例作为fixture提供给测试函数 - 独立测试函数与测试类分离,依赖的
driver实例未正确传递 - 原测试逻辑中直接用元素对象做数值比较,未提取文本并转换为可比较的数值类型
- 未对Selenium浏览器实例做资源清理
修正后的完整代码
import pytest from selenium import webdriver from selenium.common import NoSuchElementException from selenium.webdriver.common.by import By @pytest.fixture(scope="module") def driver(): # 初始化浏览器驱动 driver = webdriver.Chrome() driver.maximize_window() driver.implicitly_wait(10) yield driver # 将driver实例传递给测试函数 # 测试完成后自动清理资源 driver.quit() @pytest.fixture(scope="module") def navigate_to_target_product(driver): # 封装导航到目标商品的前置操作,避免重复代码 driver.get("https://www.amazon.com/") driver.find_element(By.ID, "nav-hamburger-menu").click() driver.find_element(By.XPATH, "//div[@id='hmenu-content']/ul/li[10]/a/div").click() driver.find_element(By.LINK_TEXT, "Beading & Jewelry Making").click() driver.find_element(By.XPATH, "//li[@id='n/12896151']/span/a/span").click() driver.find_element(By.ID, "a-autoid-0-announce").click() driver.find_element(By.ID, "s-result-sort-select_2").click() driver.find_element(By.XPATH, "//div[@id='search']/div/div/div/span/div/div[4]/div/div/div/div/div[2]/div/h2/a/span").click() def test_customer_review_score(navigate_to_target_product, driver, expected_min_score=4): try: # 提取评分文本并转换为浮点数 score_text = driver.find_element(By.ID, "acrCustomerReviewText").text review_score = float(score_text.split()[0]) assert review_score >= expected_min_score, f"当前评分{review_score}低于预期最小值{expected_min_score}" except NoSuchElementException: assert False, "页面未找到评分元素" except (ValueError, IndexError): assert False, "无法解析评分数值" def test_product_price(navigate_to_target_product, driver, expected_price_limit=3500): try: # 处理亚马逊价格格式,提取纯数值 price_text = driver.find_element(By.ID, "corePriceDisplay_desktop_feature_div").text.strip() price_num = float(price_text.replace("$", "").replace(",", "")) assert price_num <= expected_price_limit, f"当前价格{price_num}超过预期上限{expected_price_limit}" except NoSuchElementException: assert False, "页面未找到价格元素" except (ValueError, IndexError): assert False, "无法解析价格数值"
关键实现说明
- driver fixture:用
yield实现资源初始化与自动清理,scope="module"表示整个测试模块只启动一次浏览器,提升执行效率 - 导航前置fixture:将重复的页面导航步骤封装为fixture,所有依赖该fixture的测试函数都会自动执行导航操作
- 测试函数规范:
- 所有测试函数以
test_开头,确保pytest能自动识别 - 通过参数声明依赖的fixture(比如
driver、navigate_to_target_product),pytest会自动注入实例 - 修复数值解析逻辑,适配亚马逊页面的文本格式,确保比较逻辑有效
- 所有测试函数以
内容的提问来源于stack exchange,提问作者Najib Shehu
相关产品推荐
相关产品推荐

