Mnesia delete_schema does not work as "expected" in mix test

Below is the test I have, it runs ok but there is something I could not figure out why.

  1. delete_schema cannot remove the files under Mnesia’s directory. It looks like the schema is not removed.

  2. According to the testing in erlang/iex and documentation, delete_schema should have no dependencies on delete_table, but if I haven’t added the delete_table there, the second time run mix test will fail and complains ‘already_existed’

defmodule DataService.Provider.MnesiaTest do
  use ExUnit.Case
  alias :mnesia, as: Mnesia

  @node_list [node()]

  setup_all do
    on_exit fn ->
      Mnesia.stop()
      Mnesia.delete_schema(@node_list)
    end

    Mnesia.create_schema(@node_list)
    Mnesia.start()
  end

  setup context do
    on_exit fn ->
      # Must delete all tables and stop Mnesia first before deleting schema 
      Enum.each(context[:mnesia_tables], fn table ->
        Mnesia.delete_table(table)
      end)
    end
  end

  @tag mnesia_tables: [:test]
  test "Create table" do
    assert {:atomic, :ok} == Mnesia.create_table(:test, [attributes: [:id, :title, :tags], disc_copies: @node_list])
  end

  @tag mnesia_tables: [:test]
  test "Insert Data" do
    assert {:atomic, :ok} == Mnesia.create_table(:test, [attributes: [:id, :title, :tags], disc_copies: @node_list])

    assert {:atomic, :ok} == Mnesia.transaction(fn ->
      Mnesia.write({:test, 1, "title", [:dummy]})
    end)

    assert [{:test, 1, "title", [:dummy]}] == Mnesia.dirty_read(:test, 1)
  end
end
2 Likes

Finally, I got this problem “resolved” although the actual reason is not figured out yet. You may see this blog for the observation on different behavior and the solution.

Any advice or clue is still welcome.

2 Likes