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

Testing the data sent by Flask's send_file()

我从一些数据中得到了一个 Flask view that generates an Excel file (using 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 header 是否符合预期。例如:

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

要检查 "the existance of the file",例如,您可以检查某些测试数据是否在预期的大小范围内。例如:

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 文件无效。