【问题标题】:How to write unit test for file upload class in django?如何在 django 中为文件上传类编写单元测试?
【发布时间】:2014-03-03 09:11:24
【问题描述】:

我正在尝试为具有 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 应用程序正在使用 forms.py 来上传文件,所以我也将该代码与此一起放置:

from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
    label='Select a file',
    help_text='max. 42 megabytes'
)

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

【问题讨论】:

    标签: python django unit-testing http-post


    【解决方案1】:

    您可以使用 Django 中的the test client。它非常易于使用。

    来自 Django 文档的示例:

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

    【讨论】:

    • 那么我认为我做错了什么......我的终端向我显示“测试标签'lib.SOPTestCase.testWithRequestFactory'不涉及测试”......顺便说一句,非常感谢你
    【解决方案2】:

    您可以尝试使用 this 之类的东西来模拟您需要的内容。

    【讨论】:

    • 我对此感到困惑,你能举个例子来说明你如何模拟这个吗?谢谢!
    猜你喜欢
    • 2015-08-31
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    相关资源
    最近更新 更多