Pytest-Bdd-Playwright
时间: 2025-01-07 21:54:57 浏览: 8
### 使用 Pytest-Playwright 进行行为驱动开发测试
#### 安装依赖库
为了使用 `pytest-bdd-playwright` 工具,需先安装必要的 Python 库。可以通过 pip 来完成这些包的安装。
```bash
pip install pytest-bdd playwright
```
#### 创建项目结构
合理的目录布局有助于管理测试用例及其关联资源。通常情况下,会建立如下所示的基础架构:
```
project_root/
├── features/ # 存放 Gherkin 编写的特性文件(.feature)
│ └── search.feature # 特定场景描述
├── tests/ # 测试实现代码所在位置
│ ├── __init__.py # 初始化模块
│ └── test_search.py # 实现具体测试方法的地方
└── steps/ # 步骤定义的位置
├── __init__.py
└── search_steps.py # 对应 feature 文件中的 Given When Then 的解释
```
#### 编写 Feature 文件
在 `features/search.feature` 中按照 BDD 规范书写业务需求文档。这里展示了一个简单的例子来说明如何查找关键词并验证结果页面上的内容[^4]。
```gherkin
Feature: Search functionality on website
Scenario Outline: Perform a successful search with keyword "<keyword>"
Given I am on the homepage of "example.com"
When I enter "<keyword>" into the search box and submit it
Then The result page should contain results related to "<expected_result>"
Examples:
| keyword | expected_result |
| python | Python programming... |
| automation | Automation tools guide |
Scenario: Failed search due to invalid input
Given I am on the homepage of "example.com"
When I leave the search field empty and press Enter
Then An error message appears indicating that no query was entered
```
#### 实现 Step Definitions
接下来,在 `steps/search_steps.py` 中为上述每一步提供具体的实现逻辑。这涉及到了解网页交互细节以及利用 Playwright API 操作浏览器实例。
```python
from playwright.sync_api import sync_playwright
import pytest
from pytest_bdd import scenarios, given, when, then
scenarios('../features/search.feature')
@given('I am on the homepage of "{url}"')
def open_homepage(context, url):
context.page.goto(url)
@when('I enter "{text}" into the search box and submit it')
def perform_search(context, text):
context.page.fill('#search-input', text)
context.page.click('#submit-button')
@then('The result page should contain results related to "{result_text}"')
def verify_results(context, result_text):
assert result_text in context.page.text_content('.results-container')
@when('I leave the search field empty and press Enter')
def attempt_empty_query(context):
context.page.press('#search-input', 'Enter')
@then('An error message appears indicating that no query was entered')
def check_error_message(context):
alert = context.page.query_selector('.alert-error').inner_text()
assert 'Please provide a valid search term' in alert
```
#### 执行测试案例
最后,可以在命令行中指定要运行的具体测试文件或整个套件来进行实际执行操作。对于单个文件而言,只需给出路径即可;如果想要覆盖更多范围,则可以省略参数让其自动发现所有符合条件的 `.py` 脚本[^1]。
```bash
pytest ./tests/test_search.py
```
阅读全文