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

标签 python unit-testing asynchronous file-upload tornado

我想使用 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()

关于python - 如何使用 Tornado 单元测试来测试 "uploading a file"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28510730/

相关文章:

c# - MSTest:没有运行测试,因为没有加载测试或禁用了选定的测试

c# - 如何使用 Moq 模拟 Web 服务调用?

iphone - NSURLConnection 异步间歇性地返回 null

.net - 如何在 .net 内存转储中列出正在运行的任务

mysql - 如何在node.js中使用mysql创建异步函数

python - 在 Python3 中绘制具有节点和边的网络

python - 这样的进口合法还是不推荐?

python - 如何将关系从 M2O 倒推到 O2O?

python - Python 中的 multiprocessing.dummy 未使用 100% cpu

python - 如何在 python 中对工厂进行单元测试?