cardinal

Testing

Run an app's ExUnit tests against throwaway tenants with cardinal test --app.

cardinal test --app library

This runs mix test apps/library/test in the test env. The database is the workspace's with _test appended, so no test touches a real site. Each test module installs its own tenant with every workspace app on it.

A test module

test/book_test.exs
defmodule Library.BookTest do
  use ExUnit.Case, async: true
  alias Cardinal.{Ctx, DB}
  alias CardinalCore.Services.{TenantService, TxnService}

  setup_all do
    host = "library-#{System.unique_integer([:positive])}.test.localhost"
    {:ok, tenant} = Cardinal.Test.Tenants.install(host)
    on_exit(fn -> TenantService.drop(host) end)
    %{sys: DB.as_system(%Ctx{tenant: tenant, user: "Administrator"})}
  end

  test "a book without copies is refused", %{sys: sys} do
    assert {:error, {:invalid, [%{path: "copies"}]}} =
             TxnService.run(sys, &DB.insert(&1, "Book", %{"title" => "Dune", "copies" => 0}))
  end
end

Cardinal.Test.Tenants.install/1 copies a template tenant built once per test run, in about a quarter of a second. Use Cardinal.Test.Tenants.create/1 when the test is about installing.

Test as a real user

as_system skips permission checks. To test what a role may do, insert a User in setup, then load that user's principal:

{:ok, _} =
  TxnService.run(sys, fn c ->
    {:ok, _, fx} =
      DB.insert(c, "User", %{"email" => "rep@crm.test", "first_name" => "Rep", "roles" => [%{"role" => "Sales User"}]})

    {:after_commit, :ok, fx}
  end)

{:ok, rep} =
  TxnService.run(%Ctx{tenant: tenant, user: "rep@crm.test"}, fn c ->
    %{c | principal: PermService.load_principal(c), meta_version: nil}
  end)

PermService is CardinalCore.Services.PermService.

Keep tests apart

Tests in one module share a tenant. Run each write in a transaction that returns an error at the end, so it rolls back and the next test sees a clean tenant.

CI

The scaffold's .github/workflows/ci.yml checks mix format, builds a workspace from Cardinal's main with the app linked in, and runs cardinal test --app. It needs a CARDINAL_TOKEN repository secret that can read the Cardinal repository.

Desk plugin tests run separately, with bun test in frontend/.

On this page