简体   繁体   中英

How to save the response of a Tavern test in a JSON file?

I am using Tavern tool for API testing and I want to save the returned response in a JSON file while the test is being executed so I am using the following code in response of the yaml test file:

 response:
    status_code: 200
    save:
      $ext:
        function: tavern_utils:save_response

The tavern_utils:save_response() function:

def save_response(response):
    with open('saved.json','w') as file:
       json.dump(file,response.json())

So while executing the test with pytest, I get the following error:

TypeError: The Object of type 'TextIOWrapper' is not JSON serializable

How to solve this error or save the response by any other method?

Got the solution: Just replace the save_response function with this:

def save_response(response):
    filename='file4.json'
    with open(filename, 'w') as f:
        json.dump(response.json(), f)

And the Yaml test file as:

  response:
    status_code: 200
    body:
      $ext:
        function: tavern_utils:save_response            

A TextIOWrapper is an open text file, or something that acts like one (in your case some kind of net response object). You obviously can't serialize that (it would have to store the entire state of the server and the network connection between you and the server to restore the same object).

If you're looking to serialize the lines in the file, as a list of strings, that's easy. A file object is an iterator over its lines, so:

list(f)

… gives you a list of those lines.

If you want to serialize it as one giant string, you can do that too:

f.read()

Or, if the file's contents are already a JSON-encoded string, and you want to decode that to a value that you can serialize, you could json.load it. But, unless you're doing this to validate that it really is valid JSON, this is kind of silly; you could just read the JSON string as a string and write it back out as a string without doing any JSON stuff anywhere.

If you want something different than any of these, you'll need to explain what you're trying to do, but it's probably doable.

If you want something different

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM