python模拟第三方模块 [英] python mocking third party modules

查看:126
本文介绍了python模拟第三方模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im试图测试一些处理推文的类.我使用sixohsix twitter处理Twitter API. 我有一个类充当Twitter类的基础,我的想法是模拟实际的sixohsix类,以通过随机生成新的tweet或从数据库中检索它们来模拟tweet的到来.

im trying to test some classes that process tweets. Im using sixohsix twitter to deal with Twitter API. I have a class that acts as a facade for the Twitter classes, and my idea was to mock the actual sixohsix classes to simulate the arrival of tweets, by randomly generate new tweets or retrieving them from a database.

我的门面看起来像:

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类? 我已经尝试过使用Mock:

So if in an unittest i want to test some module that does something with the tweets, how would i mock the TwitterStream class ? I've tried using Mock:

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

This is not working, twitter api is still been called. I would have expected that sincen i didnt add any code to the mock class i would have gotten an error or something, but sixohsix twitter classes where called instead.

推荐答案

您需要修补本地对象;您的模块引用了TwitterStream对象,该修补程序是:

You need to patch the local object; your module has a reference to the TwitterStream object, patch that:

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

请参见在何处修补文档.

这篇关于python模拟第三方模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆