【问题标题】:Mocking modules from boto in python在 python 中从 boto 模拟模块
【发布时间】:2014-03-13 02:36:54
【问题描述】:

我正在尝试为如下所示的类编写单元测试。

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 中修补和模拟的新手,所以我不知道我该怎么做。有人可以让我知道是否有办法做到这一点?

非常感谢!

【问题讨论】:

    标签: python unit-testing mocking patch boto


    【解决方案1】:

    这个想法是修补 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
    

    另见:

    希望对您有所帮助。

    【讨论】:

    • 谢谢,亚历克西!正是我想要的。
    • The moto project 您可能也会感兴趣。
    猜你喜欢
    • 2021-08-31
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 2015-08-12
    相关资源
    最近更新 更多