Testing file uploads in Flask

前端 未结 4 405
庸人自扰
庸人自扰 2021-02-02 07:32

I\'m using Flask-Testing for my Flask integration tests. I\'ve got a form that has a file upload for a logo that I\'m trying to write tests for but I keep getting an error sayin

4条回答
  •  日久生厌
    2021-02-02 08:07

    While trying to find a bug in my code I've created a SSCCE for file upload (based on the docs) with a corresponding test based on other answers here. It might be useful for somebody:

    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(
                '''\
                
                Upload new File
                {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
                
      {% for category, message in messages %}
    • {{ message }}
    • {% endfor %}
    {% endif %}{% endwith %}

    Upload new File

    ''' )) 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',
                )
    

提交回复
热议问题