gpt4 book ai didi

python 模拟第三方模块

转载 作者:行者123 更新时间:2023-11-30 23:25:10 24 4
gpt4 key购买 nike

我正在尝试测试一些处理推文的类。我使用 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 仍然被调用。我本以为,由于我没有向模拟类添加任何代码,我会收到错误或其他错误,但改为调用 Sixohsix twitter 类。

最佳答案

您需要修补本地对象;您的模块有一个对 TwitterStream 对象的引用,请修补:

@patch('yourmodule.TwitterStream', TwitterStreamProxy())

查看模拟 Where to Patch文档。

关于python 模拟第三方模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23112199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com