1

I want to mock ConnectionError for my API. I'm creating a python package for one software which if running on localhost:8080 then it will give result correctly. But if the software is not running, then I want to catch it. I'm able to write function using httpx.ConnectError to get this exception, but how can I write test for the same ?

my function is like this

def get_workspace(self, workspace: str) -> Union[WorkspaceModel, GSResponse]:
        try:
            Client = self.http_client
            responses = Client.get(f"workspaces/{workspace}")
            if responses.status_code == 200:
                return WorkspaceModel.parse_obj(responses.json())
            else :
                results = self.response_recognise(responses)
                return results
        except httpx.TimeoutException as exc:
            res = {}
            res['code'] = 504
            res['response'] = "Timeout Error"
            return GSResponse.parse_obj(res)
        except httpx.NetworkError as exc:
            res = {}
            res['code'] = 503
            res['response'] = "Geoserver unavailable"
            return GSResponse.parse_obj(res)
krishna lodha
  • 381
  • 3
  • 9

1 Answers1

0

Using pytest-httpx, you can simulate httpx raising any kind of exception thanks to httpx_mock.add_exception.

Your test case would look something like that:

import httpx
import pytest
from pytest_httpx import HTTPXMock


def test_exception_raising(httpx_mock: HTTPXMock):
    httpx_mock.add_exception(httpx.ConnectError())

    # Your code performing the http call here.
Colin B
  • 94
  • 6