init方法Python内部的模拟函数调用
我正在编写一个单元测试来确保我的类对象被正确创建,这个对象依赖于从s3获取内容。我想完全模拟调用s3的函数:init方法Python内部的模拟函数调用,python,unit-testing,mocking,init,Python,Unit Testing,Mocking,Init,我正在编写一个单元测试来确保我的类对象被正确创建,这个对象依赖于从s3获取内容。我想完全模拟调用s3的函数: class SomeClassTest(unittest.TestCase): @patch('someDir.util._call_to_s3') def test_someclass_load(self, magic_mock): magic_mock.return_value = {"host": "bogus.com"} some
class SomeClassTest(unittest.TestCase):
@patch('someDir.util._call_to_s3')
def test_someclass_load(self, magic_mock):
magic_mock.return_value = {"host": "bogus.com"}
some_class = SomeClass()
self.assertGreater(len(some_class), 0)
class SomeClass():
def __init__():
try:
content = _call_to_s3(bucket_name, file_name)
except:
rest of code ...
如何模拟另一个库文件中定义的函数_call_to_s3 使用monkeypatch时,您正在更改名称,使其指向不同的值。您没有更改值本身。关键是修补您正在测试的单元所使用的名称 每次执行“从foo导入栏”操作时,您都在创建一个新的本地名称副本。在本例中,SomeClass似乎不在someDir.util模块中。假设它在某个目录中 someDir.other_mod将执行类似于“从someDir.util导入_调用_到_s3”的操作。这将创建一个新名称someDir.other\u mod.\u call\u to\u s3。这是SomeClass使用的名称,因此需要对其进行修补 e、 g.@patch('someDir.other.\u mod.\u call\u to\u s3') 无法修补指向特定值的每个名称