python中playwright结合pytest执行用例的实现

目录
  • 安装pytest插件
  • 编写测试用例
  • 忽略 HTTPS 错误和设置自定义视口大小
  • 持久上下文

playwright结合Pytest为您的 Web 应用程序编写端到端的测试。

安装pytest插件

C:\Users\lifeng01>pip install pytest-playwright
Collecting pytest-playwright
  Using cached pytest_playwright-0.2.2-py3-none-any.whl (9.8 kB)
Requirement already satisfied: pytest in d:\python\python37\lib\site-packages (from pytest-playwright) (6.2.5)
Requirement already satisfied: playwright>=1.13 in d:\python\python37\lib\site-packages (from pytest-playwright) (1.17.0)
Requirement already satisfied: python-slugify in d:\python\python37\lib\site-packages (from pytest-playwright) (5.0.2)
Requirement already satisfied: pytest-base-url in d:\python\python37\lib\site-packages (from pytest-playwright) (1.4.2)
Requirement already satisfied: typing-extensions in d:\python\python37\lib\site-packages (from playwright>=1.13->pytest-playwright) (3.7.4.3)
Requirement already satisfied: pyee>=8.0.1 in d:\python\python37\lib\site-packages (from playwright>=1.13->pytest-playwright) (8.2.2)
Requirement already satisfied: websockets>=8.1 in d:\python\python37\lib\site-packages (from playwright>=1.13->pytest-playwright) (9.1)
Requirement already satisfied: greenlet>=1.0.0 in d:\python\python37\lib\site-packages (from playwright>=1.13->pytest-playwright) (1.0.0)
Requirement already satisfied: atomicwrites>=1.0 in d:\python\python37\lib\site-packages (from pytest->pytest-playwright) (1.3.0)
Requirement already satisfied: attrs>=19.2.0 in d:\python\python37\lib\site-packages (from pytest->pytest-playwright) (19.3.0)
Requirement already satisfied: py>=1.8.2 in d:\python\python37\lib\site-packages (from pytest->pytest-playwright) (1.9.0)
Requirement already satisfied: toml in d:\python\python37\lib\site-packages (from pytest->pytest-playwright) (0.10.0)
Requirement already satisfied: colorama in d:\python\python37\lib\site-packages (from pytest->pytest-playwright) (0.4.3)
Requirement already satisfied: pluggy<2.0,>=0.12 in d:\python\python37\lib\site-packages (from pytest->pytest-playwright) (0.13.1)
Requirement already satisfied: packaging in d:\python\python37\lib\site-packages (from pytest->pytest-playwright) (20.9)
Requirement already satisfied: importlib-metadata>=0.12 in d:\python\python37\lib\site-packages (from pytest->pytest-playwright) (1.7.0)
Requirement already satisfied: iniconfig in d:\python\python37\lib\site-packages (from pytest->pytest-playwright) (1.0.1)
Requirement already satisfied: requests>=2.9 in d:\python\python37\lib\site-packages (from pytest-base-url->pytest-playwright) (2.25.0)
Requirement already satisfied: text-unidecode>=1.3 in d:\python\python37\lib\site-packages (from python-slugify->pytest-playwright) (1.3)
Requirement already satisfied: zipp>=0.5 in d:\python\python37\lib\site-packages (from importlib-metadata>=0.12->pytest->pytest-playwright) (3.1.0)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\python\python37\lib\site-packages (from requests>=2.9->pytest-base-url->pytest-playwright) (1.26.2)
Requirement already satisfied: certifi>=2017.4.17 in d:\python\python37\lib\site-packages (from requests>=2.9->pytest-base-url->pytest-playwright) (2020.4.5.1)
Requirement already satisfied: idna<3,>=2.5 in d:\python\python37\lib\site-packages (from requests>=2.9->pytest-base-url->pytest-playwright) (2.9)
Requirement already satisfied: chardet<4,>=3.0.2 in d:\python\python37\lib\site-packages (from requests>=2.9->pytest-base-url->pytest-playwright) (3.0.4)
Requirement already satisfied: pyparsing>=2.0.2 in d:\python\python37\lib\site-packages (from packaging->pytest->pytest-playwright) (2.4.7)
Installing collected packages: pytest-playwright
Successfully installed pytest-playwright-0.2.2

编写测试用例

import pytest
from playwright.sync_api import Page

def test_baidu_com(page: Page):

    page.goto("https://www.baidu.com")
    # xpath定位输入框,输入文本内容
    page.fill('//*[@id="kw"]', "秦时明月")
    # css点位点击“百度一下”按钮
    page.click('#su')
    # 打印title名称
    print(page.title)

if __name__ == '__main__':
    pytest.main(["-v", "test_baidu_example.py"])

名词解释:

test_baidu_com(page: Page):自动完成配置类型 ( page是pytest_playwright插件提供的一个夹函数,page指定到类型为Page,Page是playwright库提供的一个类,page指定类型为Page就可以调用Page类中的一些列方法 )

命令行输入命令执行:

PS F:\project_gitee\Test\playwrightProject\cases> pytest --browser chromium --video on
================================================================================== test session starts ==================================================================================
platform win32 -- Python 3.7.7, pytest-6.2.5, py-1.9.0, pluggy-0.13.1
rootdir: F:\project_gitee\Test\playwrightProject\cases
plugins: allure-pytest-2.9.43, anyio-3.3.4, base-url-1.4.2, clarity-1.0.1, cov-2.8.1, emoji-0.2.0, forked-1.3.0, html-3.1.1, lazy-fixture-0.6.3, metadata-1.11.0, pikachu-0.1.0, playwrigh
t-0.2.2, rerunfailures-9.1.1, xdist-2.2.1
collected 1 item                                                            

test_baidu_example.py .                                                                                                                                                           [100%]

=================================================================================== 1 passed in 1.97s ===================================================================================

命令行常用基础命令:

# 运行测试
pytest 

# 开启页面运行
pytest --headed

# 指定浏览器运行
pytest --browser firefox

# 开启页面运行并指定浏览器运行
pytest --headed --browser firefox

# 指定两个浏览器运行,优先运行火狐再运行谷歌
pytest --browser firefox --browser chromium

# 使用浏览器频道,支持谷歌浏览器(我的电脑其他浏览器是报错的)
pytest --browser-channel chromium

# 用慢动作运行测试
pytest --slowmo 100

# 指定谷歌浏览器,开启记录每次测试的轨迹(生成一个.zip包,存放在test-results文件夹中)
pytest --browser chromium --tracing on(on:开;off:关)

# 指定谷歌浏览器,开启每次测试录制视频(生成一个.webm包,存放在test-results文件夹中)
pytest --browser chromium --video on(on:开;off:关)

# 指定谷歌浏览器,开启每次测试后是否自动截屏(生成一个.png图片,存放在test-results文件夹中)
pytest --browser chromium --screenshot on

通过浏览器跳过测试:

import pytest
from playwright.sync_api import Page

@pytest.mark.skip_browser("firefox")
def test_baidu_com(page: Page):

    page.goto("https://www.baidu.com")
    # xpath定位输入框,输入文本内容
    page.fill('//*[@id="kw"]', "秦时明月")
    # css点位点击“百度一下”按钮
    page.click('#su')
    # 打印title名称
    print(page.title)

if __name__ == '__main__':
    pytest.main(["-v", "test_baidu_example.py"])

在特定浏览器上运行:

import pytest
from playwright.sync_api import Page

@pytest.mark.only_browser("chromium")
def test_baidu_com(page: Page):

    page.goto("https://www.baidu.com")
    # xpath定位输入框,输入文本内容
    page.fill('//*[@id="kw"]', "秦时明月")
    # css点位点击“百度一下”按钮
    page.click('#su')
    # 打印title名称
    print(page.title)

if __name__ == '__main__':
    pytest.main(["-v", "test_baidu_example.py"])

忽略 HTTPS 错误和设置自定义视口大小

第一种是写在conftest.py中,然后直接运行测试用例:

# conftest.py

import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {
        **browser_context_args,
        "ignore_https_errors": True,
    }

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {
        **browser_context_args,
        "viewport": {
            "width": 1920,
            "height": 1080,
        }
    }

测试用例写法如下(最好这样写,不然运行就报错,作者已采坑):

import pytest
from playwright.sync_api import Page

def test_example(page: Page):
    page.goto("http://www.baidu.com")
    assert page.title() == "百度一下,你就知道"

    page.close()

if __name__ == '__main__':
    pytest.main(["-v", "test_example.py"])

命令行运行测试用例:

PS F:\project_gitee\Test\playwrightProject\cases> pytest --headed --browser chromium
================================================================================== test session starts ==================================================================================
platform win32 -- Python 3.7.7, pytest-6.2.5, py-1.9.0, pluggy-0.13.1
rootdir: F:\project_gitee\Test\playwrightProject\cases
plugins: allure-pytest-2.9.43, anyio-3.3.4, asyncio-0.16.0, base-url-1.4.2, clarity-1.0.1, cov-2.8.1, emoji-0.2.0, forked-1.3.0, html-3.1.1, lazy-fixture-0.6.3, metadata-1.11.0, pikachu-
0.1.0, playwright-0.2.2, rerunfailures-9.1.1, xdist-2.2.1
collected 1 item                                                                                                                                                                         

test_example.py .                                                                                                                                                                  [100%]

=================================================================================== 1 passed in 2.39s ===================================================================================

第二种是直接在用例中增加指定参数即可:

import pytest
from playwright.sync_api import sync_playwright

def test_example():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_context(
            ignore_https_errors=True,
            viewport={
                "width": 1920,
                "height": 1040,
            }
        )
        page = page.new_page()
        page.goto("http://www.baidu.com")
        assert page.title() == "百度一下,你就知道"
        browser.close()

if __name__ == '__main__':
    pytest.main(["-v", "test_example.py"])

名词解释:
p.chromium.launch(headless=False):headless=False是开启有页面运行(默认是True,也就是无头浏览器)

第三种是模拟手机浏览器

# conftest.py

import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args, playwright):
    iphone_11 = playwright.devices['iPhone 11 Pro']
    return {
        **browser_context_args,
        **iphone_11,
    }

测试用例写法如下(最好这样写,不然运行就报错,作者已采坑):

import pytest
from playwright.sync_api import Page

def test_example(page: Page):
    page.goto("http://www.baidu.com")
    assert page.title() == "百度一下,你就知道"

    page.close()

if __name__ == '__main__':
    pytest.main(["-v", "test_example.py"])

命令行运行测试用例:

PS F:\project_gitee\Test\playwrightProject\cases> pytest --headed --browser chromium
================================================================================== test session starts ==================================================================================
platform win32 -- Python 3.7.7, pytest-6.2.5, py-1.9.0, pluggy-0.13.1
rootdir: F:\project_gitee\Test\playwrightProject\cases
plugins: allure-pytest-2.9.43, anyio-3.3.4, asyncio-0.16.0, base-url-1.4.2, clarity-1.0.1, cov-2.8.1, emoji-0.2.0, forked-1.3.0, html-3.1.1, lazy-fixture-0.6.3, metadata-1.11.0, pikachu-
0.1.0, playwright-0.2.2, rerunfailures-9.1.1, xdist-2.2.1
collected 1 item                                                                                                                                                                         

test_example.py F                                                                                                                                                                  [100%]

======================================================================================= FAILURES ========================================================================================
________________________________________________________________________________ test_example[chromium] _________________________________________________________________________________

page = <Page url='https://m.baidu.com/?from=844b&vit=fps'>

    def test_example(page: Page):
        page.goto("http://www.baidu.com")
>       assert page.title() == "百度一下,你就知道"
E       AssertionError: assert '百度一下' == '百度一下,你就知道'
E         - 百度一下,你就知道
E         + 百度一下

test_example.py:15: AssertionError
================================================================================ short test summary info ================================================================================
FAILED test_example.py::test_example[chromium] - AssertionError: assert '百度一下' == '百度一下,你就知道'
=================================================================================== 1 failed in 3.14s ===================================================================================

这里运行后,打开的web页面,是一个手机形状的页面,仿的是手机浏览器(代码中指定的是iPhone 11 Pro)

持久上下文

它的意思就是打开一个web页面,会在这个web页面开多个新标签页面去执行测试用例。

例如:我有两个测试用例需要执行,如果使用持久上下文,就会打开一个web页面,然后web页面的第一个标签页运行第一个测试用例,第二个标签页运行第二个测试用例,直到把所有测试用例运行完了,关闭整个web页面,结束。

当然,如果你没有使用持久上下文,那就是打开web页面执行第一个测试用例,执行完第一个测试用例关闭web页面,然后再打开web页面执行第二个测试用例,执行完第二个测试用例关闭web页面,结束。

import pytest
from playwright.sync_api import BrowserType
from typing import Dict

@pytest.fixture(scope="session")
def context(
    browser_type: BrowserType,
    browser_type_launch_args: Dict,
    browser_context_args: Dict
):
    context = browser_type.launch_persistent_context("./data", **{
        **browser_type_launch_args,
        **browser_context_args,
        "locale": "de-DE",
    })

    yield context

    context.close()

名词解释:

  • ./data用户数据目录的路径,它存储浏览器会话数据,如cookie和本地存储。
  • browser_type_launch_args如果没有设置值,返回的就是一个空字典;它里面的参数就是和p.chromium.launch()中的传参一致的,此处了解下,后面具体介绍。
  • browser_context_args如果没有设置值,返回的就是一个空字典;它里面的参数就和context = browser.new_context()中的传参一致的,此处了解下,后面具体介绍。
  • locale指定用户区域设置,例如' en-GB '、' de-DE '等。

命令行运行测试用例:

PS F:\project_gitee\Test\playwrightProject\cases> pytest --headed --browser chromium
================================================================================== test session starts ==================================================================================
platform win32 -- Python 3.7.7, pytest-6.2.5, py-1.9.0, pluggy-0.13.1
rootdir: F:\project_gitee\Test\playwrightProject\cases
plugins: allure-pytest-2.9.43, anyio-3.3.4, asyncio-0.16.0, base-url-1.4.2, clarity-1.0.1, cov-2.8.1, emoji-0.2.0, forked-1.3.0, html-3.1.1, lazy-fixture-0.6.3, metadata-1.11.0, pikachu-
0.1.0, playwright-0.2.2, rerunfailures-9.1.1, xdist-2.2.1
collected 2 items                                                                                                                                                                        

test_baidu_example.py .                                                                                                                                                            [ 50%]
test_example.py .                                                                                                                                                                  [100%]

=================================================================================== 2 passed in 3.12s ===================================================================================

必须知晓问题:

上述文章中的browser_type_launch_args和browser_context_args都是pytest_playwright插件提供的测试夹会话:
展示pytest_playwright插件部分源码:

@pytest.fixture(scope="session")
def browser_type_launch_args(pytestconfig: Any) -> Dict:
    launch_options = {}
    headed_option = pytestconfig.getoption("--headed")
    if headed_option:
        launch_options["headless"] = False
    browser_channel_option = pytestconfig.getoption("--browser-channel")
    if browser_channel_option:
        launch_options["channel"] = browser_channel_option
    slowmo_option = pytestconfig.getoption("--slowmo")
    if slowmo_option:
        launch_options["slow_mo"] = slowmo_option
    return launch_options

@pytest.fixture(scope="session")
def browser_context_args(
    pytestconfig: Any,
    playwright: Playwright,
    device: Optional[str],
) -> Dict:
    context_args = {}
    if device:
        context_args.update(playwright.devices[device])
    base_url = pytestconfig.getoption("--base-url")
    if base_url:
        context_args["base_url"] = base_url

    video_option = pytestconfig.getoption("--video")
    capture_video = video_option in ["on", "retain-on-failure"]
    if capture_video:
        context_args["record_video_dir"] = artifacts_folder.name

    return context_args

 到此这篇关于python中playwright结合pytest执行用例的实现的文章就介绍到这了,更多相关playwright pytest执行用例内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 如何使用Playwright对Java API实现自动视觉测试

    微软新的端到端浏览器自动化框架Playwright引起了轰动!仅在几个月前,我才试玩了Playwright,当时它是一个仅JavaScript的框架,当得知语言支持已经扩展到我心爱的Java以及Python和C#时,我感到非常惊喜. 借助额外的语言支持以及跨现代浏览器引擎Chromium,Firefox和WebKit执行的能力,这使Playwright与Selenium WebDriver处于同一类别,成为所有需要交叉测试的Web测试人员(不仅是JS)的可行测试解决方案浏览器测试功能,适用于复杂

  • python playwright 自动等待和断言详解

    目录 自动等待及元素执行方法 鼠标双击 获取元素焦点 鼠标悬停 鼠标点击 设置复选框取消或选中 取消已选中复选框取 输入参数 获取元素属性值 获取内部文本 获取内部HTML 获取文本内容 截图 填写文本并触发键盘事件 输入键盘操作 设置select下拉选项 调度事件 检查点(断言) 文字内容断言 内部文字断言 属性断言 复选框断言 js表达式断言 内部HTML断言 元素可见断言 启动状态断言 直接对比断言 总结 自动等待及元素执行方法 操作元素的一系列方法,只要调用了测试夹函数page,就能引出

  • Python开源自动化工具Playwright安装及介绍使用

    目录 1.Playwright介绍 2.Playwright安装 3.实操演示 微软开源了一个非常强大的自动化项目叫 playwright-python 它支持主流的浏览器,包含:Chrome.Firefox.Safari.Microsoft Edge 等,同时支持以无头模式.有头模式运行,并提供了同步.异步的 API,可以结合 Pytest 测试框架 使用,并且支持浏览器端的自动化脚本录制. 项目地址:https://github.com/microsoft/playwright-python

  • 微软开源最强Python自动化神器Playwright(不用写一行代码)

    相信玩过爬虫的朋友都知道selenium,一个自动化测试的神器工具.写个Python自动化脚本解放双手基本上是常规的操作了,爬虫爬不了的,就用自动化测试凑一凑. 虽然selenium有完备的文档,但也需要一定的学习成本,对于一个纯小白来讲还是有些门槛的. 最近,微软开源了一个项目叫「playwright-python」,简直碉堡了!这个项目是针对Python语言的纯自动化工具,连代码都不用写,就能实现自动化功能. 可能你会觉得有点不可思议,但它就是这么厉害.下面我们一起看下这个神器. 1. Pl

  • python+playwright微软自动化工具的使用

    它支持主流的浏览器,包含:Chrome.Firefox.Safari.Microsoft Edge 等,同时支持以无头模式.有头模式运行 playwright-python 提供了同步.异步的 API,可以结合 Pytest 测试框架使用,并且支持浏览器端的自动化脚本录制 项目地址:https://github.com/microsoft/playwright-python 安装playwright-python,执行命令:pip install playwright 安装成功之后,执行命令:p

  • python中playwright结合pytest执行用例的实现

    目录 安装pytest插件 编写测试用例 忽略 HTTPS 错误和设置自定义视口大小 持久上下文 playwright结合Pytest为您的 Web 应用程序编写端到端的测试. 安装pytest插件 C:\Users\lifeng01>pip install pytest-playwright Collecting pytest-playwright Using cached pytest_playwright-0.2.2-py3-none-any.whl (9.8 kB) Requiremen

  • python中windows链接linux执行命令并获取执行状态的问题小结

    目录 前言 环境 工具 库 内容汇总 创建SSHClient 设置链接主机后的策略 链接远程主机 发送命令 获取linux的输出内容 问题总结 解决方式 演示 推送 前言 最新需要做一个小工具,让协作部门能够获取到服务器上的一些资源讯息,因为工具是pyqt写的所以牵扯到用python链接linux的问题,这里记录一下一些碰到的问题 环境 工具 pycharm qt designer 库 python3.7 pyqt5.15.4 paramiko2.12.0 上网搜了很多,发现paramiko实现

  • Python中Playwright 与 pyunit 结合使用详解

    今天来填坑, 昨天说playwright未必一定要使用pytest-playwright包. 它也可以和pyunit一起使用. 那么今天,田辛老师就给大家一个例子, 供大家参考.当然,pytest好用田辛老师之后还是会介绍pytest. 这篇文章只是告诉你,思路要打开: import unittest from playwright.sync_api import Playwright, Browser class MyTests(unittest.TestCase): @classmethod

  • Python中实例化class的执行顺序示例详解

    前言 本文主要介绍了关于Python实例化class的执行顺序的相关内容,下面话不多说了,来一起看看详细的介绍吧 Python里对类的实例化时有怎样的顺序 一般来说一个类里面有类变量和方法,比如我们定义一个名为A的类 class A(): bar = "my lover love me" def __init__(self, name): print('A的class' ,self.__class__, name) 我们在这个类里面定义了一个类变量bar和一个构造方法__init__,

  • python中多个装饰器的执行顺序详解

    装饰器是程序开发中经常会用到的一个功能,也是python语言开发的基础知识,如果能够在程序中合理的使用装饰器,不仅可以提高开发效率,而且可以让写的代码看上去显的高大上^_^ 使用场景 可以用到装饰器的地方有很多,简单的举例如以下场景 引入日志 函数执行时间统计 执行函数前预备处理 执行函数后清理功能 权限校验等场景 缓存 今天讲一下python中装饰器的执行顺序,以两个装饰器为例. 装饰器代码如下: def wrapper_out1(func): print('--out11--') def i

  • 如何在python中写hive脚本

    这篇文章主要介绍了如何在python中写hive脚本,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.直接执行.sql脚本 import numpy as np import pandas as pd import lightgbm as lgb from pandas import DataFrame from sklearn.model_selection import train_test_split from io import St

  • Python中优雅使用assert断言的方法实例

    目录 什么是 assert 断言 断言和异常的使用场景 使用断言的几个原则 建议不使用断言的情况: 总结 什么是 assert 断言 Assert statements are a convenient way to insert debugging assertions into a program 断言声明是用于程序调试的一个便捷方式.断言可以看做是一个 debug 工具,Python 的实现也符合这个设计哲学,在 Python 中 assert 语句的执行是依赖于__debug__这个内置

  • python中pytest收集用例规则与运行指定用例详解

    前言 上篇文章相信大家已经了解了pytest在cmd下结合各种命令行参数如何运行测试用例,并输出我们想要看到的信息.那么今天会讲解一下pytest是如何收集我们写好的用例?我们又有哪些方式来运行单个用例或者批量运行用例呢?下面将为大家一一解答! pytest收集用例原理分析 首先我们按照如下目录结构新建我们的项目 [pyttest搜索测试用例的规则] |[测试用例目录1] | |__init__.py | |test_测试模块1.py | |test_测试模块2.py |[测试用例目录2] |

  • Pytest中skip skipif跳过用例详解

    前言 pytest.mark.skip可以标记无法在某些平台上运行的测试功能, 或者您希望失败的测试功能希望满足某些条件才执行某些测试用例,否则pytest会跳过运行该测试用例 实际常见场景:跳过非Windows平台上的仅Windows测试,或者跳过依赖于当前不可用的外部资源(例如数据库)的测试 @pytest.mark.skip 跳过执行测试用例,有可选参数reason:跳过的原因,会在执行结果中打印 #!/usr/bin/env python # -*- coding: utf-8 -*-

  • python中Pytest常用的插件

    目录 前言 1. 用例依赖 2. 失败重跑 3. 指定用例执行顺序 4. 分布式运行 5. 多重断言 6. 小结 前言 除了框架本身提供的功能外,Pytest还支持上百种第三方插件,良好的扩展性可以更好的满足大家在用例设计时的不同需求.本文将为大家详细介绍下面5项常用的插件. 1. 用例依赖 编写用例的时候,我们会注意用例之间的独立性,但部分用例之间确实存在关联,无法做到彻底独立,那么我们就可以通过使用插件pytest-dependency设置用例之间的依赖关系.当用例A依赖于用例B时,若用例B

随机推荐