我正在努力创建单元测试功能,负责上传从页面上的表单收到的图片。
主要问题是我无法弄清楚如何将图片添加到虚拟请求的发布参数中,并因此将其传递给函数。
以下是我正在尝试测试的代码。
由于
@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)
答案 0 :(得分:10)
使用客户端提供的名称(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)