简体   繁体   中英

Pyramid - Writing unittest for file upload form

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM