单元测试python请求?

Naf*_*Kay 2 python unit-testing mocking 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
Run Code Online (Sandbox Code Playgroud)

我基本上希望能够测试它

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

问题是,我希望能够在不实际提出请求的情况下对此进行测试,因为它需要太长时间,而且某些操作可能具有破坏性.

我怎样才能快速轻松地模拟和测试?

小智 9

一个简单的模拟怎么样:

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'})
Run Code Online (Sandbox Code Playgroud)