playwright 自动化框架python教程(五)[结合python + pytest + allure 自动化测试实现]

发布于:2024-05-21 ⋅ 阅读:(267) ⋅ 点赞:(0)

playwright 结合python、pytest、allure 自动化测试实现

将 Playwright、pytest 和 Allure 结合起来可以构建一套功能强大、报告美观的自动化测试框架。Allure 是一个广泛使用的测试报告工具,它能够生成详细的、易于阅读的测试报告,包括测试结果、步骤、附件和异常信息等。下面是整合这三个工具的基本步骤:

安装所需库

确保你已安装了 Playwright、pytest、pytest-allure-adaptor 和 Allure 命令行工具。如果尚未安装,可以通过以下命令进行安装:

Bash

1pip install playwright pytest pytest-allure-adaptor allure-python
2playwright install

编写测试用例

继续使用之前提到的 Playwright 和 pytest 示例,但在测试中加入 Allure 的标记和步骤记录功能:

Python

# test_example_with_allure.py

import pytest
from playwright.sync_api import Page, expect

@pytest.fixture(scope="module")
def browser():
    from playwright.sync_api import sync_playwright
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        yield browser
        browser.close()

@pytest.fixture(scope="function")
def page(browser):
    context = browser.new_context()
    page = context.new_page()
    yield page
    page.close()

@pytest.mark.allure_feature("Web UI Testing")  # 定义测试的Feature
@pytest.mark.allure_story("Verify Example Domain")  # 定义测试的故事或场景
def test_example_with_allure(page: Page):
    with allure.step("Navigate to example.com"):
        page.goto("https://www.example.com")

    with allure.step("Check page title"):
        title = page.title()
        assert title == "Example Domain", f"Expected 'Example Domain', got '{title}'"

    with allure.step("Verify 'More information...' text is visible"):
        expect(page.get_by_text("More information...")).to_be_visible()

配置 Allure 报告生成

在运行测试后,你需要使用 Allure 命令行工具来收集测试结果(.json 文件)并生成报告。

  1. 收集测试结果:pytest 运行时会生成 Allure 的结果文件,你需要确保 pytest 配置正确。通常,使用 pytest-allure-adaptor 插件时,它会自动处理。

  2. 生成报告:使用 Allure 命令行工具生成 HTML 报告。首先,找到 pytest 生成的 .json 文件的目录(通常是 ./pytest_results 或类似的),然后执行以下命令:

Bash

allure generate ./pytest_results -o ./allure-report --clean

这会在当前目录下的 allure-report 文件夹中生成可浏览的测试报告。

查看报告

报告生成后,你可以在浏览器中打开 allure-report/index.html 来查看详细的测试报告,其中包含了测试步骤、失败详情、附图等丰富信息。

通过上述步骤,你就能结合 Playwright、pytest 和 Allure 构建出一个功能全面、报告精美的自动化测试框架。