Python使用pytest-playwright的原因分析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python使用pytest-playwright的原因分析

田辛 | 田豆芽   2023-03-23 我要评论

pytest-playwright 是一个 Python 包,它允许您使用 Microsoft 的 Playwright 库在 Python 项目中进行端到端测试。

在这篇博客中,田辛老师将向您介绍 pytest-playwright,演示如何安装它,并举例说明如何在您的 Python 项目中使用它。

1 用playwright能不能不用这个包?

首先田辛老师强调,如果你不想使用 pytest-playwright,你仍然可以在你的 Python 项目中使用 Playwright。只不过需要一些额外的配置。 我们会在下次博客中介绍如何PyUnit+playwright。 下面的代码是一个单纯的playwright的例子

from playwright.sync_api import Playwright, sync_playwright_with_browsers

with sync_playwright_with_browsers() as playwright:
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto('https://www.baidu.com')
    browser.close()

此代码使用 sync_playwright_with_browsers() 函数启动 Playwright 实例,启动 Chromium 浏览器,导航至 Google 主页,然后关闭浏览器。只不过Python不会识别它是一段自动化测试代码, 只是当成一段普通的Python程序去运行。

2 安装

安装方法其实田辛老师在前两天的文档里面提过,通过pip进行安装:
pip install pytest-playwright

3 代码和文档

田辛老师还是希望大家去看原始文档的,所以给出如下链接:

pytest-playwright 的官方 Github 存储库:
https://github.com/pytest-playwright/pytest-playwright 。
在这里您可以找到源代码、文档、问题跟踪器和与包相关的其他资源。

pytest-playwright 的官方文档托管在 Read the Docs:
http://pytest-playwright.readthedocs.io/en/latest/
该文档包括安装说明、使用示例、配置选项等。

4 示例代码

以下是如何使用 pytest-playwright 测试一个简单网站的示例:

import pytest  
from playwright.sync_api import Playwright, sync_playwright  
@pytest.fixture(scope='module')  
def playwright() -> Playwright:  
    with sync_playwright() as playwright:  
        yield playwright  
@pytest.fixture(scope='module')  
def browser(playwright: Playwright):  
    browser = playwright.chromium.launch(headless=False)  
    yield browser  
    browser.close()  
@pytest.fixture(scope='module')  
def page(browser):  
    page = browser.new_page()  
    yield page  
    page.close()  
def test_baidu_homepage(page):  
    page.goto('https://www.baidu.com')  
    assert page.title() == '百度一下,你就知道'

以上的代码使用, 创建一个 Playwright 实例,启动一个 Chromium 浏览器,并创建一个新页面。然后使用 test_baidu_homepage 方法使用 page fixture 导航到网站主页并检查页面标题。

要使用 pytest-playwright 运行此测试,请将代码保存到名为 test_baidu.py 的文件中,然后从命令行运行以下命令:

pytest test_google.py

另外这个代码中,田辛老师故意用到了yield的机制, 如果对yield不熟悉的同学可以尝试阅读之前田老师写的这篇文章:【Python】一篇文章读懂yield基本用法

5 结论

pytest-playwright 是一个强大且易于使用的工具,用于在 Python 中自动化浏览器测试。凭借其直观的语法、丰富的功能集和大量的文档,它是任何希望改进其测试工作流程的人的绝佳选择。田辛老师要提醒的是, playwright的使用不一定非使用pytest-playwright, 明天我们会来看看pyunit怎么使用playwright。 虽然麻烦一点,但是田辛老师想说,作为测试人员提升的一个重要逻辑就是:不要对任何技术产生路径依赖。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们