如何为Django中的文件上传类编写单元测试?

3 投票
2 回答
1792 浏览
提问于 2025-04-17 20:35

我正在尝试为一个类编写单元测试,这个类有一个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()来编写测试用例,但我还是搞不清楚如何为这种类型的类/视图编写单元测试……

2 个回答

0

你可以试着用一些工具来模拟你需要的东西,比如这个

4

你可以使用Django里的测试客户端。这个工具非常简单好用。

下面是Django文档中的一个例子:

>>> c = Client()
>>> with open('wishlist.doc') as fp:
...     c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})

撰写回答