asyrjasalo / RESTinstance

Robot Framework library for RESTful JSON APIs
https://pypi.org/project/RESTinstance
GNU Lesser General Public License v3.0
206 stars 84 forks source link

Add support for asserting multiple matches with JSONPath #18

Closed asyrjasalo closed 6 years ago

asyrjasalo commented 6 years ago

This pull request adds support for using JSONPath queries in addition to the plain text response body ... matchers. JSONPath can be used with keywords Null, Boolean, Integer, Number, String, Object, Array and Missing, as well as the keyword Output.

JSONPath queries start with $ and are relative to the response body, unlike the plain text (e.g. response body id) are relative to the instance (response body being the instance field). This is to speed up writing tests, when testing for the responded JSON properties, which is pretty much the most common use case when testing for values.

For example, the following are possible with JSONPath:

*** Settings ***
Library         REST

*** Test Cases ***
JSONPath query from object
    GET         https://jsonplaceholder.typicode.com/users/1
    Integer     $.id                    1
    String      $..lat                  -37.3159
    String      $.name|$.username       Bret     # username matches
    Integer     $.name|$.id             13       # note that the previous 1 is kept in enum!
    Object      $.name|$.id|$.company            # company is a JSON object

JSONPath query from array
    GET        https://jsonplaceholder.typicode.com/users?_limit=5
    Array       $
    Integer     $[*].id                 1   2   3   4   5
    Integer     $[*].id                 minimum=1   maximum=5
    Integer     $.[0:1].id|$.[1:4].id   1   2   3   4   5
    Integer     $.[*] where $.id
    String      $[*].name               minLength=10
    Object      $.[*]..lat.`parent`

JSONPath was supported in the very early version of RESTinstance (before initially presenting it at the RoboCon 2018 on January), but was then dropped to keep things simple, mainly ensure that the JSON Schema generation works correctly before that. Anyway, this is now brought back and seems to work with JSON Schemas as expected.

We use https://pypi.org/project/jsonpath-ng (https://github.com/h2non/jsonpath-ng) by Tomas Aparicio and Kenn Knowles (I hope I got this right), under the hood. Thank you guys for a good implementation.