用测试驱动开发工具编写web应用程序接口

2024-04-23 22:59:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python创建一个web API,它与其他web API(Facebook、twitter等)在与API同时编程的另一个web API中进行通信。在

由于我喜欢使用测试驱动开发,我想知道如何将TDD应用于我的webapi。我知道mocking,但是如何模仿其他API,如何模拟对API的调用。在

更新1:指定我的问题。在上面指定的条件下,是否可以使用TDD创建一个webapi。如果有,我可以在Python中使用一个库来完成这个任务吗。在


Tags: apiwebfacebook编程twitter条件webapimocking
1条回答
网友
1楼 · 发布于 2024-04-23 22:59:30

既然你的问题很宽泛,我就推荐你:

下面是一个使用mock来模拟python-twitterGetSearch方法的简单示例:

  • 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'}])
    

您可能应该在unittests中模拟整个Api对象,以便仍然调用它们unit tests。 希望有帮助。在

相关问题 更多 >