svanoort / pyresttest

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

suggestation to improve the jsonpath_mini function #198

Closed rsukla-handy closed 8 years ago

rsukla-handy commented 8 years ago

I was just wondering since REST API gives a json object where all the keys are always string so why do you need a int function inside the query dictionary. Please see the below function

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) # why this int function is needed here? 
                    dictionary = dictionary[x]
                except ValueError:
                    dictionary = dictionary[x]
    except:
        return None
    return dictionary
svanoort commented 8 years ago

@rsukla-handy A REST API can return an array rather than a dictionary (the use of 'dictionary' as the argument name here is a bit misleading). This is a little bit of magic to do lookup on that array by index.

In general though, the jsonpath_mini extractor is only for a minimal case where you need to do trivial validation without access to extra libraries. More complex validation should use the JSONSchema validator or JMESpath extractor (which does far more advanced querying). See the advanced.md docs for details.

I'm going to go ahead and close this one out, since I think that answers the question here, but would be happy to reopen it if you feel there's more to it.

Thanks, Sam