Skip to content

har 生成用例

霍格沃兹测试开发学社

ceshiren.com


目录

  • 课程目标
  • 应用场景
  • Har 介绍
  • har 生成用例

课程目标

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

应用场景

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

HttpRunner的har2case生成用例功能


Har 简介

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

实现思路

uml diagram


相关技术

  • 文件读写
  • 模版技术

模板技术

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

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

环境安装

pip install chevron

模版技术使用(Python)

  • 参数1: 模板数据
  • 参数2: 要替换的数据
import chevron
chevron.render('Hello, {{ mustache }}!', {'mustache': 'World'})

模版技术-环境安装(Java)

环境安装相关库

<!-- 模版相关库 -->
<dependency>
<groupId>com.github.spullara.mustache.java</groupId>
<artifactId>compiler</artifactId>
<version>0.9.10</version>
</dependency>

模版技术使用-环境配置(Java)

<!-- 演示过程的依赖配置 -->
<properties>
    <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
    <java.version>11</java.version>
    <junit.jupiter.version>5.9.1</junit.jupiter.version>
</properties>
<dependencyManagement>
    <!--        junit5 版本管理, 找到对应依赖关系的 pom 文件,为了解决依赖冲突问题-->
    <dependencies>
        <dependency>
            <groupId>org.junit</groupId>
            <artifactId>junit-bom</artifactId>
            <version>${junit.jupiter.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
        <!-- mustache 解析mustache文件 -->
    <dependency>
        <groupId>com.github.spullara.mustache.java</groupId>
        <artifactId>compiler</artifactId>
        <version>0.9.10</version>
    </dependency>
    <!--        junit 相关依赖下载-->
    <!-- junit5 -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- junit5-suite -->
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-suite</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- 用做兼容老版本 -->
    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        <scope>test</scope>
    </dependency>


</dependencies>

模版技术使用-代码实现(Java)

import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class MustacheExample {

    void soutTemplate() throws IOException {
//        /        初始化一个map,里面是要替换的数据
        Map<String, String> data = new HashMap<>();
        data.put("name", "John");
        data.put("age", "18");
//        初始化并读取模板文件中的内容
        DefaultMustacheFactory mustacheFactory = new DefaultMustacheFactory();
        Mustache mustache = mustacheFactory.compile("hogwarts.template");
//        将数据进行替换
        StringWriter writer = new StringWriter();
        mustache.execute(writer, data).flush();
//        将替换后的数据进行打印
        String output = writer.toString();
        System.out.println(output);
    }
}

har 生成用例实现思路

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

常用模板

// 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);  // 响应断言
    }
}
# httprunner 的用例模版
config:
    name: basic test with httpbin
teststeps:
-
    name: httprunner的模板
    request:
        url: {{ url }}
        method: GET
    validate_script:
        - "assert status_code == 200"
# python 接口测试用例
import requests
def test_request():
    r = requests.get(url="{{ url }}")

har 生成用例实现(Python)

import json
import pymustache

class GenerateCase:
# 读取har 文件的数据。
    def __load_har(self, har_filename):
        with open(har_filename) as f:
            har_data = json.load(f)
        return har_data["log"]["entries"][0]["request"]
# 根据 har 文件生成用例。
    def generate_case_by_har(self, origin_template, tescase_filename, har_filename):
        with open(origin_template) as f:
            template_data = pymustache.render(f.read(), self.__load_har(har_filename))
        with open(f"{tescase_filename}.py", "w") as f:
            f.write(template_data)

har 生成用例实现-环境配置(Java)

<!-- 相关配置文件 -->
<!--    版本配置-->
    <properties>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <java.version>11</java.version>
        <junit.jupiter.version>5.9.1</junit.jupiter.version>
        <maven.compiler.version>3.8.1</maven.compiler.version>
        <maven-surefire-plugin.version>3.0.0-M7</maven-surefire-plugin.version>
        <rest-assured.version>5.3.0</rest-assured.version>
        <json-path.version>2.7.0</json-path.version>
    </properties>
    <dependencyManagement>
<!--        junit5 版本管理, 找到对应依赖关系的 pom 文件,为了解决依赖冲突问题-->
        <dependencies>
            <dependency>
                <groupId>org.junit</groupId>
                <artifactId>junit-bom</artifactId>
                <version>${junit.jupiter.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <!-- json path 解析json文件 -->
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>${json-path.version}</version>
        </dependency>
<!--        junit 相关依赖下载-->
        <!-- junit5 -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- junit5-suite -->
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-suite</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 用做兼容老版本 -->
        <dependency>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- rest-assured -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${rest-assured.version}</version>
            <scope>compile</scope>
        </dependency>
        <!-- mustache 解析mustache文件 -->
        <dependency>
            <groupId>com.github.spullara.mustache.java</groupId>
            <artifactId>compiler</artifactId>
            <version>0.9.10</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
<!--            maven 命令行执行插件-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
<!--                防止maven与junit5使用依赖冲突的问题-->
                <dependencies>
                    <dependency>
                        <groupId>org.junit.jupiter</groupId>
                        <artifactId>junit-jupiter-engine</artifactId>
                        <version>${junit.jupiter.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                        <version>${junit.jupiter.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
<!--            maven 编译使用插件-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <parameters>true</parameters>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <encoding>${maven.compiler.encoding}</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

har 生成用例实现(Java)

import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

//生成测试用例
public class GenerateCase {
    // 从Har 文件中读取数据。
    private Map<String, String> loadHar(String filePath) {
        Map<String, String> requestData = new HashMap<>();
        try {

            DocumentContext context = JsonPath.parse(new File(filePath));
            ArrayList<String> harUrl = context.read("$..request.url", ArrayList.class);
            requestData.put("url", harUrl.get(0));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return requestData;
    }

    // 根据模板生成测试用例
    public void writeCaseByTemplate(String originTemplate, String testcaseFileName, String harFilename) {
        //  初始化并读取模板文件中的内容
        DefaultMustacheFactory mustacheFactory = new DefaultMustacheFactory();
        Mustache mustache = mustacheFactory.compile(originTemplate);
        //  将数据写入到文件中
        File outputFile = new File(testcaseFileName);
        try {
            PrintWriter writer = new PrintWriter(outputFile);
            mustache.execute(writer, loadHar(harFilename));
            writer.flush();
            writer.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

    }
}