04 template technology of interface automation request transfer parameters (JsonPath and Mustache)

1. Demand background

In the actual interface test, parameter passing may sometimes require a lot, or we just want a complete set of parameters, including required and non required items, such as the following json:

{
  "store": {
    "book": [
      {
        "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      {
        "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  },
  "expensive": 10
}

It's obviously unrealistic to pass in methods one by one. When writing in hashmap, the workload and complexity are also large. At this time, we need a template to define the parameters and structures we need in advance. We only need to modify the corresponding values, which leads to the two protagonists today:

  • JsonPath
  • Mustache

2,JsonPath

First, let's look at the first template technology, JsonPath. Note that JsonPath here refers to Jayway JsonPath. maven depends on the following:

  <dependency>
      <groupId>com.jayway.jsonpath</groupId>
      <artifactId>json-path</artifactId>
      <version>2.4.0</version>
  </dependency>

2.1 element positioning

In UI automation, we will use the element positioning technology of xpath. Here I compare it to facilitate understanding and memory. Jayway JsonPath provides us with two ways to write positioning:
$.store.book[0].title
$['store']['book'][0]['title']

Here I'm used to the first method, which is also recommended. It's similar to the method call in programming. I use $to start from the root element, and to find the element on the point, layer by layer, until it reaches the place you need to find. The same element can be distinguished according to the method of brackets [] + index, and the index starts from 0;

  • Operators, the following operators are officially provided

  • Demonstration of practical operation

    The following practical demonstration is divided into the following three steps:

    • Parse and obtain the content of json file with the parse method of Jayway JsonPath
    • Then use set method to modify the parsing result with Jayway JsonPath syntax
    • Finally, use Alibaba's fastJson to format and output the results, and view the modified results

    1) $. store.book[*].author -- author of all books
    Change the author name of all books to "test author"

    @Test
    void jsonPath() throws IOException {
        //jayway jsonpath
        DocumentContext documentContext = JsonPath.parse(this.getClass().getResourceAsStream("/book.json"));
        documentContext.set("$.store.book[*].author","Test author");
        String jsonString = documentContext.jsonString();
    
        //ali fastJson
        JSONObject object = JSONObject.parseObject(jsonString);
        String pretty = com.alibaba.fastjson.JSON.toJSONString(object, SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
        System.out.println(pretty);
    }
    

    Operation result:

    2) $. Store. * - all under the store are modified, including cycle and book
    Change all content under store to all change

    @Test
    void jsonPath() throws IOException {
        //jayway jsonpath
        DocumentContext documentContext = JsonPath.parse(this.getClass().getResourceAsStream("/book.json"));
        documentContext.set("$.store.*","all change");
        String jsonString = documentContext.jsonString();
    
        //ali fastJson
        JSONObject object = JSONObject.parseObject(jsonString);
        String pretty = com.alibaba.fastjson.JSON.toJSONString(object, SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
        System.out.println(pretty);
    }
    

    Operation result:

    3) $... book[0,1] - the first and second under book
    Change the first and second contents under the book to first two change

    @Test
    void jsonPath() throws IOException {
        //jayway jsonpath
        DocumentContext documentContext = JsonPath.parse(this.getClass().getResourceAsStream("/book.json"));
        documentContext.set("$..book[0,1]","first two change");
        String jsonString = documentContext.jsonString();
    
        //ali fastJson
        JSONObject object = JSONObject.parseObject(jsonString);
        String pretty = com.alibaba.fastjson.JSON.toJSONString(object, SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
        System.out.println(pretty);
    }
    

    Operation result:

    2.2 supplementary instructions

    The above is a few simple examples. In daily work, the most commonly used is to modify some fields in the template, and the rest fields that do not change often can be set in the template file;
    There are also many calculation methods and logical symbols available on the official website. If necessary, you can continue to study them on the official website:

    3,Mustache

    The template technology of JsonPath is introduced above, but there is a disadvantage, that is, JsonPath can only handle template files in json format. If it is non json, it is not good. At this time, there needs to be a general template technology, which is Mustache

    Mustache, literally means beard, probably because its template symbol is curly bracket. It's more like beard, such as the picture on the front page of the official website:


To illustrate, we can see that Mustache supports all kinds of languages, and almost all of them are commonly used. Here is Java for example. maven depends on the following:

  • Java 8+:
<dependency>
  <groupId>com.github.spullara.mustache.java</groupId>
  <artifactId>compiler</artifactId>
  <version>0.9.6</version>
</dependency>
  • Java 6/7:
<dependency>
  <groupId>com.github.spullara.mustache.java</groupId>
  <artifactId>compiler</artifactId>
  <version>0.8.18</version>
</dependency>

3.1 practical operation demonstration

  • First of all, in the file to be modified, the field to be modified is expressed in the form of double curly braces {{variable name}}}. For example, here we will make the author and price of the first product under the book variable
  • Create a HashMap and store the fields to be modified in the map
    HashMap<String,Object> map = new HashMap<>();
    map.put("author","mustacheAuthor");
    map.put("price",56.8f);
    
  • Create a DefaultMustacheFactory object
    MustacheFactory mf = new DefaultMustacheFactory();
    
  • compile method compiles the contents of the file, and execute executes the output
    @Test
    void mustacheTest() throws IOException {
        HashMap<String,Object> map = new HashMap<>();
        map.put("author","mustacheAuthor");
        map.put("price",56.8f);
    
        MustacheFactory mf = new DefaultMustacheFactory();
        Mustache mustache = mf.compile("book.json");
        Writer writer = new OutputStreamWriter(System.out);
        mustache.execute(writer, map);
        writer.flush();
    }
    
    Operation result:

    This seems to be a success, but if you look carefully, there will be a problem. price should be floating-point type, while the modified type is String type. This is because when we write variables, we have already included them in the String:

    What if I gave the string? As follows:

    Unfortunately, the json file will report an error!
  • So we also need to introduce a plug-in and change the suffix of the file to mustache (in fact, after you have the suffix, the IDE will automatically prompt you to need the plug-in and prompt you to install it. You don't need to find it yourself, so it's convenient ~)
  • After the plug-in is installed successfully, the file is as follows:

    Enter to view the content of the document, according to our previous experience, the first reaction is to become! It should be OK:
  • Of course, the feeling is the result of the actual test:
    @Test
    void mustacheTest() throws IOException {
        HashMap<String,Object> map = new HashMap<>();
        map.put("author","mustacheAuthor");
        map.put("price",56.8f);
    
        MustacheFactory mf = new DefaultMustacheFactory();
        Mustache mustache = mf.compile("book.mustache");
        Writer writer = new OutputStreamWriter(System.out);
        mustache.execute(writer, map);
        writer.flush();
        }
    
    Operation result:

    This result is very comfortable, meet the needs, solve problems, get a new skill!

4. Write at the end

Reference documents:
JsonPath: https://github.com/json-path/JsonPath
Mustache: https://github.com/spullara/mustache.java

Published 100 original articles, won praise 49, visited 20000+
Private letter follow

Tags: JSON Java github Maven

Posted on Tue, 14 Jan 2020 04:06:19 -0500 by bk6662