如何在 Django 中对文件上传进行单元测试 [英] how to unit test file upload in django
问题描述
在我的 django 应用程序中,我有一个完成文件上传的视图.核心片段是这样的
In my django app, I have a view which accomplishes file upload.The core snippet is like this
...
if (request.method == 'POST'):
if request.FILES.has_key('file'):
file = request.FILES['file']
with open(settings.destfolder+'/%s' % file.name, 'wb+') as dest:
for chunk in file.chunks():
dest.write(chunk)
我想对视图进行单元测试.我计划测试快乐路径和失败路径..即,request.FILES
没有关键文件"的情况,如果 request.FILES['file']
有 None
..
I would like to unit test the view.I am planning to test the happy path as well as the fail path..ie,the case where the request.FILES
has no key 'file' , case where request.FILES['file']
has None
..
如何设置快乐路径的post数据?谁能告诉我?
How do I set up the post data for the happy path?Can somebody tell me?
推荐答案
来自 Client.post
:
提交文件是一种特殊情况.要发布文件,您只需要提供文件字段名称作为键,以及文件的文件句柄您希望作为值上传.例如:
Submitting files is a special case. To POST a file, you need only provide the file field name as a key, and a file handle to the file you wish to upload as a value. For example:
c = Client()
with open('wishlist.doc') as fp:
c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
这篇关于如何在 Django 中对文件上传进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!