ツイートを処理するいくつかのクラスをテストしようとしています。私は、sixohsix twitter を使用して Twitter API を処理しています。Twitter クラスのファサードとして機能するクラスがあり、実際の sixohsix クラスをモックして、新しいツイートをランダムに生成するか、データベースから取得することで、ツイートの到着をシミュレートすることを考えました。
私のファサードは次のようになります。
from twitter import TwitterStream
class TwitterFacade(object):
def __init__(self, dev='soom'):
self._auth = OAuth(dev_keys["ACCESS_TOKEN"], dev_keys["ACCESS_SECRET"], dev_keys["CONSUMER_KEY"], dev_keys["CONSUMER_SECRET"])
def tweets(self, callback=None, users=[], terms=[], locations=[], count=5):
t = TwitterStream(auth=self._auth)
args = {}
if users: args['follow'] = ",".join(users)
if terms: args['track'] = ",".join(terms)
if locations: args['locations'] = ",".join(str(l) for l in locations)
# this controls the general loop, it re-enters if there was an exception,
# otherwise the for loop should take care of looping trough the tweets
cant = count
while cant > 0:
try:
iterator = t.statuses.filter(**args)
for twit in iterator:
if twit.get('text'):
callback(twit)
cant -= 1
if cant == 0:
iterator.close()
break
except Exception as e:
print e
#some error handling code
ユニットテストで、つぶやきを処理するモジュールをテストしたい場合、TwitterStream クラスをどのようにモックしますか? 私はモックを使ってみました:
from mock import patch
from twitter_facade import TwitterFacade
class TwitterStreamProxy(object):
def __init__(self):
pass
#some code for dealing with statuses.filter(..)
@patch('twitter.TwitterStream', TwitterStreamProxy())
def test_filter_on_tweets():
facade = TwitterFacade()
facade.tweets(somemethod, [], ['term1', 'term2'], [], count=50)
def somemethod(tweet):
#some logic in here
これは機能していません。Twitter API がまだ呼び出されています。モッククラスにコードを追加しなかったので、エラーか何かが発生したと予想していましたが、代わりに6つのtwitterクラスが呼び出されました。