I’m trying to run a distributed test case based on Phoenix’s PubSub test cluster, my test_helper.exs
file looks something like this:
ExUnit.configure(exclude: [:cluster])
include = Keyword.get(ExUnit.configuration(), :include, [])
if :cluster in include do
# this line start my cluster, look a Phoenix PubSub's link above
{:ok, _} = MyApp.TestCluster.start()
else
IO.puts("==> Running tests on single node, to run on cluster mode add: --include cluster")
end
ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(Data.Repo, :manual)
Then my cluster_case.ex
file looks like this:
defmodule MyApp.ClusterCase do
use ExUnit.CaseTemplate
@timeout 5000
using do
quote do
import unquote(__MODULE__)
import MyApp.Factory # ex_machina factory
@moduletag :cluster
@timeout unquote(@timeout)
end
end
setup do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(MyApp.Repo)
end
def nodes do
Node.list()
end
def rpc(func) when is_function(func) do
parent = self()
ref = make_ref()
node = nodes()
|> Enum.random()
Node.spawn_link(node, fn ->
Ecto.Adapters.SQL.Sandbox.allow(MyApp.Repo, parent, self())
result = func.()
Kernel.send(parent, {ref, result})
ref = Process.monitor(parent)
receive do
{:DOWN, ^ref, :process, _, _} -> :ok
end
end)
receive do
{^ref, result} -> result
after
@timeout -> {:error, :timeout}
end
end
end
Everything works fine if I use mix test
, all Ecto transactions are reverted and my test DB is clean after tests run.
When I run mix test --include cluster
, Ecto transactions are not reverting, causing some tests to fail, If I check the test DB after test suite runs, I can see my tables are not clean. Is there any setting I’m missing? Or is there a way I can manually revert each transaction?
Thanks.