在Flask中测试文件上传

时间:2016-02-28 15:33:39

标签: python-3.x flask python-unittest flask-testing

我使用Flask-Testing进行Flask集成测试。我有一个表单,上面有一个徽标文件,我试图为其编写测试但是我一直收到错误说:TypeError: 'str' does not support the buffer interface

我使用的是Python 3.我找到的最接近的答案是this,但它对我不起作用。

这是我多次尝试之一:

def test_edit_logo(self):
    """Test can upload logo."""
    data = {'name': 'this is a name', 'age': 12}
    data['file'] = (io.BytesIO(b"abcdef"), 'test.jpg')
    self.login()
    response = self.client.post(
        url_for('items.save'), data=data, follow_redirects=True)
    })
    self.assertIn(b'Your item has been saved.', response.data)
    advert = Advert.query.get(1)
    self.assertIsNotNone(item.logo)

如何在Flask中测试文件上传?

5 个答案:

答案 0 :(得分:14)

问题最终不在于,当content_type='multipart/form-data'方法添加post时,它希望data中的所有值都是文件或字符串。我的数据字典中有整数,我感谢this评论。

所以最终解决方案看起来像这样:

def test_edit_logo(self):
    """Test can upload logo."""
    data = {'name': 'this is a name', 'age': 12}
    data = {key: str(value) for key, value in data.items()}
    data['file'] = (io.BytesIO(b"abcdef"), 'test.jpg')
    self.login()
    response = self.client.post(
        url_for('adverts.save'), data=data, follow_redirects=True,
        content_type='multipart/form-data'
    )
    self.assertIn(b'Your item has been saved.', response.data)
    advert = Item.query.get(1)
    self.assertIsNotNone(item.logo)

答案 1 :(得分:11)

你需要两件事:

1。{} content_type='multipart/form-data'.post()中 2.)data= file=(BytesIO(b'my file contents'), "file_name.jpg")传递 data = dict( file=(BytesIO(b'my file contents'), "work_order.123"), ) response = app.post(url_for('items.save'), content_type='multipart/form-data', data=data)

一个完整的例子:

    Intent in = new Intent("my.action.string");
    in.putExtra("state", "activated");
    sendBroadcast(in);

答案 2 :(得分:0)

您可以使用Werkzeug的FileStorage(Flask在引擎盖下使用)。

请注意,我在服务器上使用了真实文件: tests/assets/my_video.mp4

但是您可以使用io.BytesIO(b"abcdef")

来模拟它
from werkzeug.datastructures import FileStorage


my_video = os.path.join("tests/assets/my_video.mp4")

my_file = FileStorage(
    stream=open(my_video, "rb"),
    filename="my_video.mp4",
    content_type="video/mpeg",
),

rv = client.post(
   "/api/v1/video",
   data={
      "my_video": my_file,
   },
   content_type="multipart/form-data"
)

测试是否返回了响应状态码200:

assert "200" in rv.status

然后我可以测试文件是否到达服务器上的测试目录:

assert "my_video.mp4" in os.listdir("tests/my_test_path")

答案 3 :(得分:0)

在尝试查找代码中的错误时,我创建了一个用于文件上传的SSCCE(基于the docs),并根据此处的其他答案进行了相应的测试。对某人可能有用:

app.py:

import base64
import os
import pathlib
import tempfile
import textwrap

import flask
import werkzeug.utils

root = flask.Blueprint('root', __name__)

@root.route('/', methods=['GET', 'POST'])
def upload_file():
    if flask.request.method == 'POST':
        try:
            file = flask.request.files['file']
            if not file.filename:
                raise LookupError()
            filename = werkzeug.utils.secure_filename(file.filename)
            file.save(pathlib.Path(flask.current_app.config['UPLOAD_FOLDER'], filename))
            flask.flash('File saved!', 'message')
        except LookupError:
            flask.flash('No file provided!', 'error')
        return flask.redirect(flask.url_for('root.upload_file'))
    else:
        return flask.render_template_string(textwrap.dedent(
            '''\
            <!doctype html>
            <title>Upload new File</title>
            {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
            <ul class=flashes>
            {% for category, message in messages %}<li class="{{ category }}">{{ message }}</li>
            {% endfor %}
            </ul>
            {% endif %}{% endwith %}
            <h1>Upload new File</h1>
            <form method=post enctype=multipart/form-data>
            <input type=file name=file>
            <input type=submit value=Upload>
            </form>
            '''
        ))

def create_app():
    app = flask.Flask(__name__)
    app.config['UPLOAD_FOLDER'] = tempfile.gettempdir()
    app.secret_key = 'change-me'
    app.register_blueprint(root)
    return app

if __name__ == '__main__':
    create_app()

test_app.py:

"""upload tests"""

import base64
import io
import unittest

import werkzeug

import app

# https://raw.githubusercontent.com/mathiasbynens/small/master/jpeg.jpg
SMALLEST_JPEG_B64 = """\
/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8Q
EBEQCgwSExIQEw8QEBD/yQALCAABAAEBAREA/8wABgAQEAX/2gAIAQEAAD8A0s8g/9k=
"""

class BaseTestCase(unittest.TestCase):
    def test_save(self):
        with app.create_app().test_client() as client:
            file = werkzeug.datastructures.FileStorage(
                stream=io.BytesIO(base64.b64decode(SMALLEST_JPEG_B64)),
                filename="example image.jpg",
                content_type="image/jpg",
            )
            response = client.post(
                '/',
                data=dict(
                    file=file,
                ),
                follow_redirects=True,
                content_type='multipart/form-data',
            )

答案 4 :(得分:-1)

如果由于要测试与Cloudinary之类的云服务的集成而需要测试真实文件,则可以执行以下操作:

  asset = "test_asset.jpg"
  file = os.path.join(f"./tests/assets/{asset}")
  rv = client.put(
        "/api/v1/user/1",
        data={
            "avatar_image": (file, asset)
            },
        headers=headers
   )