Skip to content

多协议封装设计

多响应类型封装设计

简介

在工作中我们可能会遇到不同的请求协议类型,有的是json,有的可能是xml会给我们造成一些困难

  • 响应值不统一

    • json
    • xml
  • 断言比较困难

解决方案:获得的响应信息全部转换为结构化的数据进行处理

uml diagram

uml diagram

实战演练

对响应值做二次封装,可以使用统一提取方式完成断言。

Python 演示代码

  • 环境准备: pip install xmltodict
  • 依赖包版本: 0.13
import requests
import xmltodict
from requests.models import Response
def response_to_dict(response: Response):
    """
    获取 Response对象,将多种响应格式统一转换为dict
    :param response:
    :return:
    """
    res_text = response.text
    if res_text.startswith("<?xml"):
        final_res = xmltodict.parse(res_text)
    else:
        final_res = response.json()
    return final_res
# 测试响应是否可以转换为dict
def response_dict():
    """
    xml转换为json
    :return:
    """
    # res = requests.get("https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss")
    res = requests.get("https://httpbin.ceshiren.com/get")
    r = response_to_dict(res)
    print(r)
    assert isinstance(r, dict)

response_dict()

Java 演示代码

环境依赖

<!-- pom中的依赖 -->
<!-- 直接将xml转换成字符串json -->
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.13.1</version>
</dependency>
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.6.0</version>
    <scope>test</scope>
</dependency>
  • 多种类型的响应全部转换为标准的 json 进行断言
public class MulitiResTest {

    String resToJson(String originRes) throws IOException {
        if(originRes.startsWith("<?xml")){
            XmlMapper xmlMapper = new XmlMapper();
            JsonNode node = xmlMapper.readTree(originRes.getBytes());
            ObjectMapper jsonMapper = new ObjectMapper();
            originRes = jsonMapper.writeValueAsString(node);
        }
        return originRes;
    }

    @Test
    // 部分代码
    void resToJson() throws IOException {
        String result = given()
                .when()
//                .get("https://httpbin.ceshiren.com/get")
                .get("https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss")
                .then().extract().body().asString();
        // 调用转换成json的方法
        String res = resToJson(result);
        // 如果是向"https://httpbin.ceshiren.com/get"发起请求
//        String host = JsonPath.read(res, "$..Host");
//        assertEquals("httpbin.ceshiren.com", host);
//         如果是向"https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss"发起请求
//        System.out.println(res);
        List<String> titleList = JsonPath.read(res, "$..title");
        assertEquals(titleList.get(0),"NASA Image of the Day");
    }

}

总结

  • 多套响应类型封装