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:
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.