Test helpers

On this page

ExUnit helpers to run a hot deploy inside your own test suite: build the next version of a module, deploy it into the test VM while your processes run, and assert that the deploy kept the process, migrated its state and left a way back. Hotcode.Test.Cluster does the same across real nodes on different versions.

This page is built from the docs of Hotcode.Test and Hotcode.Test.Cluster. For a tour with explanations, read Testing your hot deploys.

Hotcode.Test

ExUnit helpers to test your hot deploys before production does: build the next version of a module, deploy it into the test VM while your processes run, and assert that the deploy did what a hot deploy must do (same process, migrated state, a way back, nothing lost).

defmodule MyApp.CounterUpgradeTest do
  use Hotcode.Test

  test "v2 keeps the counter process and migrates its state" do
    {:ok, pid} = MyApp.Counter.start_link(count: 3)
    v2 = build("test/releases/counter_v2")

    assert_survives_deploy(pid, v2,
      state: &match?(%{count: 3, history: []}, &1),
      rollback: true
    )
  end
end

See the testing guide for the whole tour.

use Hotcode.Test

Use it instead of use ExUnit.Case (other ExUnit.Case options pass through). A hot deploy changes the code of the whole VM, so:

  • the module runs synchronously: use Hotcode.Test, async: true raises at compile time, and so does a test of an async: true case reaching its setup;
  • before each test, Hotcode.Loader.reset/0 and config :hotcode, unsafe_allow_unsigned: true (tests deploy unsigned bundles, which a real node refuses; unsigned: false keeps the flag as configured), plus allowed_prefixes: and any env: given;
  • after each test, even one that raised: every module the test replaced gets its original binary back (not merely deleted, so the next test runs the code your project compiled), modules the test hot-loaded are unloaded, processes still running the test's code go with it, versioned tables (Hotcode.Table) the test created are dropped, the loader's history is reset and the :hotcode environment (and that of env_apps:) is put back.

Options: :unsigned (default true), :allowed_prefixes, :env (more :hotcode env for the test), :env_apps (other applications whose environment is restored after each test).

The helpers

  • releases: build/2, deploy!/2, rollback!/1
  • state of a Hotcode.Versioned process: assert_upgrades/3, assert_roundtrip/3
  • a live process: assert_survives_deploy/3, assert_survives_redeploy/3
  • versioned ETS tables: assert_table_upgrade/3, assert_table_deploy/3
  • traffic during a deploy: with_load/3, assert_no_lost_messages/2
  • nodes on mixed versions: Hotcode.Test.Cluster

Failures raise ExUnit.AssertionError with a sentence about the hot-deploy mistake, for example state of MyApp.Counter was not migrated: the v1 shape was found after the deploy.

The module compiles without ExUnit (it is part of the library, in every environment); the helpers are only meant to run in tests. The property form of assert_roundtrip/3 needs {:stream_data, "~> 1.1", only: :test} in your deps.

build/2

build(sources, opts \\ [])
@spec build(Path.t() | %{optional(Path.t()) => String.t()}, keyword()) :: Release.t()

Compiles the next version of some modules into a Hotcode.Test.Release, without loading it into the test VM.

sources is a directory (every **/*.ex in it), a single .ex file, or a map of %{"path.ex" => source}. They are compiled by an external elixirc with the test VM's code paths, so they can use your application and Hotcode. A compile error raises a CompileError carrying elixirc's output. The same sources are compiled once per VM.

v2 = build("test/releases/v2")

v2 = build(%{"counter.ex" => """
  defmodule MyApp.Counter do
    use Hotcode.Versioned, vsn: 2
    ...
  end
  """})

Options: :version, the bundle version (default "test-" and a hash of the sources).

deploy!/2

deploy!(release, opts \\ [])
@spec deploy!(Release.t() | Hotcode.Bundle.t() | binary(), keyword()) :: map()

Hot-deploys release into the test VM (Hotcode.Loader.deploy/2, unsigned, not persisted) and returns the loader's report. A refused or failed deploy fails the test, with the loader's reason in words.

release is a Hotcode.Test.Release, a Hotcode.Bundle or a packed bundle binary. Options go to Hotcode.Loader.deploy/2 (force:, suspend_timeout:, ...).

rollback!/1

rollback!(opts \\ [])
@spec rollback!(keyword()) :: map()

Rolls back the last deploy (Hotcode.Loader.rollback/1) and returns the report. A refused rollback fails the test with the reason in words.

assert_upgrades/3

assert_upgrades(module, state, opts)
@spec assert_upgrades(module(), term(), keyword()) :: term()

Runs the upgrade/2 chain of a Hotcode.Versioned module on state, a state of version from:, up to to: (default: the module's vsn), and returns the upgraded state. Fails when a step is missing or raises. Nothing runs in a process: it is the same function a deploy calls, on a copy.

new = assert_upgrades(MyApp.Counter, %{count: 3}, from: 1)
assert new == %{count: 3, history: []}

assert_roundtrip/3

assert_roundtrip(module, %{__struct__: StreamData} = generator, opts)
@spec assert_roundtrip(module(), term(), keyword()) :: term()

Upgrades state from from: to the module's vsn and downgrades it back (what a deploy followed by a rollback does), and fails unless that gives back exactly state. Returns the migrated state.

assert_roundtrip(MyApp.Counter, %{count: 3}, from: 1)

Given a StreamData generator instead of a state, checks every generated state (max_runs:, default 100) and reports the smallest failing one:

assert_roundtrip(MyApp.Counter, StreamData.fixed_map(%{count: StreamData.integer()}), from: 1)

Options: :from (required), :to, :max_runs.

assert_survives_deploy/3

assert_survives_deploy(server, release, opts \\ [])
@spec assert_survives_deploy(GenServer.server(), Release.t() | Hotcode.Bundle.t(), keyword()) :: map()

Deploys release while server (a pid or a registered name) runs, and fails unless the deploy kept the process and migrated its state:

  • the same pid is alive after the deploy (and the name still points to it);
  • the process is not left on the old code (it would make the next deploy fail);
  • its state changed, when the release bumps the module's vsn (the state of a Hotcode.Versioned process whose vsn changes is expected to change shape), unless allow_same_state: true;
  • state: (a function of the new state returning true) accepts the new state;
  • with rollback: true, a rollback keeps the same pid again and gives back exactly the state it had before the deploy.

Returns %{pid:, before:, after:, report:}. Other options go to deploy!/2.

assert_survives_deploy(MyApp.Counter, v2, state: &match?(%{history: []}, &1), rollback: true)

assert_survives_redeploy/3

assert_survives_redeploy(server, release, opts \\ [])
@spec assert_survives_redeploy(GenServer.server(), Release.t() | Hotcode.Bundle.t(), keyword()) :: [
  map()
]

Deploys new code under server several times in a row (times:, default 2) and fails when the process does not survive it. One deploy is not enough to find these:

  • a process that runs the old code in a local loop: the first deploy leaves it on the old code, the second must purge that code, and Hotcode.Loader refuses (:lingering_old_code) rather than kill it. The failure names the pids it found;
  • a fun created by the old code and kept in the state: it still works after one deploy, and raises :badfun once its code is purged by the second. Pass probe: (a function of the pid, run after every deploy, for example &GenServer.call(&1, :run_callback)) so the stored fun is actually called.

When release is a Hotcode.Test.Release, the later deploys are rebuilt variants of the same sources (each one a different binary of the same code). Otherwise give them with then:, a list of releases deployed after release.

Returns the list of deploy reports.

assert_survives_redeploy(pid, v2, times: 2, probe: &GenServer.call(&1, :ping))

assert_table_upgrade/3

assert_table_upgrade(module, rows, opts)
@spec assert_table_upgrade(module(), [tuple()], keyword()) :: [tuple()]

Runs rows (rows of version from:) through the upgrade/2 chain of a Hotcode.Table module up to to: (default: the module's vsn) and returns the upgraded rows. Unless roundtrip: false (an upgrade that deletes rows cannot give them back), the upgraded rows must downgrade back to exactly rows, as a rollback would need.

Nothing touches a table: it is the same chain a deploy runs, on a list.

assert_table_upgrade(MyApp.Sessions, [{"id", "ann"}], from: 1) == [{"id", "ann", %{}}]

assert_table_deploy/3

assert_table_deploy(module, release, opts \\ [])
@spec assert_table_deploy(module(), Release.t() | Hotcode.Bundle.t(), keyword()) :: map()

Deploys release and fails unless the live table of module (a Hotcode.Table) was migrated: its registered version is the new module's vsn, and its rows are exactly the rows it held, run through the new upgrade/2 chain. With rollback: true, a rollback must give back the rows and the version it had.

Returns %{before:, after:, report:} (sorted rows). Other options go to deploy!/2.

with_load/3

with_load(load, opts \\ [], action)
@spec with_load((pos_integer() -> term()), keyword(), (-> term())) :: Load.t()

Keeps traffic going while action runs (typically a deploy), and returns a Hotcode.Test.Load with what happened to it.

load is called over and over with a counter (n) by concurrency: processes (default 1). The action only starts once before: calls (default 20) have completed, and the traffic only stops once after: more have completed after it, so the deploy really happens in the middle of live traffic. A call that raises, exits or throws is a failure.

load =
  with_load(fn _n -> MyApp.Counter.inc(pid) end, fn -> deploy!(v2) end)

assert_no_lost_messages(load, received: MyApp.Counter.count(pid))

Options: :concurrency, :before, :after, :timeout (ms each phase may take, default 10_000).

assert_no_lost_messages/2

assert_no_lost_messages(%Load{} = load, opts \\ [])
@spec assert_no_lost_messages(Load.t(), keyword()) :: Load.t()

Fails when traffic was lost around a deploy: any call of with_load/3 failed (a call that timed out on a suspended process, or found it dead), or, with received: (what the receiving side counted, for casts and plain messages), fewer messages were handled than calls returned.

The message reports the counts; the test asserts none were lost, not how many were sent. Returns the load.

Hotcode.Test.Cluster

A real cluster for tests: each node is its own BEAM started with :peer, runs :hotcode configured like production (signed envelopes only, keys generated for the test), and is meshed with the others over Erlang distribution. Nodes can run different versions of your code, which is what a rolling deploy looks like halfway through.

@moduletag :cluster

test "v1 and v2 nodes talk to each other" do
  v1 = build("test/releases/v1")
  v2 = build("test/releases/v2")

  cluster =
    Hotcode.Test.Cluster.start([:a, :b],
      release: v1,
      boot: {MyApp.TestBoot, :start, []}
    )

  # b moves to v2 alone: a mixed-version cluster
  Hotcode.Test.Cluster.load(cluster, :b, v2)
  assert %{a: _, b: "test-" <> _} = Hotcode.Test.Cluster.versions(cluster)

  # ... exercise a <-> b ...

  # the real thing: a signed roll across every node
  {:ok, _} = Hotcode.Test.Cluster.deploy(cluster, v2)
end

What it needs

The nodes are started with -name on 127.0.0.1, so the machine needs epmd (it ships with Erlang; epmd -daemon starts it, and a node started with a name starts it too). The test VM itself does not join the cluster (the nodes are driven through their standard I/O), so Hotcode.Rollout on a node sees exactly the nodes under test. Each node is a full VM: a few hundred milliseconds to start, and the test module must be async: false (use Hotcode.Test).

Tag these tests (@moduletag :cluster) and exclude the tag where distribution is not available, for example in test_helper.exs:

cluster? = match?({:ok, _}, Node.start(:"test@127.0.0.1", :longnames))
ExUnit.start(exclude: if(cluster?, do: [], else: [:cluster]))

The nodes are linked to the test process: they stop when the test ends, passed or failed.

Code on the nodes

The nodes get the test VM's code paths, so your compiled application, its deps and Hotcode are there; modules defined in a test file (.exs) are not. boot: must therefore be an {module, function, args} of compiled code (in test/support, for example), and so must anything passed to call/5.

start/2

start(names, opts \\ [])
@spec start([atom()], keyword()) :: t()

Starts one node per name and meshes them. Every node:

  1. starts :hotcode with this cluster's keys trusted (:keys, default one generated key named "test"), audience: "hotcode-test" and allowed_prefixes: (default: the first segment of every module of release:);
  2. loads release: (a Hotcode.Test.Release, or %{name => release} for nodes that start on different versions), its "boot release", unsigned and not persisted;
  3. runs boot: ({m, f, args}), your application's start for the test.

Options: :release, :boot, :env (more :hotcode env on every node), :env_by_node (%{name => env}), :audience, :allowed_prefixes, :keys (%{name => {public, private}}, from Hotcode.Trust.generate_key/0).

mesh/1

mesh(%__MODULE__{nodes: nodes})
@spec mesh(t()) :: :ok

Full mesh over distribution (the nodes do not connect to each other by themselves).

member/2

member(%__MODULE__{nodes: nodes}, name)
@spec member(t(), atom()) :: member()

The member called name.

call/5

call(cluster_or_member, name_or_mod, mod_or_fun, fun_or_args, args_or_timeout \\ nil)

Runs mod.fun(args) on a node (name or a member), through its standard I/O rather than distribution. mod must be compiled code (not a module of a test file).

load/3

load(%__MODULE__{} = cluster, name, %Release{} = release)
@spec load(t(), atom(), Release.t()) :: {:ok, map()} | {:error, term()}

Loads release on one node, unsigned (as its boot release would be), bypassing the signature check for that one call: the way to put the cluster on mixed versions.

sign/3

sign(%__MODULE__{} = cluster, %Release{} = release, opts \\ [])
@spec sign(t(), Release.t(), keyword()) :: binary()

A signed envelope for release, valid for this cluster. base: (what the target nodes must be running, %{"Elixir.Mod" => md5}) defaults to what node on: (default: the first) runs now. Other options go to Hotcode.Envelope.build/2 (force:, requires:, auto_rollback:, ...); signers: picks keys by name (default: all of them).

deploy/3

deploy(cluster, release_or_envelope, opts \\ [])
@spec deploy(t(), Release.t() | binary(), keyword()) :: {:ok, map()} | {:error, term()}

A real operator action: signs release (or takes a signed envelope) and runs Hotcode.Rollout.deploy_cluster/2 on node on: (default: the first), across every node.

versions/1

versions(%__MODULE__{nodes: nodes})
@spec versions(t()) :: %{atom() => String.t() | nil}

The version each node's loader reports: %{name => version}.

stop/1

stop(%__MODULE__{nodes: nodes})
@spec stop(t()) :: :ok

Stops every node.