I have a Google App Engine app in Python that lets users upload files. After a file has been submitted, I get the file using
self.request.get('uploaded_file')
I get the filename using
self.request.POST['uploaded_file'].filename
I'm trying to write a unit test for it by manually creating a webapp request with the file set how I want it. However, I can't figure out how to initialize it such that I can get the uploaded file and its filename.
Any ideas?
If you're testing your handler, you're probably already creating a Webob request object and passing it to your handler, something like this:
request = webapp.Request({
"wsgi.input": StringIO.StringIO(),
"METHOD": "POST",
})
response = webapp.Response()
handler = MyHandler()
handler.initialize(request, response)
handler.post()
Uploaded files are cgi.FieldStorage objects, but FieldStorage is not particularly easy to test with. Instead, it's probably easiest to either use a mocking framework (such as mox) to create a mock, or just create a straightforward fake:
class FakeFieldStorage(object):
def __init__(self, filename, value):
self.filename = filename
self.value = value
Then create one and add it to the request object before you pass it to the handler:
uploaded_file = FakeFieldStorage("test.txt", "foo")
request.POST['file'] = uploaded_file
Test it by having the test actually send a request with a file attached to your app, using urlopen or similar.
Then validate the response and the state after the upload.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With