接口自动化——har 生成用例

一、目标

掌握 Har 转换成脚本的能力。

二、应用场景

通过 Har 格式的接口数据,转换为接口自动化测试脚本:
提升脚本的编写效率
降低脚本的出BUG的几率

三、Har 简介

Har格式是指HTTP归档格式(HTTP Archive Format)。
用于记录HTTP会话信息的文件格式。
多个浏览器都可以生成 Har 格式的数据。

四、实现思路

在这里插入图片描述

五、模板技术

Mustache是一种轻量级的模板语言。
需要定义模板,然后可以将数据填充到设定好的位置。
官网地址:https://mustache.github.io/

模版
Hello {{name}}!
填充name的位置
Hello KOBE!

六、模版技术-环境安装(Python)

环境安装

pip install chevron

七、har 生成用例实现思路

读取Har数据。
提前准备测试用例模版。
将读取的Har数据写入到模板中。

代码实现如下

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/5/10 11:15
# @Author  : 杜兰特
# @File    : generate_case.py
import json
import chevron

class GenerateCase:
    def load_har(self,har_file):
        """
        从har格式的文件中提取想要的数据信息
        :return:
        """
        with open(har_file) as f:
            har_file_data=json.load(f)
            #print(har_file_data)
            print(har_file_data["log"]["entries"][0]["request"])
            return har_file_data["log"]["entries"][0]["request"]

    def generate_case_by_har(self,orgin_template,testcase_filename,har_file):
        """
        生成对应的测试用例
        1、读取原本的模板文件
        2、替换模板文件中的数据信息
        3、生成新的测试用例文件
        :return:
        """
        har_data=self.load_har(har_file)
        with open(orgin_template,encoding="utf-8") as f:
            res=chevron.render(f.read(),har_data)
        with open(testcase_filename,"w",encoding="utf-8") as f:
            f.write(res)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/5/10 11:18
# @Author  : 杜兰特
# @File    : test_generate_case.py

from L5.har_to_case.generate_case import GenerateCase


generate_case=GenerateCase()

def test_load_har():
    generate_case.load_har("./template/httpbin.ceshiren.com.har")


def test_generate_case_by_har():
    generate_case.generate_case_by_har("./template/python_template","test_req.py","./template/httpbin.ceshiren.com.har")

def test_generate_httprunner_case_by_har():
    generate_case.generate_case_by_har("./template/httprunner_template","test_req.yaml","./template/httpbin.ceshiren.com.har")

def test_generate_java_case_by_har():
    generate_case.generate_case_by_har("./template/java_template","test_req.java","./template/httpbin.ceshiren.com.har")

1、python模板

模板文件

# python 接口测试用例
import requests
def test_request():
    r = requests.get(url="{{url}}",method="{{method}}",headers="{{headers}}")

生成的测试文件

# python 接口测试用例
import requests
def test_request():
    r = requests.get(url="https://httpbin.ceshiren.com/",method="GET",headers="[{'name': ':authority', 'value': 'httpbin.ceshiren.com'}, {'name': ':method', 'value': 'GET'}, {'name': ':path', 'value': '/'}, {'name': ':scheme', 'value': 'https'}, {'name': 'accept', 'value': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'}, {'name': 'accept-encoding', 'value': 'gzip, deflate, br'}, {'name': 'accept-language', 'value': 'zh-CN,zh;q=0.9'}, {'name': 'cache-control', 'value': 'max-age=0'}, {'name': 'cookie', 'value': '_ga=GA1.2.176134381.1632832298; sensorsdata2015jssdkcross=%7B%22%24device_id%22%3A%22186920d31dd1499-00e17cfac93039-26031951-1821369-186920d31de12dd%22%7D; Hm_lvt_214f62eef822bde113f63fedcab70931=1681872517,1682320279,1683459070; Hm_lpvt_214f62eef822bde113f63fedcab70931=1683459388'}, {'name': 'sec-ch-ua', 'value': '"Chromium";v="110", "Not A(Brand";v="24", "Google Chrome";v="110"'}, {'name': 'sec-ch-ua-mobile', 'value': '?0'}, {'name': 'sec-ch-ua-platform', 'value': '"Windows"'}, {'name': 'sec-fetch-dest', 'value': 'document'}, {'name': 'sec-fetch-mode', 'value': 'navigate'}, {'name': 'sec-fetch-site', 'value': 'none'}, {'name': 'sec-fetch-user', 'value': '?1'}, {'name': 'upgrade-insecure-requests', 'value': '1'}, {'name': 'user-agent', 'value': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'}]")

2、java模板

模板文件

// java 接口测试用例
package com.ceshiren.har;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
public class HttpbinTest {
    @Test
    void httpbinReq() {
        given()
                // 可以设置测试预设
                .when()
                // 发起 GET 请求
                .get("{{url}}")
                .then()
                // 解析结果
                .log().all()  // 打印完整响应信息
                .statusCode(200);  // 响应断言
    }
}

生成的测试文件

// java 接口测试用例
package com.ceshiren.har;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
public class HttpbinTest {
    @Test
    void httpbinReq() {
        given()
                // 可以设置测试预设
                .when()
                // 发起 GET 请求
                .get("https://httpbin.ceshiren.com/")
                .then()
                // 解析结果
                .log().all()  // 打印完整响应信息
                .statusCode(200);  // 响应断言
    }
}

3、httprunner模板

模板文件

# httprunner 的用例模版
config:
    name: basic test with httpbin
teststeps:
-
    name: httprunner的模板
    request:
        url: {{url}}
        method: GET
    validate_script:
        - "assert status_code == 200"

生成的测试文件

# httprunner 的用例模版
config:
    name: basic test with httpbin
teststeps:
-
    name: httprunner的模板
    request:
        url: https://httpbin.ceshiren.com/
        method: GET
    validate_script:
        - "assert status_code == 200"
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码敲到头发茂密

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值