Python: 使用 md5 校验和测试响应流

Python: test response stream with md5 checksum

我刚刚开始使用 Python,我想通过对本质上是二进制文件流的响应执行 md5sum 来测试我的应用程序的恢复。

test_file.py

import main
import unittest
import hashlib

class MainTest(unittest.TestCase):

  def setUp(self):
    self.app = main.app.test_client()
...
  # This test checks if the app retuns our new firmware correctly
  def test_get_firmware_esp_new(self):
    rv = self.app.get('/firmware',
              environ_base={'HTTP_USER_AGENT': 'test-blabla'})
    print rv.response.__dict__
    self.assertEqual(hashlib.md5(rv.response).hexdigest(), 'bf8ad256d69fa98b9facca6fb43cb234')

我得到的错误是这样的:

  File "test_file.py", line 24, in test_get_firmware_esp_new
    self.assertEqual(hashlib.md5(rv.response).hexdigest(), 'bf8ad256d69fa98b9facca6fb43cb234')
TypeError: must be convertible to a buffer, not ClosingIterator

在 main.py 中,我有一行代码执行如下操作:

return get_stream_fw(FWupdate)

streamfw.py

from flask import Response, stream_with_context
import requests

def get_stream_fw(name):
  url = 'https://media.giphy.com/media/9Sxp3YOKKFEBi/giphy.gif'
  req = requests.get(url, stream = True)
  return Response(stream_with_context(req.iter_content(chunk_size=1024)), content_type = req.headers["content-type"])

对实际上是不超过 1MB 数据流的响应进行哈希处理的正确方法是什么?

通过阅读 help(hashlib) 我认为您可以像这样重复您的回复:

hs = hashlib.md5()
...
for i in rv.response:
  hs.update(i)

self.assertEqual(hs.hexdigest(), ...)

我最后是这样的:

hs = hashlib.md5()
hs.update(rv.data)
self.assertEqual(hs.hexdigest(), '80c9574fc2d169fe9c097239c2ed0b02')

所以我没有使用 rv.response,而是使用了 rv.data