0

New to using mock. on python 2.7.13.

i'm building a wrapper around this library
https://github.com/sendgrid/sendgrid-python/blob/master/sendgrid/sendgrid.py

which in turn consumes this library for any REST calls
https://github.com/sendgrid/python-http-client/blob/master/python_http_client/client.py

My test code looks like

class TestSendgridUtils(unittest.TestCase):
    def setUp(self):
        self.sgsu = SubUser(api_key=RANDOM_API_KEY, hippo_user=RANDOM_USER_OBJ)

    @patch('sendgrid.SendGridAPIClient')
    @patch('python_http_client.Client')
    def test_create(self, sgc_mock, http_client_mock):
        self.sgsu.create()
        expected_data = {
            'email' : self.sgsu.sg_username
        }
        print http_client_mock.call_list()
        sgc_mock.client.assert_called_with(request_body=expected_data)

I'm basically trying to mock the underlying library that makes the HTTP calls. My tests are just to ensure that i'm passing the right parameters to the sendgrid module.

Right now if i run the tests, HTTP requests are still being made which means i'm not successfully mocking the intended libraries.

Reading the mock documentation I understand that patch only works where i instantiate the underlying class. But this would have to be in setUp() which would mean my mocks wouldn't be available in my test cases?

As a result I can't figure out what is the best practice around how I use mock in this instance. I also can't figure out if i can just mock the 'sendgrid.SendGridAPIClient' or if i need to mock 'python_http_client.Client'

w--
  • 6,427
  • 12
  • 54
  • 92

1 Answers1

0

You should patch objects in the module where you're using them (e.g. in app.py), not where they are defined.
So your calls to patch should look like this:

@patch('app.sendgrid.SendGridAPIClient')

not:

@patch('sendgrid.SendGridAPIClient')

Also your order of mocks is mismatched:

@patch('sendgrid.SendGridAPIClient')
@patch('python_http_client.Client')
def test_create(self, sgc_mock, http_client_mock):

You have to either switch calls to patch or switch method arguments, because now @patch('sendgrid.SendGridAPIClient') corresponds to http_client_mock and @patch('python_http_client.Client') to sgc_mock.

kchomski
  • 2,872
  • 20
  • 31