[英]Sanic unit testing for file uploads
下面是一段代碼,總結了我如何將文件發布到 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 創建的請求。 任何見解將不勝感激。
項目維護者在這里。 你看到我們在Sanic 單元測試中如何處理這個了嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.