我有一个函数foo,它是这样的:
class SomeClass(object):
def foo(self, url):
try:
r = requests.get(url)
buffer = StringIO.StringIO(r.content)
except Exception as e:
pass
我试图用Python模拟库测试它,做这样的事情:
class FooTest(unittest.TestCase):
def test_foo(self):
obj = SomeClass()
with patch('requests.get', MagicMock()):
with patch('StringIO.StringIO', some_fake_method):
obj.foo()
然而,这样做不会修补任何一个,我会得到适当的response
和StringIO
个对象。如果我从补丁中省略StringIO
,我会按预期获得MagicMock
个对象(而不是response
个对象)。我该如何正常工作?