开发者

Simulating a Google App Engine File Upload in Python

开发者 https://www.devze.com 2023-03-26 15:40 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号