📎 Webclip
Simulating Distributed Clusters for Elixir Unit Tests
The post says distributed testing in Elixir is awkward because the OTP tools are useful but not obvious, and because many projects rely on them directly without common utilities. For Cachex, the author wanted only a way to start a set of nodes in a local cluster and call them through :rpc, so he split that into a separate library called Local Cluster.
Reading notes#
- distributed behavior in Elixir is described as annoying to test, even though OTP has useful tools
- many projects, including Phoenix, build distributed tests directly on standard OTP tools
- Local Cluster was created as a small separate library for starting local distributed nodes
- the API is intentionally tiny and avoids extra DSLs or unnecessary utilities
LocalCluster.start/0starts the manager instance and can be called more than onceLocalCluster.start_nodes/2starts named nodes in a local cluster, using a prefix and a countstart_nodes/2links the nodes to the current process, which makes cleanup easy in ExUnit- clusters can be kept across tests by starting them in
setup/0and cleaning them inteardown/0 start_nodes/2returns node names that can be used with:rpc- the current VM is not included in the returned list of nodes
stop_nodes/1stops selected nodes, andstop/0stops the manager- under the hood, the manager is started with
:net_kernel.start/1on 127.0.0.1 - the Erlang Boot Server is started on first startup so nodes can fetch code and startup scripts
- new nodes are created with the
:slavemodule and named from the user prefix plus a number - Local Cluster loads code paths on the new nodes, copies application environment and Mix environment, and starts required applications
- the result is that the new nodes match the current working node
- the example test starts a cluster, pings three nodes, stops one node, and then stops the manager
- the nodes are linked to the test process, so most tests only need the first two setup lines
