Naftuli Kay
Naftuli Kay

Reputation: 91850

Unit-testing python-requests?

I have a couple methods I'd like to unit test which use the Python requests library. Essentially, they're doing something like this:

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

I'd essentially like to be able to test that

  1. It's actually making the request.
  2. It's using the GET method.
  3. It's using the right parameters.
  4. etc.

The problem is that I'd like to be able to test this without actually making the request as it'll take too long and some operations are potentially destructive.

How can I mock and test this quickly and easily?

Upvotes: 7

Views: 6382

Answers (1)

neko_ua
neko_ua

Reputation: 470

How about a simple mock:

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'})

Upvotes: 13

Related Questions