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

2024-10-04 07:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为一个类编写单元测试,该类有一个POST方法,用于将文档上载到基于web的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应用程序正在使用表单.py为了上传一个文件,所以我把代码也和这个放在一起:

^{pr2}$

我尝试过使用RequestFactory()和TestCase()来编写测试用例,但是我不知道如何为这种类型的类/视图编写单元测试。。。在


Tags: django方法文档视图应用程序authenticationrequestmsg
2条回答

你可以尝试用this这样的东西来嘲笑你所需要的东西。在

您可以使用Django中的the test client。它很容易使用。在

Django文档中的示例:

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

相关问题 更多 >