Route/Handler testing through login-walls


#1

Some of my web apps use CAS login from the offset: as soon as you try visiting you are redirected to the CAS login page and then redirected back again. Future “logged in” status is preserved via cookies, doing whatever it is CAS does. How can I start testing my routes when this is the case? For example, after logging in you should be able to visit a thing, or submit a thing.


#2

An approach that has worked well for us is to bypass the actual login. You probably have some kind of session store where you go check if the user is logged in based on the cookie in the request. As part of your test setup you can create a session there, and then set a corresponding cookie on the request.

What follows is mostly pseudocode but it should give you an idea. I’m also using the excellent matcher-combinators library.

(deftest home-page-test
  (let [fixtures (factory/person+session!)
        session  (:session fixtures)
        token    (:session/token session)
        response (-> (req/get "/")
                     (req/auth-cookie token)
                     (req/do-request))]

    (is (match? {:status  200
                 :headers {"Content-Type" "text/html"}
                 :body    (m/regex #"AcmeCorp Home Page")}
                response))))

If you go this route you probably want a separate test to verify the interaction with the CAS, possibly by having a sort of mock CAS that honors the same contract.


#3

We use a similar approach where we can essentially mock the token verification/authentication logic for dev/CI and pass a fake token as part of our tests. It relies on code knowing whether it’s in dev/CI mode or QA/production mode (which we already have baked into our environment handling).

As @plexus says, if you do that, you also need to ensure you have solid tests around the login/authentication for real tokens in dev/CI as well!