Python MagicMock returns HTTP 响应的字节值
Python MagicMock returns bytes value for HTTP response
我想用 MagicMock 模拟 returns 图片(字节)的 HTTP 请求。所以,我这里有简单的功能:
import io
import urllib.request
def blah():
try:
req = urllib.request.Request(url='<image url/base64>', data=None, method='GET')
response = urllib.request.urlopen(req)
except Exception as e:
return str(e)
body = io.BytesIO(response.read()) # error here
return 'something'
我想像这样测试它:
import unittest
from blah import blah
from unittest.mock import patch, MagicMock
class TestBlah(unittest.TestCase):
def test_blah(self):
with patch('urllib.request.urlopen') as mock_urlopen:
cm = MagicMock()
cm.getcode.return_value = 200
cm.read.return_value = open('./download.jpeg') # an image file
cm.__enter__.return_value = cm
mock_urlopen.return_value = cm
self.assertEqual(blah(), 'something')
当我执行我的代码时,它产生错误:
TypeError: a bytes-like object is required, not '_io.TextIOWrapper'
谁能帮帮我?
应该是这样的,
cm.read.return_value = open('./download.jpeg', 'rb').read()
我想用 MagicMock 模拟 returns 图片(字节)的 HTTP 请求。所以,我这里有简单的功能:
import io
import urllib.request
def blah():
try:
req = urllib.request.Request(url='<image url/base64>', data=None, method='GET')
response = urllib.request.urlopen(req)
except Exception as e:
return str(e)
body = io.BytesIO(response.read()) # error here
return 'something'
我想像这样测试它:
import unittest
from blah import blah
from unittest.mock import patch, MagicMock
class TestBlah(unittest.TestCase):
def test_blah(self):
with patch('urllib.request.urlopen') as mock_urlopen:
cm = MagicMock()
cm.getcode.return_value = 200
cm.read.return_value = open('./download.jpeg') # an image file
cm.__enter__.return_value = cm
mock_urlopen.return_value = cm
self.assertEqual(blah(), 'something')
当我执行我的代码时,它产生错误:
TypeError: a bytes-like object is required, not '_io.TextIOWrapper'
谁能帮帮我?
应该是这样的,
cm.read.return_value = open('./download.jpeg', 'rb').read()