2014-03-13 148 views
2

我想为下面的类写一个单元测试。从蟒蛇嘲讽模块

import boto 
class ToBeTested: 
    def location(self, eb): 
     return eb.create_storage_location() 

    def some_method(self): 
     eb = boto.beanstalk.connect_to_region(region, access_key, secret_key) 
     location(eb) 

有没有办法来嘲笑boto.beanstalk.connect_to_region返回值和最终嘲讽create_storage_location?我是新来的补丁和蟒蛇模拟,所以我不知道我怎么能做到这一点。有人能让我知道是否有办法做到这一点?

非常感谢!

回答

4

的想法是修补connect_to_region()以便它返回一个Mock对象,那么你可以定义模拟,比如你想要的任何方法:

import unittest 

from mock import patch, Mock 


class MyTestCase(unittest.TestCase): 
    @patch('boto.beanstalk.connect_to_region') 
    def test_boto(self, connect_mock): 
     eb = Mock() 
     eb.create_storage_location.return_value = 'test' 
     connect_mock.return_value = eb 

     to_be_tested = ToBeTested() 
     # assertions 

参见:

希望有帮助。

+0

谢谢,Alecxe!正是我在找什么。 – test123

+3

[moto项目](https://github.com/spulec/moto)也可能对你感兴趣。 – garnaat