使用unittest测试python twitter函数

时间:2015-03-20 06:00:00

标签: python

我编写的以下代码用于测试我的函数,但它失败了,因为我需要在函数中包含一些东西。我需要包含哪些内容?

# Importing libraries that are required
import unittest
from http_twitter import get_keyword_tweets
from http_twitter import get_geocode_tweets
from http_twitter import get_keyword_geo_tweets


# Testing the below function whether it is working correct or not.
class Testtwitter(unittest.TestCase):

def test_keyword_tweets(self):
    """
    testing that i am getting correct or not
    """
    res = get_keyword_tweets("CWC15", Count=10)
    self.assertIn("#CWC15", res)

def test_location_tweets(self):
    """
    testing that i am getting location wise tweets or not
    """
    res = get_geocode_tweets("37.774929,-122.419416,1mi", Count=3)
    self.assertIn("#California", res)
 def test_keyword_location_tweets(self):
    """
    testing that i am getting the combination of tweets or not
    """
    res = get_keyword_geo_tweets(keyword="INDvsBAN",
                                 location="19.075984,72.877656,1mi",
                                 Count=3)
    self.assertIn("Rohit", res)

 if __name__ == '__main__':
    unittest.main()

当我运行上面的代码“Python filename.py”

时,这就是我得到的结果
 FAIL: test_keyword_tweets (__main__.Testtwitter)
 ----------------------------------------------------------------------
 Traceback (most recent call last):
 File "http_twitter_test.py", line 16, in test_keyword_tweets
 self.assertIn("#CWC15", res)
 AssertionError: '#CWC15' not found in [u'578797293337378816RT   @MajidHumayun: Last chance for #Afridi to ................so on

请帮我这个

1 个答案:

答案 0 :(得分:0)

AssertionError表示您的测试失败,这可能意味着字符串"#CWC15"在res中不存在

使用类似:

self.assertIn("#CWC15", res, 'CWC15 not present')

代替:

self.assertIn("#CWC15", res)

你会有更好的消息错误。

如果您在res中发送了多条推文,例如:[' tweet1内容',' tweet2内容']等等,您想要测试内部是否每条推文res包含"#CWC15'然后你可以做这样的事情

for j in res:
   self.assertEqual('#CWC15' in j, True, '#CWC15 not found')

如果您的资源中只有一条推文,或者您只想测试第一条推文:

self.assertEqual('#CWC15' in res[0], True, '#CWC15 not found')

您可以将此方法应用于test_location_tweets