2013-05-31 106 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'})