# Web UI 自动化测试框架

基于 Python + Pytest + Playwright + Allure + DeepSeek 的 Web UI 自动化测试框架

## 框架特点

1. **Playwright** - 强大的浏览器自动化工具,支持多种浏览器
2. **Pytest** - 简洁易用的测试框架
3. **Allure** - 美观的测试报告生成工具
4. **Page Object Model** - 页面对象模型设计模式,提高代码可维护性
5. **DeepSeek AI** - 集成AI辅助测试,提高测试效率

## 环境准备

### 1. 安装依赖

```bash
# 创建虚拟环境(推荐)
python -m venv .venv
source .venv/bin/activate  # Linux/Mac
# .venv\Scripts\activate  # Windows

# 安装依赖
pip install -r requirements.txt

# 安装Playwright浏览器驱动
playwright install
```

### 2. 配置环境变量

```bash
# 复制示例配置文件
cp .env.example .env

# 编辑.env文件,填入实际配置
```

在.env文件中,您可以配置以下参数:
- `HEADLESS` - 控制浏览器是否以无头模式运行 (true/false)
- `BROWSER` - 指定使用的浏览器 (chromium/firefox/webkit)
- `BASE_URL` - 设置基础URL
- `DEEPSEEK_API_KEY` - DeepSeek API密钥

配置DeepSeek API密钥:
1. 访问[DeepSeek API官网](https://platform.deepseek.com/)注册账号
2. 在API管理页面创建API密钥
3. 将获取的API密钥填入.env文件中的DEEPSEEK_API_KEY字段

## 项目结构

```
SsmWebUITest/
├── config/                 # 配置文件目录
├── tests/                  # 测试用例目录
│   ├── pages/             # 页面对象模型
│   ├── test_cases/        # 测试用例
│   └── conftest.py        # pytest配置
├── utils/                  # 工具类目录
├── reports/                # 测试报告目录
├── screenshots/            # 截图目录
├── requirements.txt        # 依赖包列表
├── pytest.ini             # pytest配置文件
└── README.md              # 项目说明
```

## 运行测试

### 基本运行

```bash
# 运行所有测试
pytest

# 运行特定测试文件
pytest tests/test_cases/test_example.py

# 运行特定测试类或方法
pytest tests/test_cases/test_example.py::TestExample::test_google_search
```

### 使用标记运行

```bash
# 运行所有测试用例
python run.py

# 显示详细输出
python run.py --verbose

# 运行冒烟测试
python run.py --smoke

# 运行回归测试
python run.py --regression

# 以有头模式运行(显示浏览器界面)
python run.py --headed

# 运行特定测试文件
python run.py -t tests/test_cases/test_local.py

```

## 生成测试报告

### Allure报告

```bash
# 运行测试并生成Allure结果
pytest --alluredir=./reports/allure-results

# 生成并打开Allure报告
allure generate ./reports/allure-results -o ./reports/allure-report --clean
allure open ./reports/allure-report
```

### HTML报告

```bash
# 运行测试并生成HTML报告
pytest --html=./reports/report.html --self-contained-html
```

## 使用DeepSeek AI辅助

框架集成了DeepSeek AI,可以用于:
1. 自动生成测试用例建议
2. 分析测试结果
3. 提供测试优化建议
4. 智能测试数据分析

### 配置方法

要使用此功能,需要在`.env`文件中配置`DEEPSEEK_API_KEY`:

```env
DEEPSEEK_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

您还需要确保账户有足够的余额来使用API服务。

### 余额不足处理

框架已经实现了对余额不足情况的处理:
- 当账户余额不足时,相关测试会自动跳过而不是失败
- 系统会显示具体的错误信息

### 使用示例

框架中已包含使用AI的测试示例:

```python
# 在测试用例中使用AI辅助
    def test_deepseek_client(self, deepseek_client):
        """测试DeepSeek客户端连接"""
        if not deepseek_client:
            pytest.skip("未配置DeepSeek API密钥,跳过测试")
        
        # 发送一个简单的请求测试连接
        try:
            response = deepseek_client.chat.completions.create(
                model="deepseek-chat",
                messages=[
                    {
                        "role": "system",
                        "content": "你是一个专业的测试工程师。"
                    },
                    {
                        "role": "user",
                        "content": "请用一句话回答:Web UI自动化测试的目的是什么?"
                    }
                ],
                stream=False,
                max_tokens=100
            )
            
            # 验证响应
            assert response is not None
            assert response.choices is not None
            assert len(response.choices) > 0
            assert response.choices[0].message.content is not None
            
            print(f"AI回答: {response.choices[0].message.content}")
            
        except Exception as e:
            # 检查是否是余额不足错误
            error_message = str(e)
            if "Insufficient Balance" in error_message or "402" in error_message:
                pytest.skip(f"DeepSeek账户余额不足,跳过测试: {error_message}")
            else:
                pytest.fail(f"DeepSeek API调用失败: {str(e)}")
```

当正确配置API密钥且账户有足够余额后,相关测试将自动启用AI功能。

## 编写测试用例

### 页面对象模型

在`tests/pages/`目录下创建页面对象,继承`BasePage`类:

```python
from tests.pages.base_page import BasePage

class LoginPage(BasePage):
    def __init__(self, page):
        super().__init__(page)
        self.username_input = "#username"
        self.password_input = "#password"
        self.login_button = "#login-btn"
    
    def login(self, username, password):
        self.fill_input(self.username_input, username)
        self.fill_input(self.password_input, password)
        self.click_element(self.login_button)
```

### 测试用例编写

在`tests/test_cases/`目录下创建测试用例:

```python
import pytest
import allure
from tests.pages.login_page import LoginPage

@allure.feature("用户登录功能")
class TestLogin:
    
    @allure.story("正常登录")
    def test_valid_login(self, page):
        login_page = LoginPage(page)
        login_page.navigate_to("/login")
        login_page.login("user", "password")
        # 添加断言验证登录结果
```

## 配置说明

### pytest.ini

主要的pytest配置文件,包括:
- 测试发现规则
- Allure报告配置
- 自定义标记

### conftest.py

pytest的fixture配置文件,包括:
- 浏览器配置
- 页面对象初始化
- 失败截图
- DeepSeek客户端初始化

## 运行测试

### 基本运行

```bash
# 运行所有测试
pytest

# 运行特定测试文件
pytest tests/test_cases/test_local.py

# 运行特定测试类或方法
pytest tests/test_cases/test_local.py::TestLocal::test_local_page
```

### 控制浏览器显示

```bash
# 以有头模式运行测试(显示浏览器界面)
pytest --headed

# 使用特定浏览器运行
pytest --browser firefox

# 通过环境变量控制(需要在.env中设置HEADLESS=false)
cp .env.example .env
# 编辑.env文件,设置HEADLESS=false
pytest
```

### 网络相关问题

如果测试访问外部网站失败(如Google),可能是由于以下原因:
1. 网络连接问题
2. 防火墙限制
3. DNS解析问题

建议使用本地HTML文件进行测试,如`test_local.py`示例。

## 常见问题

1. **浏览器驱动问题**
   ```bash
   playwright install-deps
   playwright install
   ```

2. **Allure报告不显示**
   确保已安装Allure命令行工具:
   ```bash
   # macOS
   brew install allure
   
   # Windows
   scoop install allure
   ```

3. **DeepSeek API调用失败**
   检查`.env`文件中的API密钥配置是否正确。

4. **测试访问外部网站超时**
   尝试使用本地HTML文件进行测试,或者检查网络连接。

5. **playwright查找元素方式**
   playwright codegen url
   playwright codegen --browser firefox url  # 使用特定浏览器
6. 基本运行 
   python run.py
   生成并打开报告
   python run.py --generate-report --open-report
   显示详细输出
   python run.py --verbose
   有头模式运行(浏览器可见)
   python run.py --headed
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐