0

How can I make the following test to work?

mymodule.py

import requests

http_methods = {
    "GET": requests.get,
    "POST": requests.post,
    "PUT": requests.put,
    "DELETE": requests.delete
}

def foo(method):
    r = http_methods[method]("http://some.thing")
    return r.status_code

tests.py

import unittest
from mock import patch
import mymodule

class MyTestCase(unittest.TestCase):
    ...
    @patch("requests.post")
    def test_foo(self, post):
        post.return_value = 200
        self.assertEquals(mymodule.foo("POST"), 200)

When I execute the test I got a ConnectionError exception because foo is executing the real requests.post.

borges
  • 3,627
  • 5
  • 29
  • 44
  • What are you trying to do? *How can I make the following code to work?* isn't helpful enough for me (at least) to understand.. Please state what you are trying to achieve.. – pradyunsg May 12 '13 at 03:02
  • @Schoolboy the real code is bigger and has a "meaning". I removed all other parts of code that has no direct relation with the problem. My problem is: given a dictionary with several functions, how can I patch them? – borges May 12 '13 at 03:17
  • @Schoolboy `patch` decorator from python [mock library](http://www.voidspace.org.uk/python/mock/). – borges May 12 '13 at 03:27

1 Answers1

1

Try @patch("mymodule.requests.post"), see where to patch

DazWorrall
  • 13,682
  • 5
  • 43
  • 37