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?
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.