1

I'm trying to work with a third party API and I am having problems with sending the request when using the requests or even urllib.request.

Somehow when I use http.client I am successful sending and receiving the response I need.

To make life easier for me, I created an API class below:

class API:

    def get_response_data(self, response: http.client.HTTPResponse) -> dict:
        """Get the response data."""

        response_body = response.read()
        response_data = json.loads(response_body.decode("utf-8"))

        return response_data

The way I use it is like this:

api = API()

rest_api_host = "api.app.com"
connection = http.client.HTTPSConnection(rest_api_host)
token = "my_third_party_token"
data = {
    "token":token
}
payload = json.loads(data)
headers = {
    # some headers
}
connection.request("POST", "/some/endpoint/", payload, headers)
response = connection.getresponse()
response_data = api.get_response_data(response) # I get a dictionary response 
 

This workflow works for me. Now I just want to write a test for the get_response_data method.

How do I instantiate a http.client.HTTPResponse with the desired output to be tested?

For example:

from . import API
from unittest import TestCase

class APITestCase(TestCase):
    """API test case."""

    def setUp(self) -> None:
        super().setUp()
        api = API()

    def test_get_response_data_returns_expected_response_data(self) -> None:
        """get_response_data() method returns expected response data in http.client.HTTPResponse"""
        expected_response_data = {"token": "a_secret_token"}
        
         # I want to do something like this
        response = http.client.HTTPResponse(expected_response_data)

        self.assertEqual(api.get_response_data(response), expected_response_data)

How can I do this?

From the http.client docs it says:

class http.client.HTTPResponse(sock, debuglevel=0, method=None, url=None)

Class whose instances are returned upon successful connection. Not instantiated directly by user.

I tried looking at socket for the sock argument in the instantiation but honestly, I don't understand it.

I tried reading the docs in

Searched the internet on "how to test http.client.HTTPResponse" but I haven't found the answer I was looking for.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • 1
    The search term you are looking for is to _mock_ the HTTPResponse, which means not sending an actual request, but getting a _mocked_ HTTPResponse instead, which behaves like the real thing, as if a request was actually sent. – Gino Mempin Nov 10 '22 at 10:49
  • 3
    Does this answer your question? [How to create a unit test for a function that uses Python's http.client library using pytest and mocks?](https://stackoverflow.com/questions/63386822/how-to-create-a-unit-test-for-a-function-that-uses-pythons-http-client-library) – Gino Mempin Nov 10 '22 at 10:54

0 Answers0