0

I have a function foo which is something like this:

class SomeClass(object):

    def foo(self, url):
        try:
            r = requests.get(url)
            buffer = StringIO.StringIO(r.content)
        except Exception as e:
            pass

I am trying to test it with Python mock library by doing something like this:

class FooTest(unittest.TestCase):

    def test_foo(self):
        obj = SomeClass()

        with patch('requests.get', MagicMock()):
            with patch('StringIO.StringIO', some_fake_method):
                obj.foo()

However, doing it this way would not patch any of them and I would instead get proper response and StringIO objects. If I omit StringIO from the patch, I get a MagicMock object as expected (instead of a response object). How do I make this work properly?

Rafay
  • 6,108
  • 11
  • 51
  • 71
  • 1
    Try to change your approach https://github.com/dropbox/responses It could be easier. – Mauro Baraldi Aug 07 '14 at 14:37
  • 1
    Your patch is for `request.get`, not `requests.get` (although that should result in a different behavior than you report, so perhaps it's a typo in the question). – chepner Aug 07 '14 at 14:48
  • @chepner yeah that was a typo. Thanks for pointing that out. – Rafay Aug 07 '14 at 14:49
  • @MohammadRafayAleem I can't reproduce the issue you're seeing. Using nested `patch` with `'requests.get'` and `StringIO.StringIO` works fine for me. Can you provide a complete set of example code that reproduces it (meaning all we'd have to do is copy/paste then run it)? – dano Aug 07 '14 at 15:29

0 Answers0