【发布时间】:2020-01-06 04:10:38
【问题描述】:
以下是一段代码,总结了我如何将文件发布到 Sanic 应用程序的端点:
from sanic import Sanic, response
class Server(object):
def __init__(self, test=False):
self.app = Sanic()
self.app.add_route(self.upload, '/upload', methods=['POST'])
async def upload(self,request):
# Obtain some data from the request to compare md5
md5 = request.form.get('md5')
# Check for file
if not request.files.get('file'):
return {"message":"No file selected!","success":False}
test_file = request.files.get('file')
我如何编写一个单元测试,它能够将文件、md5 等作为请求对象的一部分传递?以下是我尝试过的,但没有运气:
from server import Server
import unittest
class TestUpload(unittest.TestCase):
def test_upload(self):
app = Server(test=True).app
upload_payload = {'upload': open('upload_file.yaml', 'rb'), 'digest': '56d5b275ab20831b22f835cc7bf9905a'}
headers = {"content-type": "multipart/form-data; boundary=------sanic"}
files = {'file': ('upload', open('upload_file.yaml', 'rb'), 'text/yaml'), 'Content-Type': 'multipart/form-data', 'Content-Disposition': 'form-data; name="upload"; filename="upload_file.yaml"'}
request, response = app.test_client.post("/upload", data=upload_payload, headers=headers, files=files)
正如您在上面看到的,我尝试了多种方法来查看使用 SanicTestClient 创建的请求对象是否将包含文件作为request.files 和自定义request.form.md5 的一部分,但这些属性从未填充根据 SanicTestClient 创建的请求。任何见解将不胜感激。
【问题讨论】:
标签: python unit-testing web-services python-unittest sanic