如何在Django中测试文件响应?

时间:2016-12-13 13:00:58

标签: python django unit-testing csv testing

我有一个生成并返回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文件响应的内容?

1 个答案:

答案 0 :(得分:5)

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)