使用pytest运行Selenium测试遇导入及Fixture问题求助
pytest测试运行问题排查与修复建议
问题汇总
- 执行测试时抛出
AttributeError: 'TestSignUp' object has no attribute 'implicitly_wait'错误 - 在
tests目录下执行pytest --fixtures无法看到根目录conftest.py中定义的browserfixture - 新建测试项目显示“未运行测试”,但浏览器实例能正常启动
项目结构
项目根目录/ ├── conftest.py ├── pages/ │ ├── base_page.py │ └── locators.py └── tests/ └── test_base_page.py
逐个问题修复
1. 修复AttributeError错误
原因:类中的测试方法缺少self参数,pytest会将第一个参数browser识别为TestSignUp类的实例对象,而非定义的fixture。当这个实例被传入BasePage的__init__方法后,调用browser.implicitly_wait()自然会报错——因为TestSignUp实例没有这个方法。
修复代码(修改tests/test_base_page.py):
from pages.base_page import BasePage link = "https://somelink.com/" class TestSignUp(): def test_see_sign_up(self, browser): page = BasePage(browser, link) page.open() page.should_be_sign_up_button() def test_open_sign_up_modal(self, browser): page = BasePage(browser, link) page.open() page.open_sign_up_modal()
2. 解决fixture无法识别的问题
原因:pytest只会加载当前执行目录及子目录下的conftest.py。你在tests目录下执行命令,根目录的conftest.py不会被加载,因此看不到browser fixture。
解决方法:切换到项目根目录执行pytest命令,比如:
# 运行指定测试文件 pytest tests/test_base_page.py -v # 查看所有可用fixture pytest --fixtures
3. 解决“未运行测试”提示问题
检查以下几点:
- 测试文件命名必须符合pytest规则:以
test_开头,或以_test.py结尾 - 测试类必须以
Test开头,且不能定义__init__方法 - 测试方法必须以
test_开头 - 确保在项目根目录执行pytest命令,而非
tests子目录
4. 修复断言参数顺序错误(隐性问题)
base_page.py中两个断言的错误信息传参位置错误,is_element_present方法仅接收how和what两个参数,错误信息应放在assert语句的第二个位置:
修复代码(修改pages/base_page.py):
def should_be_sign_up_button(self): # 调整错误信息到assert的第二个参数 assert self.is_element_present(*BasePageLocators.SIGN_UP), "No Sign Up button on the page" def open_sign_up_modal(self): self.browser.find_element(*BasePageLocators.SIGN_UP).click() # 同样调整错误信息位置 assert self.is_element_present(*BasePageLocators.CREATE_ACCOUNT_H2), "Sign Up modal is not open"
内容的提问来源于stack exchange,提问作者Mnnkv
相关产品推荐
相关产品推荐

