【问题标题】:Pyramid - Writing unittest for file upload formPyramid - 为文件上传表单编写单元测试
【发布时间】:2012-06-19 13:50:22
【问题描述】:

我正在努力为负责上传从页面上的表单收到的图片的功能创建单元测试。

主要问题是我不知道如何将图片添加到虚拟请求的发布参数中,并因此将其传递给函数。

这是我要测试的代码。

谢谢

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

【问题讨论】:

    标签: python unit-testing python-2.7 pyramid


    【解决方案1】:

    使用客户端提供的名称 (upload.filename) 在文件系统上实际创建文件是非常糟糕的做法(并且存在潜在的安全漏洞)。

    除此之外,我在您的代码中看到您调用request.paramsrequest.POST.get('profile')upload.fileupload.filename。我们可以模拟所有这些,最终为upload.file 提供一个StringIO 对象。

    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)
    

    【讨论】:

    • 感谢您的回答并指出我的代码中的不良做法。我一定会解决的。
    猜你喜欢
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    • 2020-05-28
    • 1970-01-01
    • 2017-04-06
    • 2013-09-30
    相关资源
    最近更新 更多