如何修补存储在变量中的函数?

时间:2013-05-12 03:00:44

标签: python python-2.7 mocking python-mock python-unittest

如何使以下测试起作用?

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)

当我执行测试时,我遇到ConnectionError例外,因为foo正在执行真实的requests.post

1 个答案:

答案 0 :(得分:1)

尝试@patch("mymodule.requests.post"),请参阅where to patch