我正在尝试为我的web应用程序创建一些自动化测试,它使用Django和DRF作为后端来处理来自前端的请求。在
我很难找到一种方法来使用客户端发送一些表单数据到API,我得到一个错误,即没有字段被发布。在
下面是我使用APITestCase类的尝试:
from django.test import TestCase, TransactionTestCase
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse
from rest_framework.test import APIRequestFactory, APITestCase, APIClient, RequestsClient, APITransactionTestCase
import json, os, re
import requests as python_requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
....
....
def testInvoiceUploadAndRead(self):
#test non-logged in user
response=self.client.get(reverse("invoiceupload"))
self.assertEqual(response.status_code, 403)
user=Account.objects.get(username="test_user")
self.client.login(username=user.username, password="rebar123")
response=self.client.get(reverse("invoiceupload"))
self.assertEqual(response.status_code, 405)
#create the invoice
full_filename=os.path.join("media", "testfiles", "sample_file.png")
invoice = MultipartEncoder(
fields={
"invoicefile":("test_file.png", open(full_filename, "rb")),
"debtor":"5560360793",
"amount":"55000",
"serial":"1234567890",
"dateout":"20180728",
"expiration":"20180808",
}
)
response=self.client.post(reverse("invoiceupload"), invoice, content_type="multipart/form-data")
print(response.data["message"])
self.assertEqual(response.status_code, 201)
我得到了一个错误:
^{pr2}$没有检测到的内容发送,有没有关于如何修复它的想法,或者更好的方法来完成同样的事情?在
通过更仔细地阅读文档解决了这个问题,如果没有将内容类型传递给post方法,它会自动设置多部分/表单数据,我的观点接受了这一点。在
更改:
相关问题 更多 >
编程相关推荐