Ways to test token expiration?

Hey there! I’m coming from an OOP background and am new to Elixir so trying to understand testing strategies where I need to change a config variable for one specific test.

For example, I have a function which verifies a token is valid and I’d like to write a test that shows when then token is over max_age it is no longer valid. I am thinking of two possible approaches:

  1. Change max_age config variable to say 500ms for this specific test case, Sleep say 1000ms, verify it is no longer valid (preferred).
  2. Somehow change the system time in the test so it progresses a day and assert the token isnt valid (interesting idea but in this case doesn’t feel great).

Here’s some code:

defmodule Auth.Token do
  @context some_value

  def verify(token) do
      max_age: MyApp.Endpoint.config(:token_max_age)

defmodule MyApp.AuthTest do
  use ExUnit.Case

    test "when: provide expired token, returns error" do

In other languages I might have added token_max_age to the constructor as an optional option (could do the same here at the function level but I believe that opens up the possibility to use a poorly thought out max_age in production).

I also understand I can change the token_max_age config variable for the entire test suite but this seems like too broad of a solution.

You can also create token that is already expired and check if the endpoint will fail. You can do it like that:

token = Phoenix.Token.sign(context, salt, token, signed_at: 0)

refute do_request(conn, token: token)
1 Like