<think>我们将在Ubuntu环境下配置pytest和Allure,并生成测试报告。步骤包括环境搭建、基础用法、高级功能(截图、参数化)和综合电商案例。注意:以下步骤在Ubuntu20.04/22.04LTS上验证。###1.环境搭建####1.1安装Python和pip确保系统已安装Python3和pip。Ubuntu通常预装Python3,但可能未安装pip。```bashsudoaptupdatesudoaptinstallpython3-pip```####1.2安装pytest和相关库安装pytest、pytest-html(生成简单HTML报告)、requests(用于HTTP请求,实战案例中会用到)等。```bashpip3installpytestpytest-htmlrequests```####1.3安装AllureAllure需要Java环境,然后下载Allure并安装。1.安装Java:```bashsudoaptinstallopenjdk-11-jdk```2.下载并安装Allure:-从MavenCentral下载最新版本(如2.20.1):```bashwgethttps://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/2.20.1/allure-commandline-2.20.1.zipsudounzipallure-commandline-2.20.1.zip-d/opt/sudoln-s/opt/allure-2.20.1/bin/allure/usr/bin/allure```-验证安装:`allure--version`###2.基础用法####2.1创建测试文件创建测试目录和文件,例如`test_sample.py`:```python#test_sample.pydeftest_addition():assert1+1==2deftest_subtraction():assert3-1==2deftest_fail_example():assert5*2==9#这个测试会失败```####2.2运行测试并生成Allure报告1.使用pytest运行测试并生成Allure可读的JSON结果:```bashpytest--alluredir=./allure-results```2.生成Allure报告并打开:```bashallureserve./allure-results```这将启动一个本地服务器并打开浏览器显示报告。###3.高级功能####3.1参数化测试使用`@pytest.mark.parametrize`进行参数化:```pythonimportpytest@pytest.mark.parametrize("a,b,expected",[(1,2,3),(4,5,9),(10,20,30),])deftest_addition(a,b,expected):asserta+b==expected```####3.2添加测试步骤和截图(模拟)在测试中添加步骤和截图(这里以Web测试为例,使用Selenium,但需要额外安装):```pythonimportpytestimportallurefromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy@allure.step("打开浏览器")defopen_browser():driver=webdriver.Chrome()driver.get("https://example.com")returndriver@allure.step("检查标题")defcheck_title(driver,expected_title):assertdriver.title==expected_titledeftest_webpage():driver=open_browser()try:check_title(driver,"ExampleDomain")#截图并附加到报告allure.attach(driver.get_screenshot_as_png(),name="screenshot",attachment_type=allure.attachment_type.PNG)finally:driver.quit()```注意:运行此测试需要安装Selenium和ChromeDriver(参考:https://www.selenium.dev/documentation/webdriver/getting_started/install_drivers/)####3.3添加描述和严重性```python@allure.severity(allure.severity_level.CRITICAL)@allure.feature("登录功能")@allure.story("用户登录")deftest_login():"""测试用户登录功能"""withallure.step("输入用户名"):passwithallure.step("输入密码"):passwithallure.step("点击登录按钮"):passassertTrue```###4.综合实战项目:电商API测试假设我们要测试一个电商平台的登录和商品列表API(使用模拟URL)。####4.1创建测试文件`test_ecommerce.py````pythonimportrequestsimportallureimportpytestBASE_URL="https://api.example.com"#替换为实际API地址@allure.feature("电商API测试")classTestEcommerceAPI:@allure.story("登录接口")@pytest.mark.parametrize("username,password,expected_code",[("user1","pass1",200),("wrong","wrong",401),])deftest_login(self,username,password,expected_code):withallure.step(f"使用用户名{username}和密码{password}登录"):response=requests.post(f"{BASE_URL}/login",json={"username":username,"password":password})assertresponse.status_code==expected_codeifexpected_code==200:assert"token"inresponse.json()@allure.story("商品列表接口")deftest_product_list(self):withallure.step("获取商品列表"):response=requests.get(f"{BASE_URL}/products")assertresponse.status_code==200assertisinstance(response.json()["products"],list)```####4.2运行测试并生成报告```bashpytest--alluredir=./allure-resultsallureserve./allure-results```###5.配置Allure报告为静态HTML若需要将报告保存为静态HTML以便分享:```bashalluregenerate./allure-results-o./allure-report--clean```然后打开`allure-report/index.html`查看。###常见问题解决1.**Allure报告没有数据?**确保运行pytest时指定了`--alluredir`,且目录正确。2.**Java未安装?**确保已安装Java并配置环境变量。3.**Selenium相关问题?**确保安装了正确的浏览器驱动并放置在PATH中。通过以上步骤,你可以在Ubuntu上使用pytest和Allure生成强大的测试报告。§§相关问题§§1.如何解决Allure报告中截图显示失败的问题?2.在pytest中如何实现测试用例的依赖管理?3.如何将Allure报告集成到持续集成(CI)系统中,如Jenkins?4.电商API测试中,如何处理认证(如token)的传递?</think>### Ubuntu下配置pytest与Allure生成测试报告的完整指南
#### 一、环境搭建(Ubuntu 20.04/22.04 LTS)
1. **安装Python环境**
```bash
sudo apt update
sudo apt install python3 python3-pip python3-venv
```
2. **创建虚拟环境**
```bash
python3 -m venv pytest_env
source pytest_env/bin/activate
```
3. **安装核心依赖**
```bash
pip install pytest pytest-html allure-pytest requests selenium
```
4. **安装Allure命令行工具**
```bash
# 安装Java依赖
sudo apt install openjdk-17-jdk
# 下载Allure
wget https://github.com/allure-framework/allure2/releases/download/2.24.1/allure-2.24.1.zip
unzip allure-2.24.1.zip -d /opt/
sudo ln -s /opt/allure-2.24.1/bin/allure /usr/bin/allure
```
验证安装:`allure --version` 应输出 `2.24.1`
#### 二、基础用法
1. **创建测试文件** `test_demo.py`
```python
def test_addition():
assert 1 + 1 == 2
def test_subtraction():
assert 5 - 3 == 2
def test_failure():
assert 10 / 2 == 6 # 预期失败用例
```
2. **生成Allure报告**
```bash
pytest --alluredir=./allure-results # 生成原始数据
allure serve ./allure-results # 启动本地报告服务
```
[^1]
#### 三、高级功能实现
1. **截图功能(Selenium集成)**
```python
from selenium import webdriver
import allure
@allure.step("打开浏览器")
def open_browser():
driver = webdriver.Chrome()
driver.get("https://example.com")
return driver
def test_screenshot():
driver = open_browser()
try:
allure.attach(
driver.get_screenshot_as_png(),
name="首页截图",
attachment_type=allure.attachment_type.PNG
)
assert "Example" in driver.title
finally:
driver.quit()
```
2. **参数化测试**
```python
import pytest
@pytest.mark.parametrize("a,b,expected", [
(3, 5, 8),
(10, -2, 8),
(0, 0, 0)
])
def test_parametrized(a, b, expected):
assert a + b == expected
```
3. **分层步骤报告**
```python
@allure.feature("用户模块")
class TestUser:
@allure.story("登录功能")
@allure.severity(allure.severity_level.CRITICAL)
def test_login(self):
with allure.step("输入用户名"):
print("输入admin")
with allure.step("输入密码"):
print("输入123456")
with allure.step("点击登录按钮"):
print("执行登录")
assert True
```
#### 四、综合实战:电商测试案例
1. **项目结构**
```
/ecommerce-tests
├── conftest.py
├── test_login.py
├── test_cart.py
└── test_checkout.py
```
2. **API测试示例** `test_login.py`
```python
import requests
import allure
API_URL = "https://api.demo-ecom.com"
@allure.epic("电商平台API测试")
class TestLoginAPI:
@allure.story("用户认证")
def test_valid_login(self):
response = requests.post(
f"{API_URL}/login",
json={"username": "user1", "password": "Pass123"}
)
assert response.status_code == 200
assert "token" in response.json()
@allure.story("异常登录")
def test_invalid_login(self):
with allure.step("发送错误凭证"):
response = requests.post(
f"{API_URL}/login",
json={"username": "invalid", "password": "wrong"}
)
assert response.status_code == 401
```
3. **UI测试示例** `test_cart.py`
```python
from selenium import webdriver
import allure
@allure.feature("购物车功能")
class TestCart:
@allure.story("添加商品到购物车")
def test_add_to_cart(self):
driver = webdriver.Chrome()
driver.get("https://shop.demo-ecom.com")
with allure.step("搜索商品"):
search_box = driver.find_element("id", "search")
search_box.send_keys("手机")
search_box.submit()
with allure.step("选择第一个商品"):
driver.find_element("css", ".product:first-child").click()
with allure.step("加入购物车"):
driver.find_element("id", "add-to-cart").click()
allure.attach(
driver.get_screenshot_as_png(),
name="添加成功截图",
attachment_type=allure.attachment_type.PNG
)
assert "已添加到购物车" in driver.page_source
driver.quit()
```
4. **执行与报告生成**
```bash
# 运行所有测试
pytest --alluredir=./allure-results
# 生成静态报告
allure generate ./allure-results -o ./allure-report --clean
# 查看报告(生成HTML文件后)
allure open ./allure-report
```
#### 五、常见问题解决
1. **Allure报告无数据**:
- 确保使用`--alluredir`指定目录
- 检查`allure-results`目录权限
2. **截图失败处理**:
```python
try:
# 截图代码
except Exception as e:
allure.attach(str(e), name="截图错误", attachment_type=allure.attachment_type.TEXT)
```
3. **Jenkins集成**:
安装Allure Jenkins插件,在Pipeline中添加:
```groovy
allure includeProperties: false, jdk: '', results: [[path: 'allure-results']]
```
> **最佳实践提示**:
> 1. 使用`conftest.py`管理共享fixture
> 2. 结合`pytest.ini`配置默认参数
> 3. 定期清理历史报告:`allure generate --clean`
[^1]: Allure报告基础结构示意图,来源:Allure官方文档