[Answered ]-Mock requests in Django

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

1👍

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

👤Zorba

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.

👤Adeel

Leave a comment