Reputation: 249
I'm strugling with creating unittests for function in charge of uploading pictures recieved from a form on a page.
Main problem is that I can't figure out how to add picture to post parameters of a dummy request and as such pass it to function.
Here is code I'm trying to test.
Thanks
@view_config(route_name='profile_pic')
def profilePictureUpload(request):
if 'form.submitted' in request.params:
#max picture size is 700kb
form = Form(request, schema=PictureUpload)
if request.method == 'POST' and form.validate():
upload_directory = 'filesystem_path'
upload = request.POST.get('profile')
saved_file = str(upload_directory) + str(upload.filename)
perm_file = open(saved_file, 'wb')
shutil.copyfileobj(upload.file, perm_file)
upload.file.close()
perm_file.close()
else:
log.info(form.errors)
redirect_url = route_url('profile', request)
return HTTPFound(location=redirect_url)
Upvotes: 3
Views: 1759
Reputation: 23331
It's really bad practice (and a potential security hole) to actually create a file on your filesystem with the a name supplied by the client (upload.filename
).
With that out of the way, I see in your code you call request.params
, request.POST.get('profile')
, upload.file
and upload.filename
. We can mock all of these out, ultimately providing a StringIO object for upload.file
.
class MockCGIFieldStorage(object):
pass
upload = MockCGIFieldStorage()
upload.file = StringIO('foo')
upload.filename = 'foo.html'
request = DummyRequest(post={'profile': upload, 'form.submitted': '1'})
response = profilePictureUpload(request)
Upvotes: 10