1

I have this function:

def function_to_test(..): # some stuff response = requests.post("some.url", data={'dome': 'data'}) # some stuff with response 

I want to make a test, but mocking requests.post("some.url", data={'dome': 'data'}) because I know it works. I need something like:

def my tets(): patch('requests.post', Mock(return_value={'some': 'values'})).start() # test for *function_to_test* 

Is that possible? If so, how?

Edited

I found these ways:

class MockObject(object): status_code = 200 content = {'some': 'data'} # First way patch('requests.post', Mock(return_value=MockObject())).start() # Second way import requests requests.post = Mock(return_value=MockObject()) 

Are these approaches good? which one is better? another one?

3 Answers 3

1

You can use HTTPretty(https://github.com/gabrielfalcao/HTTPretty), a library made just for that kind of mocks.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 because it looks nice but I don't want external apps now. I'll maybe use it later. Thanks
This does not answer the question. They want to patch the requests module directly, not monkey-patch the socket library (which is what HTTPretty does).
Actually, github.com/dropbox/responses was specifically made to patch requests.
1

you can use flexmock for that. see the example below

Say you have function in file ./myfunc.py

# ./myfunc.py import requests def function_to_test(..): # some stuff response = requests.post("www.google.com", data={'dome': 'data'}) return response 

Then the testcase is in ./test_myfunc.py

# ./test_myfunc.py import flexmock as flexmock import myfunc def test_myfunc(): (flexmock(myfunc.requests).should_recieve("post").with_args("www.google.com", data={"dome": "data"}).and_return({'some': 'values'})) resp = myfunc.function_to_test() assert resp["some"] == "values" 

Try this, see if this works or let me know for more enhancement/improvement.

Comments

0

After continue testing and testing I prefer to use this to mock requests. Hope it helps others.

class MockObject(object): status_code = 200 content = {'some': 'data'} patch('requests.post', Mock(return_value=MockObject())).start() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.