GitHub Star 1.6k

Testing

Hologram gives every test that uses the data layer a real PostgreSQL database with nothing in it. There are two case templates: Hologram.Test.DatabaseCase for tests without a browser, and Hologram.Test.E2ECase for tests that drive the running app from its UI. Tests of both can be async: true.

Both import Hologram.Test and bring in everything use Hologram.DB does: the DB, Entity and Job aliases, and the functions that build queries and writes, like filter, sort, put_attribute and trust. A test needs no extra line for them. A test module that defines and calls its own function with the name and arity of one of these doesn't compile.

Setup

Call Hologram.Test.setup/0 in test_helper.exs, after ExUnit.start():

ExUnit.start()
Hologram.Test.setup()

It compiles the app's pages, starts Hologram, and builds the schema from your model. This happens once per test run, not for each test. The run makes its own databases and reuses them between tests, but each test starts with an empty one and never sees another test's data. It never touches the configured database, so you can run the tests twice at the same time on one server. A run also drops the databases that earlier runs left behind. The configured database user must be allowed to create databases. A superuser is, and so is a role with CREATEDB:

ALTER ROLE my_app CREATEDB;

DatabaseCase and E2ECase are only for apps that use Hologram's data layer. If your app has no entities, use ExUnit.Case with your own database setup instead, as Apps That Use Ecto shows below. Keep Hologram.Test.setup/0, since it starts Hologram.

DatabaseCase

DatabaseCase runs each test in a transaction and rolls it back when the test ends, also when it fails or crashes. This costs about a millisecond, so use it for every test that needs no browser.

defmodule MyApp.TodoTest do
  use Hologram.Test.DatabaseCase, async: true

  alias MyApp.Todo

  setup do
    {:ok, todo: DB.create!(Todo.new(title: "Buy milk"))}
  end

  test "marks a todo as done", %{todo: todo} do
    :ok = DB.update(Todo, todo.id, done: true)

    assert [%Todo{done: true}] = DB.read(Todo)
  end
end

Create entities in setup or in the test. setup_all has no database, and neither has an on_exit block of an async test. Entities can't be created in test_helper.exs after Hologram.Test.setup/0 either.

Nothing a test writes is committed, so live sync doesn't see it. Test live sync with E2ECase.

A transaction in one process holds the test's connection. If that process waits inside the transaction for another process that runs a query, the test hangs.

If a process is killed or times out in the middle of a query, the test loses its connection and everything it wrote. Later data layer calls in that test raise Hologram.MisuseError.

Acting as a User

Test code has no user, so it reads and writes past the rules of Access Control. Call as_user/1 to run the rest of the test as a user, or as_user/2 to run one function as a user. nil stands for a signed-out visitor.

test "hides another user's todos", %{other_user: other_user} do
  as_user(other_user, fn ->
    assert DB.read(Todo) == []
  end)
end

Create the entities before as_user/1, or the rules apply to them too.

Running Jobs

No worker runs jobs in a DatabaseCase test. run_jobs/0 runs the jobs that are due in the test's own process, each as whoever created it, along with the jobs they create.

test "notifies the members", %{project: project} do
  Job.create!(NotifyMembers, project_id: project.id)

  assert [{NotifyMembers, _id, :done}] = run_jobs()
end

It returns {job_type, id, :done} or {job_type, id, :failed} for each run, in order. A failed job with attempts left stays queued for its retry time, and the same call doesn't run it again. Time limits don't apply. Cancelling a job while it runs doesn't stop it. The job ends up :cancelled, and the result still says how its run went. run_jobs/0 raises Hologram.MisuseError inside a DB.transaction/1 block, and in any test that doesn't use DatabaseCase.

Unique Values in Async Tests

Async DatabaseCase tests share one database that never commits. When two of them write the same unique value, the second waits until the first one ends. Two tests that write the same unique values in a different order can deadlock. Generate the values instead:

User.new(email: "user-#{System.unique_integer([:positive])}@example.com")

E2ECase tests have a database each, so this doesn't affect them.

E2ECase

Each E2ECase test gets an empty database of its own. What it writes is committed, so live sync works and a worker runs the jobs, as in the running app. When the test ends, Hologram empties the database and gives it to another test. The number of databases depends on how many connections the server has free. A test waits while none is free, and the wait counts toward its timeout.

The case opens no browser. It works with Wallaby's Chrome driver, and with any other tool that can set the user agent.

Wallaby

Put use Wallaby.Feature after the case. The browsers it starts then use the test's database:

defmodule MyApp.TodoFeature do
  use Hologram.Test.E2ECase, async: true
  use Wallaby.Feature

  import Wallaby.Query

  alias MyApp.Todo

  feature "shows a todo", %{session: session} do
    DB.create!(Todo.new(title: "Buy milk"))

    session
    |> visit("/todos")
    |> assert_has(css("li", text: "Buy milk"))
  end
end

In the other order Wallaby starts its browsers before the case can add the test's marker to their user agent, and their requests belong to no test. Hologram adds the marker only to the Chrome args of chromeOptions or goog:chromeOptions. With mobileEmulation the browser sends the emulated user agent, which has no marker, so the test has to set it itself with user_agent/1.

Firefox and Selenium sessions, and sessions the test starts itself, need user_agent/1 too.

Wallaby.Query has a count/1 too, so a module that calls count/1 on a Hologram query needs import Wallaby.Query, except: [count: 1].

Other Browsers and Clients

user_agent/1 takes a user agent and returns it with the test's marker added:

user_agent =
  user_agent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36")

{:ok, session} =
  Wallaby.start_session(
    capabilities: %{
      chromeOptions: %{args: ["--headless", "--user-agent=#{user_agent}"]}
    }
  )

Pass the whole user agent the browser would send otherwise, since the result replaces it. The same works for an HTTP client. Once the test has ended, requests with its marker get a 503 response.

A request without the marker belongs to no test, so the next section's rule applies to it.

Processes Outside the Test

The processes a test starts use its database: tasks, spawned processes, those started with start_supervised!/1, and the ones these start. So do the requests of its browsers. A process still running after its test gets Hologram.MisuseError when it uses the data layer, so wait for it in the test or start it with start_supervised!/1.

A process that belongs to no test, like a GenServer the app started, gets Hologram.MisuseError when it uses the data layer during an async test. Two things change that:

setup do
  claim_process(MyApp.Cache)
end

Hologram.Router is what ties a browser's request to its test, so code that runs outside it isn't covered:

Apps That Use Ecto

Hologram's cases and Ecto's sandbox work side by side. In an app with entities, check out the repo in setup:

defmodule MyApp.ReportTest do
  use Hologram.Test.DatabaseCase, async: true

  setup tags do
    pid = Ecto.Adapters.SQL.Sandbox.start_owner!(MyApp.Repo, shared: not tags[:async])
    on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)

    :ok
  end

  # ...
end

In an E2ECase test with Wallaby, use Wallaby.Feature checks out the repos itself and puts its own metadata into the user agent. It needs config :wallaby, otp_app: :my_app and the Phoenix.Ecto.SQL.Sandbox plug in the endpoint, before Hologram.Router. Wallaby adds its metadata only to a --user-agent= switch in chromeOptions. Hologram's marker stays next to it.

In an app without entities, leave the cases out and use the Ecto setup on its own. Keep Hologram.Test.setup/0 in test_helper.exs, since it starts Hologram:

defmodule MyApp.ReportFeature do
  use ExUnit.Case, async: true
  use Wallaby.Feature

  # ...
end
Sponsored by
Curiosum
Main sponsor
Erlang Ecosystem Foundation
Milestone sponsor
Evo Store
Performance sponsor
Sruplex
Innovation partner
Previous
← Jobs