如何为Django中的文件上传类编写单元测试?
我正在尝试为一个类编写单元测试,这个类有一个POST方法,用于将文档上传到基于Django的网页应用程序。以下是我想为其编写单元测试的视图类:
class SOP(APIView):
authentication_classes = (authentication.TokenAuthentication,)
def post(self,request):
returnDict={}
returnDict['msg']='File not uploaded'
#if form.is_valid():
newdoc = Document(sopFile = request.FILES['sopFile'])
newdoc.save()
returnDict['msg']='File uploaded'
returnDict['fileName']=newdoc.sopFile.name
# Redirect to the document list after POST
return Response(returnDict)
因为我的Django应用程序使用forms.py来上传文件,所以我也把那部分代码放在这里:
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)
我尝试使用RequestFactory()和TestCase()来编写测试用例,但我还是搞不清楚如何为这种类型的类/视图编写单元测试……