python中playwright结合pytest执行用例的实现
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执行用例内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: Python中的随机函数random详解