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

标签 python django unit-testing http-post

我正在尝试为一个类编写单元测试,该类具有用于将文档上传到基于 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/

相关文章:

python - 在 Sublime Text 2 中设置 Python IDE 时出现问题。错误 : [Error 2] The system cannot find the file specified

python - 无法使用 Django ModelForm 进行模型绑定(bind)

python - 当有选择地添加额外字段时更改模型表单的顺序?

java - PowerMock 模拟抽象类中的静态方法

javascript - 使用 Chai 进行单元测试时,未定义的 "TypeError: Cannot read property ' 地址'是什么意思?

javascript - 返回 promise 的 Jasmine 测试函数

python - 合并计算的文件内容并在输出中显示先前计算的数据

java - 程序终止时终止进程运行 `exec`

python - 使用 feedparser 检查 RSS 提要是否有新内容

python - Django:对象和模型集