Testing your hot deploys

On this page

A hot deploy can be wrong in ways a normal test suite never sees: the new code is fine, the old code was fine, and the switch between them loses a process, a state field, a table row or a message. Hotcode.Test runs that switch in your test suite: it builds the next version of a module, deploys it into the test VM while your processes run, and checks what a hot deploy must keep.

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

The helpers ship with Hotcode itself; nothing to add to your deps except, for the property form of assert_roundtrip/3, StreamData:

# mix.exs (optional: only for property-based round trips)
{:stream_data, "~> 1.1", only: :test}

use Hotcode.Test

Use it instead of use ExUnit.Case. A hot deploy replaces code for the whole VM, so the test module is synchronous: use Hotcode.Test, async: true raises at compile time. Around every test it:

  • resets the loader (Hotcode.Loader.reset/0) and lets the test deploy unsigned bundles (unsafe_allow_unsigned: true, which a real node refuses; unsigned: false keeps your configuration, for tests of the signing path);
  • afterwards, even when the test raised: gives every module the test replaced its original binary back (the code your project compiled, not merely a deleted module), unloads the modules the test hot-loaded, kills processes still running the test's code, drops the Hotcode.Table tables the test created, resets the loader and puts the :hotcode application environment back.

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

Releases: build/2, deploy!/2, rollback!/1

A test needs the next version of a module, and it must not be loaded before the deploy (or the deploy would find nothing to change). build/2 compiles sources with an external elixirc (a separate OS process, with your project's code paths) into a Hotcode.Test.Release:

v2 = build("test/releases/counter_v2")          # every .ex under the directory
v2 = build("test/releases/counter_v2.ex")       # one file
v2 = build(%{"counter.ex" => source})           # sources in the test itself

Keep the next versions next to the tests, for example test/releases/<name>/, and out of elixirc_paths (they define modules your project already has). A compile error raises a CompileError with elixirc's output. The same sources compile once per test run.

deploy!/2 deploys a release (or a Hotcode.Bundle) and returns the loader's report; rollback!/1 undoes the last deploy. Both fail the test, in words, when the loader refuses.

State: assert_upgrades/3, assert_roundtrip/3

For a Hotcode.Versioned module, the migration chain is plain functions. Check them without a process:

test "the counter migrates from v1, and back" do
  assert assert_upgrades(MyApp.Counter, %{count: 3}, from: 1) == %{count: 3, history: []}
  assert_roundtrip(MyApp.Counter, %{count: 3}, from: 1)
end

assert_roundtrip/3 fails when the downgrade chain does not give back exactly the state it started from: a rollback would hand the old code a state it did not write. With StreamData, give it a generator to check many states, and get the smallest failing one:

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

A live process: assert_survives_deploy/3

Deploys while the process runs and fails unless:

  • the same pid is alive after the deploy (and its registered name still points to it);
  • it is not left on the old code (a local receive loop: the next deploy would be refused);
  • its state changed when the module's vsn did (state of MyApp.Counter was not migrated: the v1 shape was found after the deploy to v2), and state: accepts it;
  • with rollback: true, a rollback keeps the pid again and gives back the exact state.

Deploy twice: assert_survives_redeploy/3

Some mistakes only show at the second deploy, because Hotcode (like the VM) keeps the displaced version of a module until the next one:

  • a plain process in a local loop stays on the old code; the second deploy must purge it, and the loader refuses (:lingering_old_code) instead of killing it. The failure names the pids;
  • a fun created by the old code and kept in the state works after one deploy, then raises :badfun. Give a probe: that makes the process call it.
assert_survives_redeploy(pid, v2, times: 2, probe: &GenServer.call(&1, :run_callback))

With a release from build/2, the later deploys are rebuilt variants of the same sources (the same code, a different binary); otherwise pass them with then: [release, ...].

Tables: assert_table_upgrade/3, assert_table_deploy/3

For a Hotcode.Table module, assert_table_upgrade/3 runs rows through the chain (and back, unless roundtrip: false) as plain data. assert_table_deploy/3 deploys and checks the live table: its registered version is the new vsn, its rows are exactly the old rows migrated, and with rollback: true a rollback gives back the rows and the version.

test "sessions rows gain a meta map" do
  assert assert_table_upgrade(MyApp.Sessions, [{"s1", "ann"}], from: 1) ==
           [{"s1", "ann", %{}}]
end

Traffic during a deploy: with_load/3, assert_no_lost_messages/2

A deploy suspends the processes whose code changes; messages sent meanwhile wait in their mailboxes. with_load/3 keeps calls going (from concurrency: processes) while an action runs, starting the action only once traffic is flowing and stopping only after more has gone through:

load = with_load(fn _n -> MyApp.Counter.inc(pid) end, [concurrency: 4], fn -> deploy!(v2) end)
assert_no_lost_messages(load, received: MyApp.Counter.count(pid))

The failure reports counts (3 of 1204 messages sent around the deploy failed); assert that nothing was lost, not how much was sent, which depends on the machine.

Several nodes: Hotcode.Test.Cluster

Hotcode.Test.Cluster.start/2 starts real nodes with :peer, each running :hotcode configured like production with keys generated for the test, loads a boot release on each and runs your boot: function. Put a node on another version alone (load/3) to test a cluster halfway through a roll, or run a real signed roll (deploy/3).

The nodes use Erlang distribution on 127.0.0.1, so the machine needs epmd. Tag such tests and exclude the tag where distribution cannot start:

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

The boot: function and anything passed to call/5 must be compiled code (in test/support), not a module of a test file: the nodes load your project's code paths, not your test files.

What it does not check

  • A deploy of your whole release (every changed module at once, the way mix hotcode.build diffs it) is not covered: build only the modules a test is about.
  • Writers that are not suspended by the deploy (another process writing a table) make assert_table_deploy/3 fail; that is a real hazard, see Hotcode.Table.
  • The helpers run the loader of the test VM: what production adds (signatures, the analyzer's view of your release, the cluster) is checked by mix hotcode.check (Credo rules) and by mix hotcode.deploy --dry-run.