如何在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
没有键'file'的情况,其中 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
..
如何设置快乐路径的发布数据?
How do I set up the post data for the happy path?Can somebody tell me?
推荐答案
从 Client.pos t
:
From Django docs on 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屋!