【问题标题】:How to save the response of a Tavern test in a JSON file?如何将 Tavern 测试的响应保存在 JSON 文件中?
【发布时间】:2018-12-07 14:37:15
【问题描述】:

我正在使用 Tavern 工具进行 API 测试,我想在执行测试时将返回的响应保存在 JSON 文件中,因此我使用以下代码来响应 yaml 测试文件:

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

tavern_utils:save_response() 函数:

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

所以在使用 pytest 执行测试时,出现以下错误:

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

如何解决此错误或通过任何其他方法保存响应?

【问题讨论】:

标签: python json rest dictionary pytest


【解决方案1】:

找到解决方案: 只需将 save_response 函数替换为:

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

Yaml 测试文件为:

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

【讨论】:

    【解决方案2】:

    TextIOWrapper 是一个打开的文本文件,或者类似文件的东西(在你的情况下是某种网络响应对象)。你显然不能序列化它(它必须存储服务器的整个状态以及你和服务器之间的网络连接才能恢复同一个对象)。

    如果您希望将文件中的行序列化为字符串列表,这很容易。文件对象是其行上的迭代器,因此:

    list(f)
    

    ... 为您提供这些行的列表。

    如果你想将它序列化为一个巨大的字符串,你也可以这样做:

    f.read()
    

    或者,如果文件的内容已经是 JSON 编码的字符串,并且您想将其解码为可以序列化的值,您可以json.load 它。但是,除非您这样做是为了验证它确实是有效的 JSON,否则这有点愚蠢;您可以将 JSON 字符串作为字符串读取,然后将其作为字符串写回,而无需在任何地方执行任何 JSON 操作。

    如果您想要与以上任何一种不同的东西,您需要解释您想要做什么,但这可能是可行的。

    如果你想要不同的东西

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多