2013-05-31 35 views
2

我有几个方法我想单元测试使用Python requests库。从本质上讲,他们正在做这样的事情:单元测试python-requests?

def my_method_under_test(self): 
    r = requests.get("https://ec2.amazonaws.com/", params={'Action': 'GetConsoleOutput', 
      'InstanceId': 'i-123456'}) 
    # do other stuffs 

我基本上希望能够以测试

  1. 它实际上提出请求。
  2. 它使用GET方法。
  3. 它使用正确的参数。

的问题是,我希望能够测试这种没有实际进行,因为它会花费太长的时间,有些操作是潜在的破坏性的请求。

我该如何快速轻松地进行模拟和测试?

+1

可能重复[单元测试使用该请求库Python应用程序(http://stackoverflow.com/questions/9559963/unit-testing-a- python-app-that-uses-the-requests-library) –

+0

上次我做到了,[发生了不好的事情。](https://www.youtube.com/watch?v=5O17j94YBCg&t=20) –

+1

为什么你会代码需要测试Requests库的工作原理?这不应该是你的测试的责任,而是发生在请求的测试中。 – thisfred

回答

7

怎么样一个简单的模拟:

from mock import patch 

from mymodule import my_method_under_test 

class MyTest(TestCase): 

    def test_request_get(self): 
     with patch('requests.get') as patched_get: 
      my_method_under_test() 
      # Ensure patched get was called, called only once and with exactly these params. 
      patched_get.assert_called_once_with("https://ec2.amazonaws.com/", params={'Action': 'GetConsoleOutput', 'InstanceId': 'i-123456'})