python自动化测试pom框架
时间: 2024-07-15 09:01:07 浏览: 180
Python中的POM(Page Object Model)框架是一种用于自动化Web应用程序测试的设计模式。它的主要目标是将页面元素和交互行为抽象为独立的对象,从而提高代码的可读性和维护性。在自动化测试中,POM通常按照三层结构组织:
1. **页面层**(Page Objects):这是最底层,定义了网站的各个页面或页面组件,如登录页面、商品详情页等。每个页面对象包含了页面上所有相关的HTML元素(如按钮、文本框等),以及与这些元素的交互方法。
2. **模块层**(Module):处理业务逻辑和数据操作的部分,不直接依赖于具体的页面布局。例如,可能有一个搜索模块负责执行搜索请求,并处理返回的结果。
3. **测试套件层**(Test Suite):这一层编写测试用例,调用页面对象的方法进行交互并验证结果。这样,测试代码只关注核心功能的测试,而与页面的具体实现解耦。
POM框架常见的Python库包括Selenium WebDriver + PageObject、pytest-bdd等。使用POM框架的好处包括:
- **复用性强**:可以重用页面对象,减少测试代码的冗余。
- **易于理解和维护**:各部分职责明确,便于团队协作。
- **灵活性高**:当页面结构发生变化时,只需修改相应的页面对象,不会影响到测试代码。
相关问题
给我一个python+pytest 打造接口自动化pom框架
好的,以下是一个基于Python + pytest 打造接口自动化POM框架的示例代码:
1. 安装pytest库
```bash
pip install pytest
```
2. 创建项目目录结构
```
+-- config/
| +-- __init__.py
| +-- config.py
+-- pages/
| +-- __init__.py
| +-- base_page.py
| +-- login_page.py
+-- tests/
| +-- __init__.py
| +-- test_login.py
+-- utils/
| +-- __init__.py
| +-- api.py
| +-- logger.py
| +-- parse_yaml.py
| +-- report.py
| +-- send_email.py
+-- pytest.ini
+-- requirements.txt
```
3. 编写配置文件
config/config.py
```python
import os
# 项目根目录路径
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
# 接口基础 URL
BASE_URL = "http://api.example.com"
# 测试报告目录路径
REPORT_DIR = os.path.join(ROOT_DIR, "reports")
# 日志文件目录路径
LOG_DIR = os.path.join(ROOT_DIR, "logs")
# 邮件相关配置
MAIL_HOST = "smtp.163.com"
MAIL_PORT = 465
MAIL_USER = "example@163.com"
MAIL_PASSWORD = "password"
MAIL_RECEIVER = ["example@qq.com"]
```
4. 编写基础页面类
pages/base_page.py
```python
from utils.api import send_request
class BasePage(object):
def __init__(self):
self.base_url = "http://api.example.com"
self.session = requests.session()
self.headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
"Content-Type": "application/json",
}
def send_request(self, method, url, params=None, data=None, json=None, **kwargs):
url = self.base_url + url
res = send_request(self.session, method, url, params=params, data=data, json=json, headers=self.headers, **kwargs)
return res
```
5. 编写登录页面类
pages/login_page.py
```python
from pages.base_page import BasePage
class LoginPage(BasePage):
def __init__(self):
super(LoginPage, self).__init__()
self.url = "/login"
def login(self, username, password):
data = {"username": username, "password": password}
res = self.send_request("post", self.url, json=data)
return res
```
6. 编写测试用例
tests/test_login.py
```python
import pytest
from pages.login_page import LoginPage
from utils.parse_yaml import parse_yaml
data = parse_yaml("data/login_data.yaml")
class TestLogin(object):
@pytest.fixture(scope="class", autouse=True)
def setup_class(self):
self.login_page = LoginPage()
@pytest.mark.parametrize("test_data", data)
def test_login(self, test_data):
res = self.login_page.login(test_data["username"], test_data["password"])
assert res["status"] == test_data["expected"]
```
7. 编写pytest配置文件
pytest.ini
```ini
[pytest]
log_cli = true
log_cli_level = INFO
log_cli_format = %(asctime)s - %(levelname)s - %(message)s
log_cli_date_format = %Y-%m-%d %H:%M:%S
log_file = logs/pytest.log
log_file_level = INFO
log_file_format = %(asctime)s - %(levelname)s - %(message)s
log_file_date_format = %Y-%m-%d %H:%M:%S
addopts = -s -v --html=reports/pytest_report.html --self-contained-html
```
8. 编写运行脚本
run.py
```python
import os
import pytest
from config.config import REPORT_DIR, LOG_DIR, MAIL_HOST, MAIL_PORT, MAIL_USER, MAIL_PASSWORD, MAIL_RECEIVER
from utils.logger import Logger
from utils.report import generate_report
from utils.send_email import send_mail
if __name__ == "__main__":
# 创建日志文件夹
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
# 创建测试报告文件夹
if not os.path.exists(REPORT_DIR):
os.makedirs(REPORT_DIR)
# 设置日志器
logger = Logger().get_logger()
# 运行pytest测试用例
pytest.main(["-s", "-v", "--alluredir", "allure_report"])
# 生成测试报告
generate_report(REPORT_DIR)
# 发送邮件
send_mail(MAIL_HOST, MAIL_PORT, MAIL_USER, MAIL_PASSWORD, MAIL_RECEIVER, REPORT_DIR)
```
9. 编写运行脚本所需的依赖
requirements.txt
```
pytest
allure-pytest
pytest-html
pytest-rerunfailures
pytest-xdist
requests
PyYAML
allure-python-commons
```
10. 运行测试用例
在命令行中进入项目根目录,执行以下命令:
```bash
python run.py
```
以上是一个基于Python + pytest 打造接口自动化POM框架的示例代码,供你参考。
给我一个python+pytest+allure 打造接口自动化pom框架
好的,下面是一个简单的 Python + Pytest + Allure 实现接口自动化 POM 框架的示例:
1. 安装依赖库
```
pip install requests
pip install pytest
pip install allure-pytest
```
2. 创建项目目录结构:
```
├── api
│ ├── __init__.py
│ ├── base_api.py
│ └── user_api.py
├── common
│ ├── __init__.py
│ ├── constants.py
│ ├── logger.py
│ └── utils.py
├── config
│ ├── __init__.py
│ └── config.py
├── data
│ ├── __init__.py
│ └── users.json
├── pytest.ini
├── README.md
├── requirements.txt
├── testcases
│ ├── __init__.py
│ ├── conftest.py
│ ├── test_login.py
│ └── test_user.py
└── pytest.ini
```
3. 编写配置文件 `config.py`、常量文件 `constants.py` 等。
`config.py`:
```python
class Config:
API_BASE_URL = 'https://xxx.com/api'
USERNAME = 'testuser'
PASSWORD = 'testpass'
```
`constants.py`:
```python
class StatusCode:
SUCCESS = 200
CLIENT_ERROR = 400
SERVER_ERROR = 500
```
4. 创建 HTTP 请求封装类 `base_api.py` 和业务接口类 `user_api.py`
`base_api.py`:
```python
import requests
from common.logger import logger
from common.constants import StatusCode
from config.config import Config
class BaseApi:
def __init__(self):
self.session = requests.session()
self.base_url = Config.API_BASE_URL
def request(self, method, url, **kwargs):
url = self.base_url + url
response = self.session.request(method, url, **kwargs)
logger.info(f'{method} {url} {kwargs} response: {response.json()}')
return response
def get(self, url, params=None, **kwargs):
return self.request('get', url, params=params, **kwargs)
def post(self, url, data=None, json=None, **kwargs):
return self.request('post', url, data=data, json=json, **kwargs)
def put(self, url, data=None, **kwargs):
return self.request('put', url, data=data, **kwargs)
def delete(self, url, **kwargs):
return self.request('delete', url, **kwargs)
def assert_status_code(self, response, expected_status_code):
assert response.status_code == expected_status_code, \
f'Expected status code is {expected_status_code}, but actual is {response.status_code}'
response_json = response.json()
assert response_json['code'] == StatusCode.SUCCESS, \
f'Response code is {response_json["code"]}, message is {response_json["message"]}'
```
`user_api.py`:
```python
from api.base_api import BaseApi
from common.constants import StatusCode
from config.config import Config
from common.utils import json_load
class UserApi(BaseApi):
def __init__(self):
super().__init__()
def login(self):
url = '/login'
data = {
'username': Config.USERNAME,
'password': Config.PASSWORD
}
response = self.post(url, json=data)
self.assert_status_code(response, StatusCode.SUCCESS)
return response.json()['data']['access_token']
def get_user_info(self, user_id):
url = f'/users/{user_id}'
headers = {
'Authorization': f'Bearer {self.login()}'
}
response = self.get(url, headers=headers)
self.assert_status_code(response, StatusCode.SUCCESS)
return response.json()['data']
def create_user(self, data):
url = '/users'
headers = {
'Authorization': f'Bearer {self.login()}'
}
response = self.post(url, json=data, headers=headers)
self.assert_status_code(response, StatusCode.SUCCESS)
return response.json()['data']
def delete_user(self, user_id):
url = f'/users/{user_id}'
headers = {
'Authorization': f'Bearer {self.login()}'
}
response = self.delete(url, headers=headers)
self.assert_status_code(response, StatusCode.SUCCESS)
return response.json()['data']
def get_random_user(self):
users = json_load('data/users.json')
return users[0]
```
5. 编写测试用例 `test_user.py` 和 `test_login.py`
`test_user.py`:
```python
import pytest
from api.user_api import UserApi
class TestUser:
@pytest.fixture(scope='class')
def user(self):
return UserApi().get_random_user()
def test_create_and_delete_user(self, user):
user_api = UserApi()
new_user = user_api.create_user(user)
assert new_user['username'] == user['username']
user_api.delete_user(new_user['id'])
def test_get_user_info(self):
user_api = UserApi()
user_info = user_api.get_user_info(1)
assert user_info['username'] == 'admin'
```
`test_login.py`:
```python
import pytest
from api.user_api import UserApi
class TestLogin:
def test_login(self):
user_api = UserApi()
access_token = user_api.login()
assert access_token is not None
```
6. 运行测试用例
在项目根目录下执行以下命令:
```
pytest --alluredir=./allure-results testcases/
```
7. 生成报告
在项目根目录下执行以下命令:
```
allure serve ./allure-results
```
此时会启动一个本地服务,打开浏览器输入 `http://localhost:port` 即可查看测试报告。
以上就是一个简单的 Python + Pytest + Allure 实现接口自动化 POM 框架的示例,希望对你有帮助。
阅读全文