我正在尝试为一个类编写单元测试,该类具有用于将文档上传到基于 Web 的 Django 应用程序的 POST 方法。这是我要为其编写单元测试的 View 类:
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() 编写测试用例,但我不知道如何为此类类/ View 编写单元测试...
最佳答案
您可以使用 the test client来自 Django 。它非常易于使用。
来自 Django 文档的示例:
>>> c = Client()
>>> with open('wishlist.doc') as fp:
... c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
关于python - 如何在 Django 中为文件上传类编写单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22142610/