Playwright+Pytest自动化实践

点击名片关注 阿尘blog,一起学习,一起成长

本部分内容主要测试将playwright实际用于pytest的可行性

事实证明:确实很简单

网上有许多可用于测试Web UI自动化的网站,这里我们直接挑选一个电商网站作为测试实践

测试网站:https://www.saucedemo.com/

1、开始录制脚本

首先尝试看看能否录制pytest

python -m playwright codegen -o "D:\PythonProject\playwright_project2\code.py" --target python-pytest
结果:
from playwright.sync_api import Page, expect




def test_example(page: Page) -> None:
    page.goto("https://www.saucedemo.com/")
    page.locator("[data-test=\"username\"]").click()
    page.locator("[data-test=\"username\"]").fill("standard_user")
    page.locator("[data-test=\"password\"]").click()
    page.locator("[data-test=\"password\"]").fill("secret_sauce")
    page.locator("[data-test=\"login-button\"]").click()
    page.locator("[data-test=\"add-to-cart-sauce-labs-backpack\"]").click()
    page.locator("[data-test=\"add-to-cart-sauce-labs-bolt-t-shirt\"]").click()
    page.locator("[data-test=\"add-to-cart-sauce-labs-onesie\"]").click()
    page.locator("a").filter(has_text="3").click()
    page.locator("[data-test=\"checkout\"]").click()
    page.locator("[data-test=\"cancel\"]").click()
    page.get_by_text("Swag Labs").click()

这似乎并没有不同,看来不符合自己的预期不能自动实现与pytest的结合,这样看来其实我们用到的也只是playwright的元素定位,那么我们换回默认的录制方法:

python -m playwright codegen -o "D:\PythonProject\playwright_project2\code.py"
登录录制脚本如下:
from playwright.sync_api import Playwright, sync_playwright, expect




def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://www.saucedemo.com/")
    page.get_by_text("Accepted usernames are:standard_userlocked_out_userproblem_userperformance_glitc").dblclick()
    page.locator("[data-test=\"username\"]").click()
    page.locator("[data-test=\"username\"]").fill("standard_user")
    page.locator("[data-test=\"password\"]").click()
    page.locator("[data-test=\"password\"]").fill("secret_sauce")
    page.locator("[data-test=\"login-button\"]").click()


    # ---------------------
    context.close()
    browser.close()




with sync_playwright() as playwright:
    run(playwright)

2、编写一个验证登录的测试用例

先下载pytest框架

pip install pytest -i http://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn

一个测试用例,把它分为page层,用于管理公共元素;case_data 层用于储存数据,便于管理;testcase层用于编写测试用例,其中结合PO封装模式实现元素操作,结合pytest.mark.paramtrize实现参数化、结合pytest.fixture实现预处理

目录架构图:

db97c5c3158821240a94f44d40d78305.png

现在我们开始将元素定位扔到page层面

login_ele = {"username": "[data-test=\'username\']",
             "password" : "[data-test=\'password\']",
             "login_button" : "[data-test=\'login-button\']",
             "Swag_Labs" : 'Swag Labs'}

接着定义数据层:

先定义一个用例的数据

url = 'https://www.saucedemo.com/'
success_login = [{'username':'standard_user',
                  'password':'secret_sauce',
                  'expect_url':'https://www.saucedemo.com/inventory.html',
                  'erro_info1':'wrong net address',
                  'expect_text':'Swag Labs',
                  'erro_info2':'wrong page text'}]

再来定义前置,打开conftest.py

import pytest
from case_data.login_data import url
from playwright.sync_api import sync_playwright
@pytest.fixture(scope="class")
def every_one():
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch()
        context = browser.new_context()
        page =context.new_page()
        page.goto(url)
        yield page
        context.close()
        page.close()

接下来正式编辑用例层

import case_data.login_data as lg
import page.page_index as pg
import pytest
class Test_login():
    @pytest.mark.parametrize('info',lg.success_login)
    def test_login(self,every_one,info):
        page = every_one
        page.locator(pg.login_ele['username']).fill(info['username'])
        page.locator(pg.login_ele['password']).fill(info['password'])
        page.locator(pg.login_ele['login_button']).click()
        aspect_url = page.url
        expect_url = info['expect_url']
        aspect_text = page.get_by_text(pg.login_ele['Swag_Labs']).text_content()
        expect_text = info['expect_text']
        assert aspect_url == expect_url,info['erro_info1']
        assert aspect_text == expect_text,info['erro_info2']




if __name__ == '__main__':
    pytest.main()

运行结果:

e90ca9924a9f3b729c47d46431cd99d7.png

好了今天到这,浅尝辄止,更多用例以及结合allure报告就没有多大差别,可以参考以往文章Python-Ui自动化测试

注意事项(避坑):

1、文件名一定要正确,测试用例层的类名和方法名一定要正确 

2、尽量不要更改文件名,不要直接把录制脚本的文件名直接改为用例层的文件名,如果改了,就把代码复制重新粘贴一遍,正常先把目录创建好再挨个编辑 

3、前置一定要用with 关键字,不要和网上那样,否则会报错

错误示例:以下都会导致前置启动失败

@pytest.fixture(scope="function")
def preview(page):
    page.goto(pg.url)
    page.click(pg.popup)
    yield page
    page.close()
 #*********或者*****
from playwright.sync_api import Playwright
import pytest
import case_data.login_data as lg


@pytest.fixture(scope='class')
def every_test(playwright:Playwright):
    # 定义前置,开启用例场景打开page
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.goto(lg.url)
    yield page
    #定义后置
    context.close()
    page.close()

扫描二维码关注阿尘blog,一起交流学习

3e7ce29a839f9120e846bae5946357f3.png

Playwright+Pytest是一种常用的自动化测试框架组合,用于编写和执行Web应用程序的自动化测试。下面是一个简单的示例,展示了如何使用PlaywrightPytest进行自动化测试: 首先,确保已经安装了PlaywrightPytest模块。可以使用以下命令进行安装: ``` pip install playwright pytest ``` 接下来,创建一个pytest测试文件,例如 `test_example.py`,并导入所需的模块: ```python import pytest from playwright.sync_api import Playwright, sync_playwright # 使用fixture装饰器,创建一个Playwright实例 @pytest.fixture(scope="session") def playwright() -> Playwright: with sync_playwright() as playwright: yield playwright # 编写一个基本的测试用例 def test_example(playwright): # 启动一个浏览器实例 browser = playwright.chromium.launch() # 创建一个页面对象 page = browser.new_page() # 导航到目标网页 page.goto("https://www.example.com") # 断言页面标题 assert page.title() == "Example Domain" # 关闭浏览器 browser.close() ``` 在上面的示例中,使用`@pytest.fixture`装饰器创建了一个Playwright实例,作为测试用例的前置条件。然后,使用`playwright`夹具作为参数传递给测试用例函数。在测试用例中,使用Playwright的功能来启动浏览器、创建页面对象、导航到网页,并进行断言验证。 最后,使用以下命令运行测试: ``` pytest test_example.py ``` 这是一个简单的Playwright+Pytest自动化框架的示例,你可以根据实际需求扩展和定制测试用例。希望对你有帮助!如果你有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是阿尘呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值