Skip to content

接口自动化测试代码

接口自动化测试用例

测试用例编写

使用 pytest 测试类组织测试用例。在测试类中编写具体的测试方法,每一个测试方法是一个测试用例。

在每一条测试用例中,使用 requests 发起请求。接受接口响应内容,然后进行断言,判断用例是否通过。

class TestOwnerSearch:
    OWNER_URL = "https://spring-petclinic-angular.poc.ceshiren.com/petclinic/api/owners"

    def test_search_more_exists(self):
        """
        测试步骤:
        1. 设定lastName的值为【searchkey】
        2. 使用设定的参数发起requests请求
        3. 取出requests请求的结果
        预期结果:结果数量大于=2 不止一个
        :return:
        """
        searchkey = "Davis"
        param = {"lastName": searchkey}
        ownerlist = requests.request("GET", url=self.OWNER_URL, params=param).json()
        assert len(ownerlist) >= 2

添加日志

编写日志工具类

import logging
import os

from logging.handlers import RotatingFileHandler

# 绑定绑定句柄到logger对象
logger = logging.getLogger(__name__)
# 获取当前工具文件所在的路径
root_path = os.path.dirname(os.path.abspath(__file__))
# 拼接当前要输出日志的路径
log_dir_path = os.sep.join([root_path, f'/logs'])
if not os.path.isdir(log_dir_path):
    os.mkdir(log_dir_path)
# 创建日志记录器,指明日志保存路径,每个日志的大小,保存日志的上限
file_log_handler = RotatingFileHandler(os.sep.join([log_dir_path, 'log.log']), maxBytes=1024 * 1024, backupCount=10)
# 设置日志的格式
date_string = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(
    '[%(asctime)s] [%(levelname)s] [%(filename)s]/[line: %(lineno)d]/[%(funcName)s] %(message)s ', date_string)
# 日志输出到控制台的句柄
stream_handler = logging.StreamHandler()
# 将日志记录器指定日志的格式
file_log_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)
# 为全局的日志工具对象添加日志记录器
# 绑定绑定句柄到logger对象
logger.addHandler(stream_handler)
logger.addHandler(file_log_handler)
# 设置日志输出级别
logger.setLevel(level=logging.INFO)

在测试用例中添加日志

logger.info(f"给接口设定输入内容:{searchkey}")

参数化

如果多个测试用例,测试步骤完全相同,只有测试数据不同,可以使用参数化的方式,在一个测试方法中完成多个测试用例的执行。

@pytest.mark.parametrize("searchkey", ["a", "b", "A"])
def test_search_only_exists(self, searchkey):
    ...

设置测试用例优先级

使用 pytest 添加标签的特性,为测试用例设置优先级。这样可以方便单独执行其中一种优先级的测试用例。

在 pytest.ini 文件中声明用例优先级

[pytest]
markers = P0
        P1
        P2

在测试用例中添加优先级

@pytest.mark.P0
def test_search_more_exists(self):
    ...

添加测试报告

使用 allure,在测试用例的不同位置添加测试报告信息。

@allure.epic("宠物医院")
@allure.feature("搜索功能")
class TestOwnerSearch:
    OWNER_URL = "http://spring-petclinic-angular.poc.ceshiren.com/owners"

    @pytest.mark.P0
    @allure.story("Owners搜索")
    @allure.title("搜索-结果不止一个")
    def test_search_more_exists(self):
        ...

测试代码

部分用例代码如下:

@allure.epic("宠物医院")
@allure.feature("搜索功能")
class TestOwnerSearch:
    OWNER_URL = "https://spring-petclinic-angular.poc.ceshiren.com/petclinic/api/owners"

    @pytest.mark.P0
    @allure.story("Owners搜索")
    @allure.title("搜索-结果不止一个")
    def test_search_more_exists(self):
        """
        测试步骤:
        1. 设定lastName的值为【searchkey】
        2. 使用设定的参数发起requests请求
        3. 取出requests请求的结果
        预期结果:结果数量大于=2 不止一个
        :return:
        """
        searchkey = "Davis"
        logger.info(f"给接口设定输入内容:{searchkey}")
        param = {"lastName": searchkey}
        ownerlist = requests.request("GET", url=self.OWNER_URL, params=param).json()
        logger.info("断言比较结果列表的长度大于2 len(ownerlist) >= 2")
        assert len(ownerlist) >= 2

完整的自动化测试用例代码请查看源码:接口自动化测试代码