接口自动化框架详解(Pytest+request+Allure)

🍅 点击文末小卡片,免费获取软件测试全套资料,资料在手,涨薪更快

接口自动化是指模拟程序接口层面的自动化,由于接口不易变更,维护成本更小,所以深受各大公司的喜爱。

接口自动化包含2个部分,功能性的接口自动化测试和并发接口自动化测试。

本次文章着重介绍第一种,功能性的接口自动化框架。

一、简单介绍

环境:Mac、Python 3,Pytest,Allure,Request
流程:读取Yaml测试数据-生成测试用例-执行测试用例-生成Allure报告
模块类的设计说明:

Request.py 封装request方法,可以支持多协议扩展(get\post\put)
Config.py 读取配置文件,包括:不同环境的配置,email相关配置
Log.py 封装记录log方法,分为:debug、info、warning、error、critical
Email.py 封装smtplib方法,运行结果发送邮件通知
Assert.py 封装assert方法
run.py 核心代码。定义并执行用例集,生成报告

Yaml测试数据格式如下:

---

Basic:

dec: "基础设置"

parameters:

-

url: /settings/basic.json

data: slug=da1677475c27

header: {

"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko)\

Chrome/67.0.3396.99 Safari/537.36",

"Content-Type": "keep-alive"

}

二、代码结构与框架流程

1、代码结构见下图:

2、框架流程见下图:

三、详细功能和使用说明

1、定义配置文件config.ini

该文件中区分测试环境[private_debug]和正式环境[online_release]分别定义相关配置项,[mail]部分为邮件相关配置项

# http接口测试框架配置信息


[private_debug]

# debug测试服务

tester = your name

environment = debug

versionCode = your version

host = www.jianshu.com

loginHost = /Login

loginInfo = email=wang@user.com&password=123456


[online_release]

# release正式服务

tester = your name

environment = release

versionCode = v1.0

host = www.jianshu.com

loginHost = /Login

loginInfo = email=wang@user.com&password=123456


[mail]

#发送邮件信息

smtpserver = smtp.163.com

sender = test1@163.com

receiver = wang@user.com

username = wang@user.com

password = 123456

2、读取yaml测试数据后封装

yaml测试数据例子见第一节,一条接口可定义多条case数据,get_parameter为已封装好的读取yaml数据方法,循环读取后将多条case数据存在list中。

class Basic:

params = get_parameter('Basic')

url = []

data = []

header = []

for i in range(0, len(params)):

url.append(params[i]['url'])

data.append(params[i]['data'])

header.append(params[i]['header'])

3、编写用例

class TestBasic:

@pytest.allure.feature('Home')

@allure.severity('blocker')

@allure.story('Basic')

def test_basic_01(self, action):

"""

用例描述:未登陆状态下查看基础设置

"""

conf = Config()

data = Basic()

test = Assert.Assertions()

request = Request.Request(action)


host = conf.host_debug

req_url = 'http://' + host

urls = data.url

params = data.data

headers = data.header


api_url = req_url + urls[0]

response = request.get_request(api_url, params[0], headers[0])


assert test.assert_code(response['code'], 401)

assert test.assert_body(response['body'], 'error', u'继续操作前请注册或者登录.')

assert test.assert_time(response['time_consuming'], 400)

Consts.RESULT_LIST.append('True')

4、运行整个框架run.py

if __name__ == '__main__':

# 定义测试集

allure_list = '--allure_features=Home,Personal'

args = ['-s', '-q', '--alluredir', xml_report_path, allure_list]

log.info('执行用例集为:%s' % allure_list)

self_args = sys.argv[1:]

pytest.main(args)

cmd = 'allure generate %s -o %s' % (xml_report_path, html_report_path)


try:

shell.invoke(cmd)

except:

log.error('执行用例失败,请检查环境配置')

raise


try:

mail = Email.SendMail()

mail.sendMail()

except:

log.error('发送邮件失败,请检查邮件配置')

raise

5、err.log实例

[ERROR 2018-08-24 09:55:37]Response body != expected_msg, expected_msg is {"error":"继续操作前请注册或者登录9."}, body is {"error":"继续操作前请注册或者登录."}

[ERROR 2018-08-24 10:00:11]Response time > expected_time, expected_time is 400, time is 482.745

[ERROR 2018-08-25 21:49:41]statusCode error, expected_code is 208, statusCode is 200

6、Assert部分代码

def assert_body(self, body, body_msg, expected_msg):

"""

验证response body中任意属性的值

:param body:

:param body_msg:

:param expected_msg:

:return:

"""

try:

msg = body[body_msg]

assert msg == expected_msg

return True


except:

self.log.error("Response body msg != expected_msg, expected_msg is %s, body_msg is %s" % (expected_msg, body_msg))

Consts.RESULT_LIST.append('fail')


raise


def assert_in_text(self, body, expected_msg):

"""

验证response body中是否包含预期字符串

:param body:

:param expected_msg:

:return:

"""

try:

text = json.dumps(body, ensure_ascii=False)

# print(text)

assert expected_msg in text

return True


except:

self.log.error("Response body Does not contain expected_msg, expected_msg is %s" % expected_msg)

Consts.RESULT_LIST.append('fail')


raise

7、Request部分代码

def post_request(self, url, data, header):

"""

Post请求

:param url:

:param data:

:param header:

:return:


"""

if not url.startswith('http://'):

url = '%s%s' % ('http://', url)

print(url)

try:

if data is None:

response = self.get_session.post(url=url, headers=header)

else:

response = self.get_session.post(url=url, params=data, headers=header)


except requests.RequestException as e:

print('%s%s' % ('RequestException url: ', url))

print(e)

return ()


except Exception as e:

print('%s%s' % ('Exception url: ', url))

print(e)

return ()


# time_consuming为响应时间,单位为毫秒

time_consuming = response.elapsed.microseconds/1000

# time_total为响应时间,单位为秒

time_total = response.elapsed.total_seconds()


Common.Consts.STRESS_LIST.append(time_consuming)


response_dicts = dict()

response_dicts['code'] = response.status_code

try:

response_dicts['body'] = response.json()

except Exception as e:

print(e)

response_dicts['body'] = ''


response_dicts['text'] = response.text

response_dicts['time_consuming'] = time_consuming

response_dicts['time_total'] = time_total


return response_dicts

四、Allure报告及Email

1、Allure报告总览,见下图:

2、Email见下图:

五、后续优化

1、集成Jenkins,使用Jenkins插件生成Allure报告
2、多线程并发接口自动化测试
3、接口加密,参数加密

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于做【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴我走过了最艰难的路程,希望也能帮助到你!凡事要趁早,特别是技术行业,一定要提升技术功底。

<think>我们正在构建一个使用pytestrequests的接口自动化测试项目。根据用户的问题,我们需要详细解释如何实现这样的项目。参考引用内容,我们可以总结出以下几个关键点:1.使用requests库发送HTTP请求。2.使用pytest作为测试框架来管理测试用例。3.可能使用YAML文件进行数据驱动(引用[3])。4.使用Allure生成测试报告(引用[2],[3])。5.测试用例的组织和标记(引用[1])。因此,我们将按照以下结构进行详解:一、项目结构二、环境准备三、请求的封装四、测试用例编写(使用pytest)五、数据驱动(结合YAML)六、测试报告(Allure)七、运行测试注意:引用内容中有些代码片段,我们可以参考并适当调整。开始详细说明:</think>### 使用 Pytest + Requests 构建接口自动化测试项目详解 #### 一、项目结构设计 ```bash project/ ├── conftest.py # pytest全局配置 ├── requirements.txt # 依赖库 ├── testcases/ # 测试用例目录 │ ├── __init__.py │ ├── test_login.py # 示例测试模块 │ └── test_user.py ├── utils/ # 工具类 │ ├── __init__.py │ ├── request_util.py # 请求封装 │ └── assert_util.py # 断言封装 └── data/ # 测试数据 ├── login_data.yaml └── user_data.yaml ``` #### 二、核心组件实现 1. **请求封装 (`utils/request_util.py`)** ```python import requests class RequestUtil: def __init__(self): self.session = requests.Session() def send_request(self, method, url, **kwargs): method = method.upper() try: response = self.session.request(method, url, **kwargs) response.raise_for_status() # 自动抛出HTTP错误 return response except requests.exceptions.RequestException as e: raise AssertionError(f"请求失败: {str(e)}") ``` 2. **断言工具 (`utils/assert_util.py`)** ```python def assert_response(response, expected_status=200, expected_data=None): # 状态码断言 assert response.status_code == expected_status, \ f"状态码错误: 期望{expected_status}, 实际{response.status_code}" # 响应体断言 if expected_data: actual_data = response.json() for key, value in expected_data.items(): assert key in actual_data, f"缺失字段: {key}" assert actual_data[key] == value, \ f"字段值不匹配: {key} 期望={value}, 实际={actual_data[key]}" ``` #### 三、测试用例编写 (`testcases/test_login.py`) ```python import pytest from utils.request_util import RequestUtil from utils.assert_util import assert_response @pytest.mark.login class TestLogin: @pytest.fixture(scope="class") def req(self): return RequestUtil() @pytest.mark.parametrize("case", [ {"username": "admin", "password": "123456", "expected": 200}, {"username": "invalid", "password": "xxx", "expected": 401} ]) def test_login(self, req, case): """登录接口测试""" url = "https://api.example.com/login" payload = { "username": case["username"], "password": case["password"] } response = req.send_request("POST", url, json=payload) assert_response(response, expected_status=case["expected"]) ``` #### 四、Pytest 配置 (`conftest.py`) ```python import pytest # 全局前置处理 @pytest.fixture(scope="session", autouse=True) def setup_session(): print("\n=== 测试开始 ===") yield print("\n=== 测试结束 ===") # 失败重试机制 def pytest_addoption(parser): parser.addoption("--reruns", action="store", default=1, help="失败重试次数") @pytest.hookimpl(tryfirst=True) def pytest_configure(config): config.addinivalue_line("markers", "login: 登录模块测试") ``` #### 五、运行与报告生成 1. **安装依赖 (`requirements.txt`)** ``` pytest==7.4.0 requests==2.31.0 pytest-rerunfailures==12.0 allure-pytest==2.13.2 ``` 2. **执行测试** ```bash # 运行全部测试 pytest -v # 运行标记为login的测试 pytest -m login # 失败重试3次 pytest --reruns 3 -v ``` 3. **生成Allure报告** ```bash pytest --alluredir=./report/allure_results allure serve ./report/allure_results # 本地查看报告 ``` #### 六、最佳实践 1. **数据驱动** ```python # 从YAML加载测试数据 import yaml @pytest.mark.parametrize("case", yaml.safe_load(open("data/login_data.yaml"))) def test_login_data_driven(req, case): ... ``` 2. **关联参数处理** ```python # 在conftest.py中存储全局token @pytest.fixture def auth_token(req): response = req.send_request("POST", login_url, json=credentials) return response.json()["token"] # 测试用例使用token def test_user_info(req, auth_token): headers = {"Authorization": f"Bearer {auth_token}"} ... ``` 3. **异步请求支持** ```python # 在request_util.py中添加 import aiohttp async def async_request(self, method, url, **kwargs): async with aiohttp.ClientSession() as session: async with session.request(method, url, **kwargs) as response: ... ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值