Replies: 1 comment
-
|
Another thing I thought about is using But that lead to really inconsistent behaviour where the mock was applied either for all tests or none (using mocker.patch("app.admin_user_guard", return_value=None) |
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.
-
Hi, I had a first look at testing with litestar and how to set it up for an app with an auth middleware. My rationale is that I want to be able to test the endpoints functionally without considering authentication (where possible) and then have a separate set of tests to confirm proper authentication and authorization behavior.
The problem
Switching between auth-enabled and auth-disabled testing was simple by using either an "app client" (
AsyncTestClient(app=app)) or a "controller client" (create_async_test_client(UserController)). Figuring out the right configuration for testing an "admin user guard" was not as straightforward.I based my work on the docs for guards and testing using sessions. Thus, I expected something like this to work
... async with create_async_test_client( UserController, session_config=session_config, debug=True ) as client: await client.set_session_data({"user_name": "admin"}) yield client ...However this solution complains that the auth middleware is missing (fair, the session middleware does not specify a user retrieve handler). Unexpectedly, just setting the
on_app_initparameter as one does for setting up the app also does not work - it's missing the session configuration (which the session_auth object owns).... async with create_async_test_client( UserController, on_app_init=[session_auth.on_app_init], debug=True ) as client: await client.set_session_data({"user_name": "admin"}) yield client ...What ended up working was the following: Both the
session_authand thesession_configobject need to be provided for creating a test client which is in contrast to how the app is set up (where thesession_configobject is passed to thesession_authobject and that then installs the session middleware).... async with create_async_test_client( UserController, session_config=session_config, on_app_init=[session_auth.on_app_init], debug=True ) as client: await client.set_session_data({"user_name": "admin"}) yield client ...My questions
session_authandsession_configseparately?user_clientstill uses the same authentication and authorization mechanisms as the app - it just bypasses the login and is always set to an admin user.The Code
Full app and test code below. I was running this on Win10, Python 3.11.7, with Litestar 2.8.2.
App
Test
Beta Was this translation helpful? Give feedback.
All reactions