测试Flask的send_file()发送的数据 [英] Testing the data sent by Flask's send_file()

查看:61
本文介绍了测试Flask的send_file()发送的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个烧瓶视图,该视图生成一个Excel文件(使用

I have a Flask view that generates an Excel file (using openpyxl) from some data and it's returned to the user using send_file(). A very simplified version:

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 ):

This works fine -- the file downloads and is a valid Excel file. But I'm not sure how to test the file download. So far I have something like this (using 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文件吗?

Which passes, but I'd like to test that the (a) the filename used is as expected and (b) that the file... exists? Is an Excel file?

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

I can access response.get_data(), which is a bytes object, but I'm not sure what to do with it.

推荐答案

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

To check that the filename used is as expected you could check that the Content-Disposition header is as expected. For example:

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

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

To check "the existance of the file" you could for example check that for some test data it lies within an expected range of size. For example:

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

验证Excel文件是否有效的另一级别是尝试将数据加载回 openpyxl 并检查其是否报告任何问题.例如:

Another level of verifying that the Excel file works would be attempting to load the data back into openpyxl and checking if it reports any problems. For example:

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

在这里您可能会遇到诸如以下的异常情况:

Here you risk running into some sort of exception like:

zipfile.BadZipFile: File is not a zip file

这将表明该文件的数据内容作为Excel文件无效.

Which would indicate that the data contents of the file are invalid as a Excel file.

这篇关于测试Flask的send_file()发送的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆