gpt4 book ai didi

Python 模拟 requests.get 内容和 iter_lines()

转载 作者:行者123 更新时间:2023-12-01 04:33:02 25 4
gpt4 key购买 nike

我正在尝试为内部使用它的一个对象模拟流式 requests.get 函数。

我特别需要测试以下方法:

class MyObject(object)
def __iter__(self):
payload = {"op": "OPEN"}
response = requests.get("http://" + self.parsed_uri.uri_path, params=payload, stream=True)
return response.iter_lines()

def read(self, size=None):
if not size or size < 0:
payload = {"op": "OPEN", "offset": self.offset}
self.offset = 0
else:
payload = {"op": "OPEN", "offset": self.offset, "length": size}
self.offset = self.offset + size
response = requests.get("http://" + self.parsed_uri.uri_path, params=payload, stream=True)
return response.content

我需要 requests.get 返回类似“abc\n123”的内容

然后我的测试方法应该如下所示:

@mock.patch('requests.get', mock.Mock(side_effect=mocked_requests_get))
def test_iter(self, mock_get):
object = MyObject(ParseUri("http://host/path"))
self.assertEqual(object.next(), "abc")
self.assertEqual(object.next(), "123")

@mock.patch('requests.get', mock.Mock(side_effect=mocked_requests_get))
def test_read(self, mock_get):
object = MyObject(ParseUri("http://host/path"))
self.assertEqual(object.read, "abc\n123")

我正在尝试实现mocked_requests_get,但不幸的是我无法使其工作。可以这样使用模拟库吗? mocked_requests_get 应该是什么样子?

最佳答案

UPD。如果没有完整的示例,无法说出您的代码到底有什么问题。我如何使用 responses 模块解决这个问题:

import requests
import unittest
import responses


class Foo(object):
def __init__(self, uri):
self.uri = uri

def __iter__(self):
payload = {"op": "OPEN"}
response = requests.get("http://" + self.uri, params=payload,
stream=True)
return response.iter_lines()


class TestFoo(unittest.TestCase):
@responses.activate
def test_iter_lines(self):
responses.add(responses.GET, "http://local.host/", body='abc\n123')
r = iter(Foo("local.host"))
self.assertEqual(r.next(), "abc")
self.assertEqual(r.next(), "123")

if __name__ == '__main__':
unittest.main()

附注也许您想在调用此函数之前返回迭代器?

self.assertEqual(object.next(), "123")

关于Python 模拟 requests.get 内容和 iter_lines(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32113298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com