1. 查看PlayWright的官方文档
Pytest Plugin Reference | Playwright Python
2. PlayWright + Pytest 执行测试用例
文档中的隔离性也有描述,PlayWright 会在每一个测试用例函数中创建 Context 和 Page 对象。也就说明了每一个测试用例函数都是隔离的。你可以运行下面代码先体验一下:
请确保你正确安装了 PlayWright。并注意相关导入包
class TestBasicMethod:
def test_access_taobao(self, page: Page):
page.goto('https://www.taobao.com')
page.wait_for_timeout(1000)
page.screenshot(path='./taobao.png')
def test_access_jd(self, page: Page):
page.goto('https://www.jd.com')
page.wait_for_timeout(1000)
page.screenshot(path='./jd.png')
你就会发现浏览器启动了两次(context)。每一次有一个 page。
这里你也可以这样理解。反正我是这样理解的。
其实有些场景这样是不适用的,比如登录之后。如果是按照上面的写法,不做其他操作的话,程序运行的情况是不符合预期的。【当然你可以在登录完之后把 Cookie 信息保存起来也可以解决这种场景】。但我们要将的是 Persistent context
3. PlayWright的Persistent context
根据 官方文档表示。使用这个持久化 Context 可以在所有页面共享一个状态。
执行下面的代码看看
# conftest.py
"""
你可以在 pytest_playwright\pytest_playwright.py:309 或者 官方文档中找到是怎么样的写法
"""
@pytest.fixture(scope="session")
def context(
browser_type: BrowserType,
browser_type_launch_args: Dict,
browser_context_args: Dict
):
context = browser_type.launch_persistent_context('./foobar', headless=False ,**{
**browser_type_launch_args,
**browser_context_args
}
)
# context.tracing.start(screenshots=True, snapshots=True, sources=True)
yield context
# context.tracing.stop(path='./trace.zip')
context.close()
# test_persistence.py
class TestContextPersistence:
def test_access_taobao(self, page: Page):
page.goto('https://www.taobao.com')
page.wait_for_timeout(1000)
page.screenshot(path='./taobao.png')
def test_access_jd(self, page: Page):
page.goto('https://www.jd.com')
page.screenshot(path='./jd.png')
你就会发现浏览器启动了一次(context)。会包含两个 page
也就说明了所有的测试用例函数都共用了一些数据。结合登录场景的话,不就是所有的page都是登录状态了?
4. PlayWright 的 同一个 Page。【可选】
还是结合登录场景。假设你要分别测试错误账号和错误密码进行登录。用上面的代码就已经足够了。但是难免有的喜欢只在一个页面操作的(一个 context, 一个 page)
# conftest.py
@pytest.fixture(scope="session")
def context(
browser_type: BrowserType,
browser_type_launch_args: Dict,
browser_context_args: Dict
):
context = browser_type.launch_persistent_context('./foobar', headless=False ,**{
**browser_type_launch_args,
**browser_context_args
}
)
# context.tracing.start(screenshots=True, snapshots=True, sources=True)
yield context
# context.tracing.stop(path='./trace.zip')
context.close()
@pytest.fixture(scope="session")
def page(context):
page = context.new_page()
yield page
page.close()
# test_persistence.py
class TestContextPersistence:
def test_access_taobao(self, page: Page):
page.goto('https://www.taobao.com')
page.wait_for_timeout(1000)
page.screenshot(path='./taobao.png')
def test_access_jd(self, page: Page):
page.goto('https://www.jd.com')
page.screenshot(path='./jd.png')
你就会发现,只会有一个 context 和 一个 page。 当然还有其他的方式也能实现这种效果。
【疑问】其实持久化context中打开浏览器会有一个 blank 的页面。我在网上找也是说这是PlayWright 本身的问题。并不是咋们操作的问题。