【问题标题】:How to test file response in Django?如何在 Django 中测试文件响应?
【发布时间】:2023-03-17 20:21:01
【问题描述】:

我有一个生成并返回 CSV 文件的 API:

def getCSV():
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=export.csv'
    writer = csv.writer(response, csv.excel)

    # ... Write some CSV content ...

    return response

当我从浏览器调用它时,它工作正常,但我不知道如何编写一个调用 API 的测试并检查 CSV 内容是否应该是。

如果我:

c = Client()
r = c.get('/my/export/api')
print(r.content)

这只是打印三个字节,很可能在概念上完全错误。

如何在我的测试中获取 CSV 文件响应的内容?

【问题讨论】:

标签: python django unit-testing csv testing


【解决方案1】:

How to read a csv django http response

import csv
import io

def test_csv_export(self):

    response = self.client.get('/my/export/api')
    self.assertEqual(response.status_code, 200)

    content = response.content.decode('utf-8')
    cvs_reader = csv.reader(io.StringIO(content))
    body = list(cvs_reader)
    headers = body.pop(0)

    print(body)
    print(headers)

【讨论】:

    猜你喜欢
    • 2018-12-07
    • 2016-01-27
    • 2020-04-10
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 2011-05-07
    • 2015-01-24
    • 1970-01-01
    相关资源
    最近更新 更多