在Python中模拟boto模块
我正在尝试为一个类编写单元测试,类的结构如下。
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?我对Python中的patch和mock还很陌生,所以不知道该怎么做。请问有没有人能告诉我该怎么做?
非常感谢!
1 个回答
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
另外,您可以参考:
希望这对你有帮助。