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
-
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
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_init
parameter as one does for setting up the app also does not work - it's missing the session configuration (which the session_auth object owns).What ended up working was the following: Both the
session_auth
and thesession_config
object need to be provided for creating a test client which is in contrast to how the app is set up (where thesession_config
object is passed to thesession_auth
object and that then installs the session middleware).My questions
session_auth
andsession_config
separately?user_client
still 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