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

How to test api.exception_handler #1171

Open
cosgus opened this issue May 19, 2024 · 0 comments
Open

How to test api.exception_handler #1171

cosgus opened this issue May 19, 2024 · 0 comments

Comments

@cosgus
Copy link

cosgus commented May 19, 2024

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

api_v1 = NinjaAPI()
router = Router()

# I have also tried this with api_v1.get
@router.get("/endpoint1")
def get_endpoint(request):
    data = thing.do()  #This is where the exception would get raised
    return api_v1.create_response(request=request, data=response_data, status=200)

@api.exception_handler(CustomException)
def crawler_locked_handler(request, exc):
    data = {"error": "FATAL ERROR", "message": exc.error}
    return api_v1.create_response(request=request, data=data, status=500)

api_v1.add_router("",router)

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.

from api import router, api_v1
from ninja.testing import TestClient
from django.test import Client

class ThingPatch:

    def raise_custom_error(cls):
        raise CustomError


class TestApiEndpoints(unittest.TestCase):

    def setUp(self):
        self.ninja_client = TestClient(router) # Raises CustomError but does not catch in exception handler
        # self.ninja_client = TestClient(api_v1) # Raises ConfigError copied below
        self.django_client = Client() # Works as expected

    @patch('thing.do', ThingPatch.raise_custom_error)
    def test_custom_error_request(self):
        response = self.ninja_client.get(f'/endpoint1', content_type="application/json")
        self.assertEqual(response.status_code, 500)

ConfigError:

ninja.errors.ConfigError: Looks like you created multiple NinjaAPIs or TestClients
To let ninja distinguish them you need to set either unique version or urls_namespace
 - NinjaAPI(..., version='2.0.0')
 - NinjaAPI(..., urls_namespace='otherapi')
Already registered: ['api-1.0.0']
@cosgus cosgus closed this as completed May 20, 2024
@cosgus cosgus reopened this May 20, 2024
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

1 participant