Andres
Andres

Reputation: 4501

Mock requests in Django

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?

Upvotes: 1

Views: 2538

Answers (3)

Andres
Andres

Reputation: 4501

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

Upvotes: 0

Adeel
Adeel

Reputation: 781

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.

Upvotes: 1

Zorba
Zorba

Reputation: 566

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

Upvotes: 1

Related Questions