While working on a personal project using Go and alexedwards/scsfor handling sessions, I’ve come across an issue when creating tests: After setting up the configuration and the LoadAndSave middleware, all tests started failing with 401 (Unauthorized) response.
In this quickly post we’ll simple a small GoLang server using go-chirouter and implement a LoadAndSaveMock middleware to inject any session information into our test.
First, let’s create a Server struct to hold our session manager and router
And now, create our main function, session, router and server
Note that we are defining the LoadAndSave middleware from the SCS session. This middleware will get the value from the cookie and save into our request context.
Server routes
We can now define two routes:
/ - Will return 200 (Ok) with the message “Hello, World!” and insert an user_role value into our context
/admin - Will return 200 (Ok) with the message “Hello, <role>!”
If we request the /admin endpoint before requesting the root endpoint, we should get an 401 (Unauthorized) status code.
Let’s implement all handlers:
Defining the handlers into router:
Middleware for user authorization
To complete our simple GoLang server, we need a middleware for handling user authorization
We’ll use this middleware inside the router.Group
The testing
Now, the testing part.
Our test will have four paths:
Public endpoint that will return 200 (Ok)
Admin endpoint without role that will return 401 (Unauthorized)
Admin endpoint with wrong role that will return 401 (Unauthorized)
Admin endpoint with correct role that will return 200 (Ok)
Implementing the first part of the test logic (server configuration):
Second part of the test logic (http request and status validation):
LoadAndSaveMock middleware
In this section we’ll create a wrapper/middleware of the LoadAndSave middleware from the SCS package, this mock will inject any value we want into our router before recording the test request:
Putting all together
The final test code logic:
And.. we get this result
Conclusion
In this post I show you a solution to a problem that I’ve encountered while implementing auth tests using the SCS session package.
Comments