0

I created a custom exception handler and wanted to write test cases for it.

This is my Testcase:

def test_is_exception_raised(app_client):
    exception = CustomException(InvalidSQLStatement())
    with pytest.raises(exception):
        raise exception

    try:
        raise exception
    except Exception as e:
        assert e.message
        assert e.status_code

This is the error I get:

error message

My Code looks like this: main.py

@app.exception_handler(CustomException)
async def custom_exception_handler(request: Request, exc: CustomException):
    log.error(f"{exc}")
    return JSONResponse(
        status_code=exc.status_code_number,
        content=jsonable_encoder({exc.status_code_number: exc.message}),
    )

exceptions.py

class CustomException(Exception):
    """
    All Custom Exceptions are defined in xyz\exceptions.py
    """

    def __init__(self, exception):
        if not check_if_exception_exists(exception):
            raise KeyError(f"Custom Exception: {exception.__class__.__name__} does not exist.")
        self.message = exception.message
        self.status_code_number = exception.status_code_number
daniel guo
  • 45
  • 1
  • 7
  • `with pytest.raises(CustomException):`? Since you're testing that the exception type gets raised, not that a specific instance is raised? Also be aware that if you're using `TestClient`, no exceptions are returned - since the exception handler inside FastAPI handles them and returns a regular response; in that case you'll want to test that the `status_code` is as expected instead. – MatsLindh Aug 16 '22 at 09:05
  • Thank you @MatsLindh But my CustomException expects an exception (```python def __init__(self, exception):```). This parameter contains all information for the test (status_code, message, etc.) – daniel guo Aug 16 '22 at 09:15
  • 1
    Yes, you still _raise_ that exception. But you _expect_ a `CustomException` to be raised, regardless of how it was created. `pytest.raises` expects a class, not an instance as far as I can tell. – MatsLindh Aug 16 '22 at 09:15

1 Answers1

2

You need to use raises in the class, like this:

with pytest.raises(CustomException):

Also, you declare status_code_number (in exceptions.py), but use status_code in test case.

Srđan Popić
  • 1,191
  • 13
  • 25