我试图用Pythons mock package来模拟Pythonrequests
模块。在下面的场景中,让我工作的基本要求是什么?
在我的views.py中,我有一个函数,它每次都以不同的响应发出各种各样的请求
def myview(request):
res1 = requests.get('aurl')
res2 = request.get('burl')
res3 = request.get('curl')
在我的测试类中,我想做一些类似的事情,但无法计算出确切的方法调用
步骤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:
验证响应是否包含“a响应”、“b响应”、“c响应”
如何完成步骤1(模拟请求模块)?
您可以这样做(可以按原样运行此文件):
重要提示:如果您的
MyGreatClass
类位于另一个包中,比如my.great.package
,则必须模拟my.great.package.requests.get
,而不仅仅是“request.get”。在这种情况下,您的测试用例将如下所示:享受吧!
尝试使用responses library:
提供了一个很好的方便,比设置所有的嘲笑自己
还有HTTPretty:
它并不特定于
requests
库,在某些方面更强大,尽管我发现它不适合检查它截获的请求,而responses
很容易做到还有httmock。
以下是对我有用的:
相关问题 更多 >
编程相关推荐