Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom exception handler with TestClient cannot access request data #641

Closed
LaundroMat opened this issue Jan 2, 2023 · 2 comments
Closed

Comments

@LaundroMat
Copy link

LaundroMat commented Jan 2, 2023

I have this custom exception handler for PermissionDenied errors:

@api.exception_handler(PermissionDenied)
def permission_error(request, exc):
    if 'team_id' in request.resolver_match.captured_kwargs.keys():
        message = "You do not have access to this team."
    else:
        message = "Forbidden."

    return api.create_response(
        request,
        {"detail": message},
        status=403,
    )

I'd like to customize the error messages based on information in the request. But using the TestClient, the request is a Mock instance, so I get an TypeError: argument of type 'Mock' is not iterable when trying to access the request's captured kwargs. Is there a way around this?

@vitalik
Copy link
Owner

vitalik commented Jan 3, 2023

@LaundroMat

I guess you can override the TestClient like this:

class MyTestClient(TestClient):
    def _call(self, func, request, kwargs):
        request.resolver_match.captured_kwargs.keys = Mock(return_value=['team_id'])
        return super()._call(func, request, kwargs)

@LaundroMat
Copy link
Author

Thanks for the pointer. In the end I'm returning custom error messages from within the views, it makes things a bit more manageable :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants