Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 688
Naftuli Kay Avatar asked Dec 20 '22 04:12

Naftuli Kay


1 Answers

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'})
like image 107
neko_ua Avatar answered Dec 28 '22 07:12

neko_ua