sessions_test.go
Overview
sessions_test.go contains comprehensive unit tests for the session management REST API controller defined in the controllers package. It verifies the correctness of CRUD operations on session resources by exercising HTTP handlers that manage user sessions within applications. The file leverages fake in-memory session services from the internal/fakes package to simulate backend data storage and focuses on validating API behavior such as session retrieval, creation, deletion, and listing.
These tests ensure that the session controller correctly handles input validation, error conditions, and response formatting, including proper HTTP status codes and JSON payloads. The tests use the httptest package to simulate HTTP requests and responses, and mux for URL variable extraction. Test cases cover both successful and failure scenarios to verify robustness.
This file is part of the session management domain, closely related to the Session Management topic, particularly in exercising the REST API layer described in REST API and Web Launchers.
Test Functions and Their Details
TestGetSession
Validates the behavior of the GetSessionHandler method, which handles HTTP GET requests to fetch a specific session.
Test Cases:
Session exists: verifies retrieval returns the expected session data with HTTP 200.
Session does not exist: expects an error with HTTP 500.
Missing user ID in input: expects HTTP 400 with appropriate error.
Session ID missing in stored session: expects HTTP 500 error.
Parameters: None (test cases are embedded).
Returns: None (uses t.Fatalf and t.Errorf for test failures).
Usage: Simulates GET requests with URL variables and verifies response code and JSON body correctness using
cmp.Diffwith approximate time equality.
TestCreateSession
Tests the CreateSessionHandler method which handles HTTP POST requests to create a new session.
Test Cases:
Session already exists: expects HTTP 500 with error.
Successful creation: verifies session is stored and returned correctly with HTTP 200.
Missing user ID: expects HTTP 400 error.
Parameters: None (test cases embedded).
Returns: None.
Usage: Sends JSON payloads representing session creation requests, verifies response status, error messages, and response JSON correctness.
TestDeleteSession
Tests the DeleteSessionHandler method which handles HTTP DELETE requests to remove a session.
Test Cases:
Session exists: expects HTTP 200 and confirms deletion.
Session does not exist: expects HTTP 500.
Parameters: None.
Returns: None.
Usage: Simulates DELETE requests and verifies the session is removed from the fake service's map.
TestListSessions
Tests the ListSessionsHandler method which handles HTTP GET requests to list all sessions for a given user.
Test Cases:
Sessions exist: verifies the list of sessions returned matches stored sessions, regardless of order, with HTTP 200.
Parameters: None.
Returns: None.
Usage: Issues a request with URL variables for app_name and user_id, decodes JSON array response, and compares expected vs actual sessions.
Helper Functions
sessionVars(sessionID fakes.SessionKey) map[string]string
Generates a map of URL path variables (app_name, user_id, session_id) from a fakes.SessionKey struct to simulate mux route parameters in tests.
Parameters: sessionID - structure containing app, user, and session identifiers.
Returns: map of string keys to string values for URL variables.
EquateApproxInt(margin int64) cmp.Option
Creates a custom comparer for go-cmp that treats two integer values as equal if their absolute difference is within the specified margin. Used for comparing UpdatedAt timestamps approximately.
Parameters: margin - maximum allowed difference between two int64 values.
Returns: a
cmp.Optionfor approximate integer equality.Usage: Helps in ignoring slight time differences in test comparisons.
Implementation Details and Algorithms
In-memory Session Simulation: The tests utilize fakes.FakeSessionService which holds sessions in a map keyed by fakes.SessionKey. This avoids external dependencies and allows deterministic testing.
Time Handling: Session update times use time.Now() with approximate equality checks to account for slight timing variations during test execution.
Error Handling: Tests verify that error responses from handlers return appropriate HTTP status codes and messages matching expected error strings.
JSON Encoding/Decoding: Session data is marshaled and unmarshaled from JSON in HTTP request bodies and responses to simulate realistic API interactions.
Routing Variables: The mux router's URL variables are manually set in tests to mimic path parameters without running a full server.
Interactions with Other Components
Controllers Package: The API controller under test is instantiated via controllers.NewSessionsAPIController, which takes a session service interface.
Fakes Package: Uses in-memory fakes from internal/fakes for session storage and test session data.
Models Package: The session and event models (models.Session, models.Event, models.CreateSessionRequest) define the data structures used in tests.
Mux Router: URL path variables are set using mux.SetURLVars to simulate extracted route parameters.
Go-Cmp: Used for deep comparison of expected vs actual session structs with custom comparers for time tolerance.
HTTP Testing: Uses
httptestto simulate HTTP response writers and requests.
These interactions ensure isolated, fast, and reliable testing of the session REST API functionality, corresponding to the REST API controller layer described in REST API and Web Launchers and the underlying session logic in Session Management.
Diagram: Session API Test Flow
flowchart TD
A[Test Setup] --> B[Initialize FakeSessionService]
B --> C[Create SessionsAPIController]
C --> D[Create HTTP Request with mux Vars]
D --> E["Invoke Handler (Get/Create/Delete/List)"]
E --> F[Record HTTP Response]
F --> G{Check HTTP Status}
G -->|Matches| H[Decode Response JSON]
H --> I[Compare with Expected Data]
G -->|Mismatch| J[Fail Test]
I --> K{Data Matches?}
K -->|Yes| L[Test Pass]
K -->|No| J
Summary of Main Test Functions
Function | Purpose | HTTP Method | Endpoint Tested |
|---|---|---|---|
Tests retrieving a session | GET | ||
Tests creating a new session | POST | ||
Tests deleting an existing session | DELETE | ||
Tests listing all sessions for user | GET |