svanoort / pyresttest

Python Rest Testing
Apache License 2.0
1.15k stars 325 forks source link

jsonpath_mini fail to extract value from a json array #197

Closed manueligno78 closed 8 years ago

manueligno78 commented 8 years ago

I'm trying to validate some responses and i'm using jsonpath_mini extractor. This is the response, it is a json array, i have to extract the value of the id of the first array element:

[
  {
    "id": "Vendor",
    "creationDate": "2016-05-19T08:42:59Z",
    "modifiedDate": "2016-05-19T08:42:59Z",
    "modelType": "VENDOR",
    "s3BucketRootPath": "myS3BucketPath"
  },
  {
    "id": "Vendor2",
    "creationDate": "2016-05-19T08:51:18Z",
    "modifiedDate": "2016-05-19T08:51:18Z",
    "modelType": "VENDOR",
    "s3BucketRootPath": "myS3BucketPath"
  }
]

This is my validator:

- validators:
     # Check the user name matches
     - compare: {jsonpath_mini: "[0].id", comparator: "eq", expected: 'Vendor'}

This validation at the moment fails, but shouldn't as indeed testing it against http://jmespath.org/

The extractor seems to return "None" instead of "Vendor" as reported by test output:

ERROR:Test Failure, failure type: Validator Failed, Reason: Comparison failed, evaluating eq(None, chiliVendor) returned False
ERROR:Validator/Error details:Extractor: Extractor Type: jsonpath_mini,  Query: "[0].id", Templated?: False
rsukla-handy commented 8 years ago

This will not work since the your json object is an array not proper dictionary response. The function below is used to compute jsonpath_mini

@staticmethod
    def query_dictionary(query, dictionary, delimiter='.'):
        """ Do an xpath-like query with dictionary, using a template if relevant """
        # Based on
        # http://stackoverflow.com/questions/7320319/xpath-like-query-for-nested-python-dictionaries

        try:
            stripped_query = query.strip(delimiter)
            if stripped_query:
                for x in stripped_query.split(delimiter):
                    try:
                        x = int(x)
                        dictionary = dictionary[x]
                    except ValueError:
                        dictionary = dictionary[x]
        except:
            return None
        return dictionary
manueligno78 commented 8 years ago

So no way to get it works.. neither with next releases?

svanoort commented 8 years ago

@manueligno78 and @rsukla-handy Actually... we added a feature that allows this with the last release: the JMESpath extractor --https://github.com/svanoort/pyresttest/blob/master/advanced_guide.md#extractor-jmespath

You'll need to have the JMESPath library installed for it to work: PyRestTest does not auto-install it, because it's attempting to keep core dependencies minimal, but the jmespath extractor will automatically become available when the necessary libraries are installed.

manueligno78 commented 8 years ago

Thank you, my mistake.