测试 Flask 的 send_file() 发送的数据



>我有一个 Flask 视图,它从一些数据生成一个 Excel 文件(使用 openpyxl),并使用send_file()将其返回给用户。一个非常简化的版本:

import io
from flask import send_file
from openpyxl.workbook import Workbook
@app.route("/download/<int:id>")
def file_download(id):
wb = Workbook()
# Add sheets and data to the workbook here.
file = io.BytesIO()
wb.save(file)
file.seek(0)
return send_file(file, attachment_filename=f"{id}.xlsx", as_attachment=True)

这工作正常 - 文件下载并且是有效的 Excel 文件。但我不确定如何测试文件下载。到目前为止,我有这样的东西(使用 pytest):

def test_file_download(test_client):
response = test_client.get("/download/123")
assert response.status_code == 200
assert response.content_type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

这通过了,但我想测试一下 (a) 使用的文件名是否符合预期,以及 (b) 文件......存在?是 Excel 文件吗?

我可以访问response.get_data(),这是一个bytes的对象,但我不确定如何处理它。

要检查使用的文件名是否符合预期,您可以检查Content-Disposition标头是否符合预期。例如:

assert response.headers['Content-Disposition'] == 'attachment; filename=123.xlsx'

例如,要检查"文件是否存在",您可以检查某些测试数据是否位于预期的大小范围内。例如:

assert 3000 <= response.content_length <= 5000
assert 3000 <= len(response.data) <= 5000

验证 Excel 文件是否正常工作的另一个级别是尝试将数据加载回openpyxl并检查它是否报告了任何问题。例如:

from io import BytesIO
from openpyxl import load_workbook
load_workbook(filename=BytesIO(response.data))

在这里,您可能会遇到某种异常,例如:

zipfile.BadZipFile: File is not a zip file

这将指示文件的数据内容作为 Excel 文件无效。

相关内容

最新更新