我有以下代码:
def verify_pseudo_streaming(self, publishedName, path, start):
cname = self.get_cname(publishedName)
params = {'start': start}
url = 'http://{}{}'.format(cname, path)
origin_size = int(requests.head(url).headers['Content-Length'])
start_headers = requests.head(url, params=params).headers
start_size = int(start_headers['Content-Length'])
msg = "Start size is not lower than origin size"
assert start_size < origin_size, msg
在我的测试中,我在单元测试中模拟了requests.head
,如何在没有真正运行的情况下运行headers
时第一次和第二次获得requests.head
的值?< / p>
我终于完成了下面的工作......
class MockHeaders(object):
def __init__(self):
pass
def streaming_headers(self, *args, **kwargs):
start = kwargs.get('params', {})
self.headers['Content-Length'] = start.get('start', 10)
stuff = Mock()
stuff.headers = self.headers
return stuff
<snip> ... </snip>
@patch("FrontEnd.requests.head")
@patch("FrontEnd.FrontEnd.get_cname")
def test_verify_pseudo_streaming(self, mock_get_cname,mock_head):
mock_get_cname.return_value = 'hulahoop'
mock_header = MockHeaders()
mock_head.side_effect = mock_header.streaming_headers
mock_head.return_value = mock_header
try:
self.fe.verify_pseudo_streaming('publishedName', 'path', 5)
except AssertionError:
self.fail("Unexpected Assertion Error")
我只是要保持开放,看看其他人是否有其他更优雅的想法。
答案 0 :(得分:0)
你可以模拟\ monkeypatch只有这个方法
requests.sessions.Session.send
这是请求用于发送请求的内容,因此如果您将其更改为什么都不做 它不会发送请求
def x(*args, **kwarg):
pass
requests.sessions.Session.send = x
答案 1 :(得分:0)
我会嘲笑这样的请求:
class FakeHeaders(object):
def __init__(self):
self.headers = {'Content-Length': 1}
def inc_headers():
self.headers['Content-Length'] += 1
def testVerifyPsuedoStreaming(self):
fake_header = FakeHeader()
with mock.patch.object(
request, 'head', side_effect=fake_header.inc_headers,
return_value=fake_header) as mock_head:
...