Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Testing file upload handling in Flask
#!/usr/bin/env python
from flask import Flask, Request, request
from StringIO import StringIO
import unittest
RESULT = False
class TestFileFail(unittest.TestCase):
def test_1(self):
class FileObj(StringIO):
def close(self):
print 'in file close'
global RESULT
RESULT = True
class MyRequest(Request):
def _get_file_stream(*args, **kwargs):
return FileObj()
app = Flask(__name__)
app.debug = True
app.request_class = MyRequest
@app.route("/upload", methods=['POST'])
def upload():
f = request.files['file']
print 'in upload handler'
self.assertIsInstance(
f.stream,
FileObj,
)
# Note I've monkeypatched werkzeug.datastructures.FileStorage
# so it wont squash exceptions
f.close()
#f.stream.close()
return 'ok'
client = app.test_client()
resp = client.post(
'/upload',
data = {
'file': (StringIO('my file contents'), 'hello world.txt'),
}
)
self.assertEqual(
'ok',
resp.data,
)
global RESULT
self.assertTrue(RESULT)
def test_2(self):
pass
if __name__ == '__main__':
unittest.main()
in upload handler
in file close
..
----------------------------------------------------------------------
Ran 2 tests in 0.021s
OK
@gregorynicholas

This comment has been minimized.

Copy link

commented Dec 8, 2012

this saved my life.

@etscrivner

This comment has been minimized.

Copy link

commented Nov 12, 2013

this saved my marriage

@ajferrick

This comment has been minimized.

Copy link

commented Jan 10, 2014

this saved my family.

@mitgr81

This comment has been minimized.

Copy link

commented Jan 10, 2014

this saved my pants.

(I forked it and made it py3-lovvin: https://gist.github.com/mitgr81/8355834)

@nickretallack

This comment has been minimized.

Copy link

commented Feb 15, 2014

You don't have to override the request class to test file uploads. Just make sure you specify the Content-Type: multipart/form-data header. A better way to test this would be to put your upload directory in a configuration setting and have your test clear out that folder, run the upload, and then check that the file was put there.

@ereyes01

This comment has been minimized.

Copy link

commented May 6, 2014

Agree with @nickretallack ... the following worked just fine for me:

app_client = app.test_client()
response = app_client.post('blueprint/upload_file', buffered=True,
                           content_type='multipart/form-data',
                           data={'form_field1' : 'field1_data',
                                 'form_field2' : 'field2_data',
                                 'file_field' : (StringIO('hello there'), 'hello.txt')})

You have to replace StringIO with ByteIO for Python 3, I think.

@gensmusic

This comment has been minimized.

Copy link

commented Dec 7, 2015

this saved my country

@green4984

This comment has been minimized.

Copy link

commented Jan 7, 2016

this saved my team leader

@mafrosis

This comment has been minimized.

Copy link

commented Jan 30, 2016

this saved my CI server

@darioblanco

This comment has been minimized.

Copy link

commented Mar 2, 2016

this saved my social life

@quantumew

This comment has been minimized.

Copy link

commented Apr 20, 2016

This took my sanity

@pratikzambani

This comment has been minimized.

Copy link

commented May 3, 2016

this saved jon snow

@aviaryan

This comment has been minimized.

Copy link

commented May 16, 2016

this saved humanity

@SirNeuman

This comment has been minimized.

Copy link

commented May 17, 2016

Why didn't this save Prince?

@spncrlkt

This comment has been minimized.

Copy link

commented Jun 18, 2016

this did save Prince

@alissonperez

This comment has been minimized.

Copy link

commented Jun 23, 2016

this saved Ned Stark! Thanks!!!

@guicheffer

This comment has been minimized.

Copy link

commented Jun 23, 2016

this saved my job assignment opportunity

@arthurbarros

This comment has been minimized.

Copy link

commented Sep 1, 2016

this saved Kappa

@feedingaliencat

This comment has been minimized.

Copy link

commented Sep 12, 2016

If you're using Python3, consider using BytesIO instead of StringIO

from io import BytesIO

[...]

        resp = client.post(
            '/upload',
            data = {
                'file': (BytesIO(b'my file contents'), 'hello world.txt'),
            }
        )

In this way, it should continue saving things.

You can also send open files:

import tempfile

[...]

    mb = 1
    with tempfile.TemporaryFile() as tf:
        tf.seek(mb * 1024 * 1024 - 1)
        tf.write(b'0')
        tf.seek(0)

        with app.test_client() as client:
            resp = client.post('/upload', data={
                'file': (tf, 'filename.txt')
            })
@popjxc

This comment has been minimized.

Copy link

commented Oct 10, 2016

This save my ut coverage!

@skortchmark9

This comment has been minimized.

Copy link

commented Nov 19, 2016

This saved a file to my server

@uptown

This comment has been minimized.

Copy link

commented Nov 28, 2016

This saved my boring afternoon

@EugeneKovalev

This comment has been minimized.

Copy link

commented Nov 29, 2016

@feedingaliencat thanks, it works :)

@lightcast

This comment has been minimized.

Copy link

commented Jan 20, 2017

This saved me an hour of code.

@cstubens

This comment has been minimized.

Copy link

commented Jan 20, 2017

This saved baby jesus

@Ryanb58

This comment has been minimized.

Copy link

commented May 16, 2017

This saved the earth.

@l1553k

This comment has been minimized.

Copy link

commented May 25, 2017

This saved my file

@yrosgeru

This comment has been minimized.

Copy link

commented Jun 21, 2017

This save the planet

@jaykam

This comment has been minimized.

Copy link

commented Aug 2, 2017

@ereyes01
Thanx bro, it works fine.

@aluckcat

This comment has been minimized.

Copy link

commented Aug 4, 2017

This saved my money

@deka108

This comment has been minimized.

Copy link

commented Nov 9, 2017

this saved my sleeping hours

@PPitson

This comment has been minimized.

Copy link

commented Nov 11, 2017

This saved my future children

@zominym

This comment has been minimized.

Copy link

commented Nov 14, 2017

this saved my robot.

@sebbekarlsson

This comment has been minimized.

Copy link

commented Jan 4, 2018

This totally saved my file

@miljkovicivan

This comment has been minimized.

Copy link

commented Jan 4, 2018

This saved christmas

@OneNeptune

This comment has been minimized.

Copy link

commented Jan 5, 2018

This saved my dog.

@dedgar1

This comment has been minimized.

Copy link

commented Feb 12, 2018

Thanks.
This saved..................... uh, can't think of anything good enough

@marco-lavagnino

This comment has been minimized.

Copy link

commented Mar 12, 2018

This saved the docs from being comprehensive

@brettvanderwerff

This comment has been minimized.

Copy link

commented Apr 6, 2018

this saved everything!

@aditshinde

This comment has been minimized.

Copy link

commented May 7, 2018

This saved Avengers.

@SkamDart

This comment has been minimized.

Copy link

commented May 10, 2018

This saved me tons of money on my car insurance.

@aedalton

This comment has been minimized.

Copy link

commented May 11, 2018

This saved the cheerleader.

@mhsueh2

This comment has been minimized.

Copy link

commented May 25, 2018

@ereyes01 You saved my soul

@adamloving

This comment has been minimized.

Copy link

commented Jun 7, 2018

I decided it was time to write proper tests for my controllers, but times have been tough at home since Prince passed away. My favorite pants got ruined when I discovered the USA didn't qualify for the world cup. I can't even do a simple fake file upload with werkzeug. The CI server has been down for days. Jon Snow called to offer me a discount on my car insurance... because I almost got fired at work. When Microsoft bought Github, I was worried I wouldn't be able to get help. So, when I cracked open Google and quickly found this solution - tears welled up. You, @DazWorrall are a good person. For our future children, thank you. If baby jesus were born today as a robot, it would agree with me.

@MohammadBarati

This comment has been minimized.

Copy link

commented Jul 2, 2018

this save my Thumb

@llazzaro

This comment has been minimized.

Copy link

commented Jul 17, 2018

this saved a segmentation fault

@JackPoteYes

This comment has been minimized.

Copy link

commented Aug 1, 2018

This saved James Bond

@giovannibelzoni

This comment has been minimized.

Copy link

commented Aug 7, 2018

this saved my bacon

@curif

This comment has been minimized.

Copy link

commented Aug 15, 2018

this saved to file.

@nandan-pc

This comment has been minimized.

Copy link

commented Sep 4, 2018

God Send, This saved my day!

@duquesnay

This comment has been minimized.

Copy link

commented Sep 30, 2018

this saved my tire

@NonSvizzero

This comment has been minimized.

Copy link

commented Oct 18, 2018

this saved my guitar

@joegasewicz

This comment has been minimized.

Copy link

commented Nov 24, 2018

if anyone is using flask with Cloudinary and testing for integration, you'll need a real image, so you could do this:

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

This comment has been minimized.

Copy link

commented Feb 25, 2019

This saved me from myself

@BrianFehrle

This comment has been minimized.

Copy link

commented Mar 18, 2019

This saved me from Thanos

@shmuli9

This comment has been minimized.

Copy link

commented Apr 17, 2019

This saved Daniels awful code...

@CouchMaster789

This comment has been minimized.

Copy link

commented Apr 17, 2019

This saved me from killing shmuli

@paulegradie

This comment has been minimized.

Copy link

commented May 7, 2019

This... poor guy's inbox.

@poudel

This comment has been minimized.

Copy link

commented Jun 25, 2019

This saved my button

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.