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

时间:2015-08-20 08:31:02

标签: python unit-testing mocking python-requests

我正在尝试为内部使用它的一个对象模拟流式化的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给我回复一些类似&#34; abc \ n123&#34;

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

@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应该怎么样?

1 个答案:

答案 0 :(得分:1)

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()

P.S。也许你想在调用之前返回迭代器?

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