python模拟请求和响应
我是一个初学者在python中使用模拟并尝试使用http://www.voidspace.org.uk/python/mock 。 请告诉我的基本要求,让我在以下情况下工作。 我正在使用pythons请求模块。
在我的views.py,我有一个函数,使每次requests.get()调用各种不同的响应
def myview(request): res1 = requests.get('aurl') res2 = request.get('burl') res3 = request.get('curl')
在我的testingclass,我想要做这样的事情,但不能找出确切的方法调用
步骤1:
//Mock the requests module //when mockedRequests.get('aurl') is called then return 'a response' //when mockedRequests.get('burl') is called then return 'b response' //when mockedRequests.get('curl') is called then return 'c response'
第2步:
打电话给我的观点
第3步:
validation响应包含“一个响应”,“b响应”,“c响应”
请帮我完成第1步。
这是你如何做到的(你可以直接运行这个文件):
import requests import unittest from unittest import mock # This is the class we want to test class MyGreatClass: def fetch_json(self, url): response = requests.get(url) return response.json() # This method will be used by the mock to replace requests.get def mocked_requests_get(*args, **kwargs): class MockResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code def json(self): return self.json_data if args[0] == 'http://someurl.com/test.json': return MockResponse({"key1": "value1"}, 200) elif args[0] == 'http://someotherurl.com/anothertest.json': return MockResponse({"key2": "value2"}, 200) return MockResponse(None, 404) # Our test case class class MyGreatClassTestCase(unittest.TestCase): # We patch 'requests.get' with our own method. The mock object is passed in to our test case method. @mock.patch('requests.get', side_effect=mocked_requests_get) def test_fetch(self, mock_get): # Assert requests.get calls mgc = MyGreatClass() json_data = mgc.fetch_json('http://someurl.com/test.json') self.assertEqual(json_data, {"key1": "value1"}) json_data = mgc.fetch_json('http://someotherurl.com/anothertest.json') self.assertEqual(json_data, {"key2": "value2"}) json_data = mgc.fetch_json('http://nonexistenturl.com/cantfindme.json') self.assertIsNone(json_data) # We can even assert that our mocked method was called with the right parameters self.assertIn(mock.call('http://someurl.com/test.json'), mock_get.call_args_list) self.assertIn(mock.call('http://someotherurl.com/anothertest.json'), mock_get.call_args_list) self.assertEqual(len(mock_get.call_args_list), 3) if __name__ == '__main__': unittest.main()
重要提示:如果你的MyGreatClass
类存在于不同的包中,比如说my.great.package
,那么你必须嘲笑my.great.package.requests.get
而不是仅仅是'request.get'。 在这种情况下,你的testing用例如下所示:
import unittest from unittest import mock from my.great.package import MyGreatClass # This method will be used by the mock to replace requests.get def mocked_requests_get(*args, **kwargs): # Same as above class MyGreatClassTestCase(unittest.TestCase): # Now we must patch 'my.great.package.requests.get' @mock.patch('my.great.package.requests.get', side_effect=mocked_requests_get) def test_fetch(self, mock_get): # Same as above if __name__ == '__main__': unittest.main()
请享用!
这是什么对我有用:
import mock @mock.patch('requests.get', mock.Mock(side_effect = lambda k:{'aurl': 'a response', 'burl' : 'b response'}.get(k, 'unhandled request %s'%k)))
尝试这个:
https://github.com/dropbox/responses
提供了相当不错的便利,可以设置所有的嘲弄自己
还有这个:
https://github.com/gabrielfalcao/HTTPretty
它不是特定的requests
库,在某些方面更强大,虽然我发现它不能很好地检查它拦截的请求,哪个responses
很容易
这个: https : //github.com/patrys/httmock
我使用了request-mock来为单独的模块编写testing:
# module.py import requests class A(): def get_response(self, url): response = requests.get(url) return response.text
而testing:
# tests.py import requests_mock import unittest from module import A class TestAPI(unittest.TestCase): @requests_mock.mock() def test_get_response(self, m): a = A() m.get('http://aurl.com', text='a response') self.assertEqual(a.get_response('http://aurl.com'), 'a response') m.get('http://burl.com', text='b response') self.assertEqual(a.get_response('http://burl.com'), 'b response') m.get('http://curl.com', text='c response') self.assertEqual(a.get_response('http://curl.com'), 'c response') if __name__ == '__main__': unittest.main()
这是你如何模拟requests.post,将其更改为您的http方法
@patch.object(requests, 'post') def your_test_method(self, mockpost): mockresponse = Mock() mockpost.return_value = mockresponse mockresponse.text = 'mock return' #call your target method now
如果你想嘲笑假响应,另一种方法是简单地实例化一个HttpResponse类的实例,就像这样:
from django.http.response import HttpResponseBase self.fake_response = HttpResponseBase()
- 集成testing中需要的数据库数据; 通过API调用创build或使用导入的数据?
- 在JavaScript中嘲笑window.location.href
- 用Mockito嘲笑静态方法
- 我如何模拟一个在Angularjs Jasmineunit testing中返回承诺的服务?
- ASP.NET WebApiunit testing与Request.CreateResponse
- 我如何validationRSpec中的退出和中止?
- 如何在AngularJSunit testing中模拟$ window.location.replace?
- 模拟PHPUnit – 使用不同参数的相同方法的多重configuration
- unit testing数据库驱动应用程序的最佳策略是什么?