使用类作用域Fixture时,Pytest Playwright如何多浏览器运行测试?
Pytest Playwright多浏览器运行基于类的测试问题
我希望使用Pytest Playwright多浏览器运行测试,例如执行命令pytest --browser firefox --browser webkit。
该命令在如下函数式测试中可正常工作:
import pytest from playwright.sync_api import Page @pytest.mark.playwright def test_liveserver_with_playwright(page: Page, live_server): page.goto(f"{live_server.url}/") # etc.
测试会执行两次,对应每个浏览器配置各一次。
但在使用基于类的测试时(基类中使用自动生效的Fixture):
import pytest import unittest from playwright.sync_api import Page @pytest.mark.playwright class PlaywrightTestBase(unittest.TestCase): @pytest.fixture(autouse=True) def playwright_liveserver_init(self, page: Page, live_server): self.page = page # etc. class FrontpageTest(PlaywrightTestBase): def test_one_thing(self): self.page.goto("...") # etc
测试仅运行一次,多浏览器配置被忽略。请问我遗漏了什么?是否有办法让此类测试也支持多浏览器运行?
问题原因
问题核心在于你继承了unittest.TestCase:
- Pytest Playwright的多浏览器逻辑是通过参数化
pagefixture实现的,但unittest测试类的执行模型和原生pytest测试类不同,不会自动继承pytest的参数化规则。 - 当测试类继承
unittest.TestCase时,pytest会将其当作unittest用例处理,跳过pytest-playwright的多浏览器参数化流程。
解决方法
方案1:改用pytest原生测试类(推荐)
放弃继承unittest.TestCase,使用pytest原生的测试类写法,这样就能自动适配多浏览器参数化:
import pytest from playwright.sync_api import Page @pytest.mark.playwright class PlaywrightTestBase: @pytest.fixture(autouse=True) def playwright_liveserver_init(self, page: Page, live_server): self.page = page # etc. class FrontpageTest(PlaywrightTestBase): def test_one_thing(self): self.page.goto("...") # etc
执行pytest --browser firefox --browser webkit后,测试会按每个浏览器各运行一次。
方案2:手动为unittest测试类添加参数化
如果必须保留unittest.TestCase继承,可以手动给测试类添加浏览器参数化:
import pytest import unittest from playwright.sync_api import BrowserType @pytest.mark.playwright @pytest.mark.parametrize("browser_name", ["firefox", "webkit"]) class PlaywrightTestBase(unittest.TestCase): @pytest.fixture(autouse=True) def playwright_liveserver_init(self, browser_name: str, browser: BrowserType, live_server): self.page = browser.new_page() # 测试完成后关闭页面 yield self.page.close() class FrontpageTest(PlaywrightTestBase): def test_one_thing(self): self.page.goto("...") # etc
这种写法需要手动管理页面生命周期,不如方案1简洁。
关键注意点
- 避免混合使用unittest测试类和pytest的fixture参数化特性,两者的执行逻辑存在差异。
- pytest-playwright的
--browser参数仅对pytest原生的测试函数/类生效,unittest风格的测试需要额外处理。
内容的提问来源于stack exchange,提问作者mfit
相关产品推荐
相关产品推荐

