Skip to main content
 首页 » 编程设计

python之如何使用 Tornado 单元测试来测试 "uploading a file"

2024年10月25日8think

我想使用 tornado.testing.AsyncHTTPTestCase 测试我的网络服务(基于 Tornado 构建)。它说here对 AsyncHttpClients 使用 POST 应该如下所示。

from tornado.testing import AsyncHTTPTestCase 
from urllib import urlencode 
 
class ApplicationTestCase(AsyncHTTPTestCase): 
  def get_app(self): 
    return app.Application() 
 
  def test_file_uploading(self): 
    url = '/' 
    filepath = 'uploading_file.zip' # Binary file 
    data = ??????? # Read from "filepath" and put the generated something into "data" 
    self.http_client.fetch(self.get_url(url), 
                           self.stop, 
                           method="POST", 
                           data=urlencode(data)) 
    response = self.wait() 
    self.assertEqual(response.code, 302) # Do assertion 
 
if __name__ == '__main__': 
  unittest.main() 

问题是我不知道在 ???????? 写什么。 Tornado 中是否内置了任何实用函数,还是使用像 Requests 这样的替代库更好? ?

附言 ...实际上,我尝试过使用 Requests,但我的测试停止工作了,因为可能我没有做好异步任务处理

  def test_file_uploading(self): 
    url = '/' 
    filepath = 'uploading_file.zip' # Binary file 
    files = {'file':open(filepath,'rb')} 
    r = requests.post(self.get_url(url),files=files) # Freezes here 
    self.assertEqual(response.code, 302) # Do assertion 

请您参考如下方法:

您需要构造一个multipart/form-data 请求体。这在 the HTML spec 中正式定义. Tornado 目前没有任何用于生成多部分主体的辅助函数。但是,您可以使用 requests_toolbelt 中的 MultipartEncoder 类包裹。只需使用 to_string() 方法,而不是将编码器对象直接传递给 fetch()。