如何使用龙卷风单元测试测试"uploading a file"?



我想使用tornado.testing.AsyncHTTPTestCase测试我的web服务(基于Tornado构建)。这里说对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中有没有内置的实用程序函数,或者使用其他库(如Request)更好?

p.S.…实际上,我已经尝试过使用请求,但我的测试停止了,因为可能我在异步任务方面做得不好

  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请求体。这是在HTML规范中正式定义的。Tornado目前没有任何用于生成多部分主体的辅助函数。但是,您可以使用requests_toolbelt包中的MultipartEncoder类。只需使用to_string()方法,而不是将编码器对象直接传递给fetch()

最新更新