|
| 1 | +# pylint: disable=protected-access |
| 2 | +# pylint: disable=redefined-outer-name |
| 3 | +# pylint: disable=too-many-arguments |
| 4 | +# pylint: disable=too-many-statements |
| 5 | +# pylint: disable=unused-argument |
| 6 | +# pylint: disable=unused-variable |
| 7 | + |
| 8 | +from collections.abc import Callable |
| 9 | + |
| 10 | +from aiohttp import web |
| 11 | +from servicelib.aiohttp import status |
| 12 | +from simcore_service_webserver.exception_handling import exception_handling_decorator |
| 13 | + |
| 14 | + |
| 15 | +async def test_handling_exceptions_decorating_a_route(aiohttp_client: Callable): |
| 16 | + |
| 17 | + # custom exception handler |
| 18 | + async def value_error_as_422( |
| 19 | + request: web.Request, exception: BaseException |
| 20 | + ) -> web.Response: |
| 21 | + return web.json_response(status=status.HTTP_422_UNPROCESSABLE_ENTITY) |
| 22 | + |
| 23 | + # decorator |
| 24 | + exc_handling = exception_handling_decorator({ValueError: value_error_as_422}) |
| 25 | + |
| 26 | + # adding new routes |
| 27 | + routes = web.RouteTableDef() |
| 28 | + |
| 29 | + @routes.get("/{what}") |
| 30 | + @exc_handling # < ----- using decorator |
| 31 | + async def _handler(request: web.Request): |
| 32 | + match request.match_info["what"]: |
| 33 | + case "ValueError": |
| 34 | + raise ValueError # handled |
| 35 | + case "IndexError": |
| 36 | + raise IndexError # not-handled |
| 37 | + case "HTTPConflict": |
| 38 | + raise web.HTTPConflict # not-handled |
| 39 | + case "HTTPOk": |
| 40 | + # non errors should NOT be raised, |
| 41 | + # SEE https://github.com/ITISFoundation/osparc-simcore/pull/6829 |
| 42 | + # but if it is so ... |
| 43 | + raise web.HTTPOk # not-handled |
| 44 | + |
| 45 | + return web.Response() |
| 46 | + |
| 47 | + app = web.Application() |
| 48 | + app.add_routes(routes) |
| 49 | + |
| 50 | + # testing from the client side |
| 51 | + client = await aiohttp_client(app) |
| 52 | + |
| 53 | + # success |
| 54 | + resp = await client.get("/ok") |
| 55 | + assert resp.status == status.HTTP_200_OK |
| 56 | + |
| 57 | + # handled non-HTTPException exception |
| 58 | + resp = await client.get("/ValueError") |
| 59 | + assert resp.status == status.HTTP_422_UNPROCESSABLE_ENTITY |
| 60 | + |
| 61 | + # undhandled non-HTTPException |
| 62 | + resp = await client.get("/IndexError") |
| 63 | + assert resp.status == status.HTTP_500_INTERNAL_SERVER_ERROR |
| 64 | + |
| 65 | + # undhandled HTTPError |
| 66 | + resp = await client.get("/HTTPConflict") |
| 67 | + assert resp.status == status.HTTP_409_CONFLICT |
| 68 | + |
| 69 | + # undhandled HTTPSuccess |
| 70 | + resp = await client.get("/HTTPOk") |
| 71 | + assert resp.status == status.HTTP_200_OK |
0 commit comments