2

I'm creating a web API in Python which communicates with some other web API's (Facebook, twitter, etc) en a other web API which is programmed at the same time as my API.

Since I like to use test driven development, I wonder how I can apply TDD to my web API. I know about mocking but how can I mock other API's and how can I mock calls to my API.

Update 1: To specify my question. Is it possible to create a web API with TDD under the conditions specified above. If yes, is there a library I can use in Python to do so.

  • Welcome to Stack Overflow! I'm sorry, but I think your question is too vague and overly broad to be answered here on SO; see the [FAQ#dontask]. If you have more concrete problems (preferably involving some code), feel free to ask those! – Martijn Pieters Jun 01 '13 at 14:44

1 Answers1

4

Since your question is rather broad, I'll just refer you:

Here's a simple example of using mock to mock python-twitter's GetSearch method:

  • test_module.py

    import twitter
    
    
    def get_tweets(hashtag):
        api = twitter.Api(consumer_key='consumer_key',
                          consumer_secret='consumer_secret',
                          access_token_key='access_token',
                          access_token_secret='access_token_secret')
        api.VerifyCredentials()
        results = api.GetSearch(hashtag)
        return results
    
  • test_my_module.py

    from unittest import TestCase
    from mock import patch
    import twitter
    from my_module import get_tweets
    
    
    class MyTestCase(TestCase):
        def test_ok(self):
            with patch.object(twitter.Api, 'GetSearch') as search_method:
                search_method.return_value = [{'tweet1', 'tweet2'}]
    
                self.assertEqual(get_tweets('blabla'), [{'tweet1', 'tweet2'}])
    

You probably should mock the whole Api object in your unittests in order to still call them unit tests. Hope that helps.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195