Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 文件上传表单的金字塔写入单元测试_Python_Unit Testing_Python 2.7_Pyramid - Fatal编程技术网

Python 文件上传表单的金字塔写入单元测试

Python 文件上传表单的金字塔写入单元测试,python,unit-testing,python-2.7,pyramid,Python,Unit Testing,Python 2.7,Pyramid,我正在为负责上传从页面表单接收到的图片的函数创建unittests 主要的问题是,我不知道如何将图片添加到虚拟请求的post参数中,并将其传递给函数 这是我要测试的代码 谢谢 @view_config(route_name='profile_pic') def profilePictureUpload(request): if 'form.submitted' in request.params: #max picture size is 700kb form = Form(r

我正在为负责上传从页面表单接收到的图片的函数创建unittests

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

这是我要测试的代码

谢谢

@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)
使用客户端提供的名称(
upload.filename
)在文件系统上实际创建一个文件,这是一种非常糟糕的做法(而且可能存在安全漏洞)

这样,我在代码中看到您调用了
request.params
request.POST.get('profile')
upload.file
upload.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)

感谢您的回答,并指出我代码中的错误做法。我一定会把它修好的。