How to mock external authentication decorator used along with routes #11584
-
First Check
Commit to Help
Example Code# project_name/routes/school_routes.py
from external_library import authentication
@router.get("/", status_code=status.HTTP_200_OK, tags=["schools"])
@authentication
def list_schools(request: Request):
#Code logic
# tests/routes.py
client = TestClient(app)
class TestRoutes(unittest.TestCase):
@patch('project_name.routes.school_routes.authentication')
def setUp(self, mock_auth):
mock_auth.return_value = lambda func: func
def test_list_schools(self):
response = client.get(<PATH>) DescriptionI am importing this authentication decorator from an external library. I am currently writing unittests for the application and somehow the authentication decorator doesn't get patched. I am aware of using authentication through Depends() but somehow I am not permitted to alter the authentication decorator as it is commonly used in several other projects primarily written using other frameworks within the org. Operating SystemmacOS Operating System DetailsNo response FastAPI Version0.110.3 Pydantic Version2.7.1 Python Version3.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Have you tried using import unittest
from unittest.mock import patch
patcher = patch('project_name.routes.school_routes.authentication')
self.mock_auth = patcher.start()
|
Beta Was this translation helpful? Give feedback.
-
You can't patch decorator since Python applies decorators right after you import the module and before methods of Your case is a clear example of the benefits of using dependencies instead of other mechanisms (injecting logic via middlewares, decorators, etc..). I think you can overcome this by introducing a dependency like it's shown above:
To mock the authentication just override the dependency:
|
Beta Was this translation helpful? Give feedback.
You can't patch decorator since Python applies decorators right after you import the module and before methods of
TestRoutes
are called.So, at the moment when you call
TestRoutes
's methods,list_schools
is already modified and patching theauthentication
function doesn't have any effect.Your case is a clear example of the benefits of using dependencies instead of other mechanisms (injecting logic via middlewares, decorators, etc..).
I think you can overcome this by introducing a dependency like it's shown above: