Replies: 1 comment
-
sup! i have very strange workaround for this, but got it working # apps.common.api.errors
from django.core.exceptions import ValidationError
from ninja import NinjaAPI
def get_validation_error_handler(api: NinjaAPI):
def handle(request, exc: ValidationError):
error = "Validation Error"
error_data = {"message": error, "errors": exc.error_list}
return api.create_response(request, error_data, status=400)
return (handle, ValidationError)
def get_exception_handler(api: NinjaAPI):
def handle(request, exc: Exception):
error_data = {"message": str(exc)}
return api.create_response(request, error_data, status=500)
return (handle, Exception)
EXCEPTION_HANDLERS = [get_validation_error_handler, get_exception_handler]
def add_exception_handlers(api: NinjaAPI):
for handler in EXCEPTION_HANDLERS:
handler_func, exc = handler(api)
api.add_exception_handler(handler=handler_func, exc_class=exc) # apps.common.test_client
'''
This is mixin file for testing
'''
from django.conf import settings
from ninja import NinjaAPI, Router
from ninja.testing import TestClient
from apps.common.api.errors import add_exception_handlers
class BaseNinjaTestCase(object):
@classmethod
def setup_client(cls, router: Router):
settings.DEBUG = True
settings.IN_TEST = True
cls.api_client = TestClient(router)
'''
https://github.com/vitalik/django-ninja/blob/c6d44b62a180fcf8ddfd73d67e0274a77b9d30ae/ninja/testing/client.py#L94-L95
when we in test we not having urls, so it recreates api instance without attached handlers
'''
_ = cls.api_client.urls
# add handlers
add_exception_handlers(cls.api_client.router_or_app.api) # example test file
from apps.common.test_client import BaseNinjaTestCase
from apps.sheets.operations.api import router
class TestOperationsApi(TestCase, BaseNinjaTestCase):
@classmethod
def setUpTestData(cls):
cls.setup_client(router) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I have api.exception handlers to return a particular payload when that error is raised. Works great but I cant figure out how to handle the tests. Here is a condensed version of my code:
api.py
and here is my test. If I instatiate the Ninja TestClient with api_v1.router, the CustomError gets raised but the exception handler does not catch it. TestClient(api_v1) raises a ninja ConfigError. Django.test Client() works as expected.
ConfigError:
Beta Was this translation helpful? Give feedback.
All reactions