Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #42553 > unrolled thread

Re: python mock Requests and the response

Started byJean-Michel Pichavant <jeanmichel@sequans.com>
First post2013-04-02 11:40 +0200
Last post2013-04-02 11:40 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python


Contents

  Re: python mock Requests and the response Jean-Michel Pichavant <jeanmichel@sequans.com> - 2013-04-02 11:40 +0200

#42553 — Re: python mock Requests and the response

FromJean-Michel Pichavant <jeanmichel@sequans.com>
Date2013-04-02 11:40 +0200
SubjectRe: python mock Requests and the response
Message-ID<mailman.32.1364895662.17481.python-list@python.org>
----- Original Message -----
> I am a beginner to using mock in python and trying to use
> http://www.voidspace.org.uk/python/mock.
> 
> Please tell me the basic calls to get me working in below scenario. I
> am using python's Requests module
> (http://docs.python-requests.org/en/latest/) .
> 
> In my views.py, I have a function that makes variety of
> requests.get() calls with different response each time
> 
>     def myview(request):
>       res1 = requests.get('aurl')
>       res2 = request.get('burl')
>       res3 = request.get('curl')
> 
> In my test class I want to do something like this but cannot figure
> out exact method calls
> 
> Step 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'
> 
> Step 2:
> 
> Call my view
> 
> Step 3:
> 
> verify response contains 'a response', 'b response' , 'c response'
> 
> Please help me to complete Step 1.
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

Hi,

Why are you passing the requests (with typo ?) module to the function ? anyway, the code could look like this:

!! untested code, I don't have the requests module installed !!

import requests
import mock

def myView():
	res1 = requests.get('aurl')
	res2 = requests.get('burl')
	res3 = requests.get('curl')

@mock.patch('requests.get', mock.Mock(side_effect = lambda k:{'aurl': 'a response', 'burl' : 'b response'}.get(k, 'unhandled request %s'%k)))
def testMyView(mockedGet):
	# you can further customize the mock object here
	mockedGet.whatever()
	myView()

testMyView()


side_effect is the mock way of returning multiple values.

Hope it helps,

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web