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

@gregorynicholas gregorynicholas commented Dec 8, 2012

this saved my life.

@etscrivner

This comment has been minimized.

Copy link

@etscrivner etscrivner commented Nov 12, 2013

this saved my marriage

@ajferrick

This comment has been minimized.

Copy link

@ajferrick ajferrick commented Jan 10, 2014

this saved my family.

@mitgr81

This comment has been minimized.

Copy link

@mitgr81 mitgr81 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

@nickretallack nickretallack 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

@ereyes01 ereyes01 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

@gensmusic gensmusic commented Dec 7, 2015

this saved my country

@green4984

This comment has been minimized.

Copy link

@green4984 green4984 commented Jan 7, 2016

this saved my team leader

@mafrosis

This comment has been minimized.

Copy link

@mafrosis mafrosis commented Jan 30, 2016

this saved my CI server

@darioblanco

This comment has been minimized.

Copy link

@darioblanco darioblanco commented Mar 2, 2016

this saved my social life

@quantumew

This comment has been minimized.

Copy link

@quantumew quantumew commented Apr 20, 2016

This took my sanity

@pratikzambani

This comment has been minimized.

Copy link

@pratikzambani pratikzambani commented May 3, 2016

this saved jon snow

@aviaryan

This comment has been minimized.

Copy link

@aviaryan aviaryan commented May 16, 2016

this saved humanity

@SirNeuman

This comment has been minimized.

Copy link

@SirNeuman SirNeuman commented May 17, 2016

Why didn't this save Prince?

@spncrlkt

This comment has been minimized.

Copy link

@spncrlkt spncrlkt commented Jun 18, 2016

this did save Prince

@alissonperez

This comment has been minimized.

Copy link

@alissonperez alissonperez commented Jun 23, 2016

this saved Ned Stark! Thanks!!!

@guicheffer

This comment has been minimized.

Copy link

@guicheffer guicheffer commented Jun 23, 2016

this saved my job assignment opportunity

@arthurbarros

This comment has been minimized.

Copy link

@arthurbarros arthurbarros commented Sep 1, 2016

this saved Kappa

@feedingaliencat

This comment has been minimized.

Copy link

@feedingaliencat feedingaliencat 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

@popjxc popjxc commented Oct 10, 2016

This save my ut coverage!

@skortchmark9

This comment has been minimized.

Copy link

@skortchmark9 skortchmark9 commented Nov 19, 2016

This saved a file to my server

@uptown

This comment has been minimized.

Copy link

@uptown uptown commented Nov 28, 2016

This saved my boring afternoon

@EugeneKovalev

This comment has been minimized.

Copy link

@EugeneKovalev EugeneKovalev commented Nov 29, 2016

@feedingaliencat thanks, it works :)

@lightcast

This comment has been minimized.

Copy link

@lightcast lightcast commented Jan 20, 2017

This saved me an hour of code.

@cstubens

This comment has been minimized.

Copy link

@cstubens cstubens commented Jan 20, 2017

This saved baby jesus

@Ryanb58

This comment has been minimized.

Copy link

@Ryanb58 Ryanb58 commented May 16, 2017

This saved the earth.

@l1553k

This comment has been minimized.

Copy link

@l1553k l1553k commented May 25, 2017

This saved my file

@yrosgeru

This comment has been minimized.

Copy link

@yrosgeru yrosgeru commented Jun 21, 2017

This save the planet

@jaykam

This comment has been minimized.

Copy link

@jaykam jaykam commented Aug 2, 2017

@ereyes01
Thanx bro, it works fine.

@aluckcat

This comment has been minimized.

Copy link

@aluckcat aluckcat commented Aug 4, 2017

This saved my money

@deka108

This comment has been minimized.

Copy link

@deka108 deka108 commented Nov 9, 2017

this saved my sleeping hours

@PPitson

This comment has been minimized.

Copy link

@PPitson PPitson commented Nov 11, 2017

This saved my future children

@zominym

This comment has been minimized.

Copy link

@zominym zominym commented Nov 14, 2017

this saved my robot.

@sebbekarlsson

This comment has been minimized.

Copy link

@sebbekarlsson sebbekarlsson commented Jan 4, 2018

This totally saved my file

@miljkovicivan

This comment has been minimized.

Copy link

@miljkovicivan miljkovicivan commented Jan 4, 2018

This saved christmas

@OneNeptune

This comment has been minimized.

Copy link

@OneNeptune OneNeptune commented Jan 5, 2018

This saved my dog.

@dedgar1

This comment has been minimized.

Copy link

@dedgar1 dedgar1 commented Feb 12, 2018

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

@marco-lavagnino

This comment has been minimized.

Copy link

@marco-lavagnino marco-lavagnino commented Mar 12, 2018

This saved the docs from being comprehensive

@brettvanderwerff

This comment has been minimized.

Copy link

@brettvanderwerff brettvanderwerff commented Apr 6, 2018

this saved everything!

@aditshinde

This comment has been minimized.

Copy link

@aditshinde aditshinde commented May 7, 2018

This saved Avengers.

@SkamDart

This comment has been minimized.

Copy link

@SkamDart SkamDart commented May 10, 2018

This saved me tons of money on my car insurance.

@aedalton

This comment has been minimized.

Copy link

@aedalton aedalton commented May 11, 2018

This saved the cheerleader.

@mhsueh2

This comment has been minimized.

Copy link

@mhsueh2 mhsueh2 commented May 25, 2018

@ereyes01 You saved my soul

@adamloving

This comment has been minimized.

Copy link

@adamloving adamloving 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

@MohammadBarati MohammadBarati commented Jul 2, 2018

this save my Thumb

@llazzaro

This comment has been minimized.

Copy link

@llazzaro llazzaro commented Jul 17, 2018

this saved a segmentation fault

@JazzPote

This comment has been minimized.

Copy link

@JazzPote JazzPote commented Aug 1, 2018

This saved James Bond

@giovannibelzoni

This comment has been minimized.

Copy link

@giovannibelzoni giovannibelzoni commented Aug 7, 2018

this saved my bacon

@curif

This comment has been minimized.

Copy link

@curif curif commented Aug 15, 2018

this saved to file.

@nandan-pc

This comment has been minimized.

Copy link

@nandan-pc nandan-pc commented Sep 4, 2018

God Send, This saved my day!

@duquesnay

This comment has been minimized.

Copy link

@duquesnay duquesnay commented Sep 30, 2018

this saved my tire

@noplus

This comment has been minimized.

Copy link

@noplus noplus commented Oct 18, 2018

this saved my guitar

@joegasewicz

This comment has been minimized.

Copy link

@joegasewicz joegasewicz 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
       )
@envp

This comment has been minimized.

Copy link

@envp envp commented Feb 25, 2019

This saved me from myself

@BrianFehrle

This comment has been minimized.

Copy link

@BrianFehrle BrianFehrle commented Mar 18, 2019

This saved me from Thanos

@shmuli9

This comment has been minimized.

Copy link

@shmuli9 shmuli9 commented Apr 17, 2019

This saved Daniels awful code...

@CouchMaster789

This comment has been minimized.

Copy link

@CouchMaster789 CouchMaster789 commented Apr 17, 2019

This saved me from killing shmuli

@paulegradie

This comment has been minimized.

Copy link

@paulegradie paulegradie commented May 7, 2019

This... poor guy's inbox.

@poudel

This comment has been minimized.

Copy link

@poudel poudel commented Jun 25, 2019

This saved my button

@kmazi

This comment has been minimized.

Copy link

@kmazi kmazi commented Jul 3, 2019

This saved my breath

@codrex

This comment has been minimized.

Copy link

@codrex codrex commented Jul 3, 2019

This saved Nobody

@oladimillion

This comment has been minimized.

Copy link

@oladimillion oladimillion commented Jul 4, 2019

This saved my saved

@vonabarak

This comment has been minimized.

Copy link

@vonabarak vonabarak commented Jul 23, 2019

This saved this.

@Edgar-Lozano

This comment has been minimized.

Copy link

@Edgar-Lozano Edgar-Lozano commented Jul 23, 2019

This saved the Teletubbies.

@alexd2580

This comment has been minimized.

Copy link

@alexd2580 alexd2580 commented Feb 5, 2020

This saved me from going to the scrum-retro (And my coverage)

@shmam

This comment has been minimized.

Copy link

@shmam shmam commented Feb 26, 2020

This saved my senior design project

@santalvarez

This comment has been minimized.

Copy link

@santalvarez santalvarez commented Feb 27, 2020

This saved my job.

@ccardas

This comment has been minimized.

Copy link

@ccardas ccardas commented Mar 13, 2020

This saved my thesis

@jakegeno

This comment has been minimized.

Copy link

@jakegeno jakegeno commented Mar 19, 2020

This saved the humanity from corona virus. Oh wait not yet.

@fusmanii

This comment has been minimized.

Copy link

@fusmanii fusmanii commented Mar 27, 2020

This saved 15 or more on car insurance

@davidRichards39

This comment has been minimized.

Copy link

@davidRichards39 davidRichards39 commented Mar 27, 2020

This saved greg

@abhistack

This comment has been minimized.

Copy link

@abhistack abhistack commented Mar 27, 2020

greg

@jahin07

This comment has been minimized.

Copy link

@jahin07 jahin07 commented May 8, 2020

A long time ago this saved a galaxy far far away

@po5i

This comment has been minimized.

Copy link

@po5i po5i commented Aug 12, 2020

This saved me from covid

@finomayato

This comment has been minimized.

Copy link

@finomayato finomayato commented Sep 5, 2020

this saved my wolf

@betodealmeida

This comment has been minimized.

Copy link

@betodealmeida betodealmeida commented Nov 30, 2020

This saved 2020 from being a complete failure.

@aprilahijriyan

This comment has been minimized.

Copy link

@aprilahijriyan aprilahijriyan commented Mar 25, 2021

this saved me from covid (2)

@ifeLawal

This comment has been minimized.

Copy link

@ifeLawal ifeLawal commented May 25, 2021

This saved the queen (latifah)

@judeapana

This comment has been minimized.

Copy link

@judeapana judeapana commented May 28, 2021

This saved Jonah from the whale.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment