pytest+request 接口自动化测试

本文详细介绍了如何使用python3brew和pyenv管理Python环境,安装pytest及相关依赖包进行自动化测试。涵盖pytest框架的基本使用,包括setup和teardown方法,参数化测试,以及跳过和标记失败的测试用例。同时,还提供了生成测试报告的方法,包括使用allure和pytest-html插件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.安装python3
brew update
brew install pyenv
然后在 .bash_profile 文件中添加 eval “$(pyenv init -)”
pyenv install 3.5.3 -v
pyenv rehash 安装完成后,更新数据库
pyenv versions  查看目前系统已安装的 Python 版本
pyenv global 3.5.3  切换 Python 版本
python -V,查看 Python 版本
2.安装pytest及其他所需安装包:

pip install -U pytest
pip install -U requests
pip install -U pytest-pythonpath
pip install -U pytest-capturelog
pip install PyYAML
pip install configparser
pip install pyopenssl
二、pytest框架
setup_module(module):  #开始测试前执行一次,目前无实际使用
setup_function(function):  #每个测试用开始前执行一次,用于检查、准备测试环境
teardown_function(function):  #每个测试用例执行完执行一次,用于清除生成的测试数据
teardown_module(module):  #每次测试完成执行一次,用于还原测试环境
@pytest.mark.parametrize(‘mycase’, case.list,ids=case.name)  #装饰器,用来将list格式的测试用例分开执行

pytest.skip("skip testcase: (%s)" % mycase['Name']) #跳过测试用例
pytest.xfail("previous test failed (%s)" % mycase['Name']) #跳过会失败的测试用例
三、测试报告
python -m pytest -s -q  控制台输出每一步结果
1.allure

安装:

sudo pip install pytest-allure-adaptor
brew tap qatools/formulas
brew install allure-commandline

执行:

python -m pytest -s -q --alluredir ./report  #控制台也输出每一步结果
python -m pytest --alluredir ./report  #控制台只输出成功/失败和失败报的错误
allure generate report/ -o report/html  #生成报告,可直接打卡看
2.pytest-html

安装:

sudo pip install pytest-html

执行:

python -m pytest -s -q --html=./report.html  #控制台也输出每一步结果

python -m pytest --html=./report.html #控制台只输出成功/失败和失败报的错误
四、Demo

    # coding: utf-8
    import pytest
    import public
    import read_testcase
    import record
     
    #获取一个账号token,全局变量
    public.getalltoken()
    #测试用例实例化
    testcase=read_testcase.case()
     
    #所有测试用例开始前执行的文件,只执行一次
    def setup_module(module):#每次开始测试执行一次
        print ("setup_module")
    #所有测试用例结束后执行的文件,只执行一次
    def teardown_module(module):#每次测试完成执行一次
        print ("teardown_module")
    #每个测试用开始执行一次
    def setup_function(function):
        print ("setup_function")
    #每个测试用例执行完执行一次
    def teardown_function(function):
        print ("teardown_function")
    #装饰器 pytest 整合的测试用例生成多个结果
    @pytest.mark.parametrize('mycase', testcase.testcase_list,ids=testcase.testcasename)
    def test_all(mycase):
        testcase=mycase['Testcase_name']+str(mycase['Testcase_ID'])+'.'+str(mycase['ID'])+":"+mycase['Name']
        #print(mycase['Name'])
        #pytest.skip("skip testcase: (%s)" % mycase['Name'])
        #pytest.xfail("previous test skip (%s)" % mycase['Name'])
        mycase = public.get_Precondition(mycase)
     
        #执行接口的测试
        r=public.request_method(mycase)
        try:
            print(r.status_code)
            print(r.json())
        except Exception as e:
            print(r.content)
            print(e)
        #对返回数据进行断言
        public.assert_method(r, mycase)
        #记录测试用例名称存储log
        record.record_testcase_name(testcase)
        #记录测试时使用的数据
        record.record_testcase_msg(mycase)
---------------------

转载于:https://www.cnblogs.com/klb561/p/10273025.html

<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、付费专栏及课程。

余额充值