Testing User Creation and Login
In this section, we first test the user creation flow by verifying that the response returns the correct email and status code. Then, we test the login route by performing a POST request with the user’s credentials and ensuring that a valid token is generated.Login Endpoint Implementation
Within the authentication router (typically found in yourauth.py under the routers directory), the login endpoint uses a Token schema as its response model. The code snippet below shows the login route that confirms the user’s existence and validates the provided password:
schemas module provides access to the necessary token schema. The following code snippet demonstrates the user creation test:
Decoding and Validating the Access Token
Once the access token is received, decoding it is crucial to verify that it contains the correct user information. The logic used is similar to what is implemented in theOAuth2.py file for retrieving the current user. The get_current_user function decodes the token and uses the embedded user_id to fetch the corresponding user from the database:
verify_access_token function leverages the jwt.decode method to validate the token and extract the user’s ID. If the token is invalid, it immediately raises an exception:
Finalizing the Login Test with Token Decoding
After obtaining the token from the login response, decode it using your application settings (imported from your configuration module). This allows you to extract and validate theuser_id. The final login test confirms that the decoded token contains the correct user details and that the token type is set to “bearer”.
app.config import settings is properly imported so that the secret_key and algorithm values are correctly referenced during the token decoding process.
The test fixture used to create a test user is vital for ensuring consistent test results. Ensure that the test user creation code is correctly configured.