0

I'm building a (facebook connected) web server using Flask. Here's an example route

@app.route('/login', methods=['GET'])
def login():
    graph = facebook.GraphAPI(request.args.get('access_token'))
    profile = graph.get_object('me')
    return jsonify(profile)

This works fine, but it seems bad practice to be continually hitting Facebook servers when I'm doing local dev.

What is the most effective way to re-route the facebook API to mocks or even a mock server? Internally, the facebook-sdk library uses requests to reach graph.facebook.com.

I've seen this question

python mock Requests and the response

and in particular, Dropbox's responses library, but it looks like you have to wrap each call in their decorator. It would work well for a unit testing suite, but I'm just interested in doing development against mock data and mock responses.


Update: In response to Thomas, I had been thinking about a similar solution. I tried adding:

if config_name == 'development':
    print 'monkey'
    import requests
    def mock(*args, **kwargs):
        print args, kwargs
        return {}
    requests.request = mock

But that didn't seem to change the behavior of the facebook-sdk library.

2 Answers 2

0

You could check if debug mode is on using app.config, and then (if debug mode is on), turn your requests into dummy requests. I'm not that familiar with the facebook API, so (unfortunately) I can't write out the dummy code for you.

1
  • Updated in response. Any thoughts? Aug 1, 2014 at 18:00
0

How about using the flask-testing and mock libraries:

import requests

from flask.ext.testing import TestCase
from mock import Mock

class TestLogin(TestCase):

  def setUp(self):
    requests.request = Mock()
    super(TestLogin, self).setUp()

  def test_it(self):
    resp = self.client.get('/login')
    self.assertEquals('right stuff', resp.data)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.