UI自动化-Playwright+pytest探索之旅(二)搭建工程
2024.01.17 23:56浏览量:16简介:本文将介绍如何使用Playwright和pytest搭建一个简单的UI自动化工程。我们将从环境准备、项目结构、编写测试用例等方面进行详细讲解,旨在帮助读者快速入门UI自动化测试。
在上一篇文章中,我们简要介绍了Playwright和pytest这两个工具,以及它们在UI自动化测试中的优势。接下来,我们将深入探讨如何使用这些工具搭建一个实际的工程。
一、环境准备
首先,确保你的系统已经安装了Node.js和Python。你可以访问Node.js和Python的官方网站下载并安装最新版本。
接下来,安装Playwright库。打开终端或命令提示符,运行以下命令:
npm install playwright
对于Python用户,可以使用pip安装pytest和pytest-asyncio:
pip install pytest pytest-asyncio
二、项目结构
创建一个新的文件夹作为项目的根目录,并在其中创建以下文件和文件夹结构:
my_ui_test_project/├── tests/│ ├── test_example.py│ └── fixtures/│ └── browser.py└── playwright.config.js
tests文件夹用于存放测试用例文件。你可以根据需要创建更多的测试文件。fixtures文件夹用于存放一些辅助函数或配置。在我们的例子中,我们将创建一个浏览器实例的辅助函数。playwright.config.js是Playwright的配置文件,用于定义全局的配置选项。
三、编写测试用例和辅助函数
打开tests/test_example.py文件,编写一个简单的测试用例:
上面的测试用例使用了pytest的asyncio装饰器,这意味着它是一个异步测试。我们还需要编写一个fixture来创建一个浏览器实例。打开import pytestfrom fixtures import browser@pytest.mark.asyncioasync def test_example():page = await browser.new_page() # 使用fixture创建新页面await page.goto('https://example.com') # 导航到网页# 这里添加断言来验证网页是否符合预期
fixtures/browser.py文件,编写以下代码:python from playwright import sync_playwright as playwright def browser(): with playwright() as playwright_context: browser = playwright_context.chromium.launch() # 启动Chromium浏览器实例 yield browser # 返回浏览器实例供测试使用 browser.close() # 关闭浏览器实例这个辅助函数使用Playwright库来启动一个Chromium浏览器实例,并在测试完成后关闭它。请注意,我们使用了yield关键字来在关闭浏览器之前返回浏览器实例。这样,每个测试用例都可以使用这个浏览器实例。四、运行测试打开终端或命令提示符,进入项目根目录,运行以下命令来执行测试:
对于Node.js用户:
```arduino
npx pytest tests/ -s -v —playwright —browser=chromium —headless —timeout=30000 —slow-tests=10000 —random=off —debug-mode —capture=no-stdio —engine=jsdom —parallel —junitxml=junit-results.xml —output=junit-results.xml —html=junit-results.html —disable-flaky-tests —color=yes —max-diffsize=100 —max-difflines=100 —max-diffpercent=50 —no-assertions-rejection —no-assertions-timeout —no-assertions-maxdepth —no-assertions-mindepth —no-assertions-checkallskips —no-assertions-maxerrormessagelength —no-assertions-maxcontextlines —no-assertions-mincontextlines —no-assertions-checkdocstyle —no-assertions-maxcharslastassert —no-assertions-maxcharslastcheck —no-assertions-maxcharslastskippedcheck —no-assertions-checkskippedlines —no-assertions-checkskippedcontextlines —no-assertions-checktypestyle —no-assertions-checktypestylecontextlines —no-assertions-checktypestylecontextskippedlines —no-assertions-checktypestylecontextskippedcontextlines —no-assertions-checktypestylelastskippedcheck —no-assertions-checktypestylelastskippedcontextcheck —

发表评论
登录后可评论,请前往 登录 或 注册