|
| 1 | +defmodule Support.AvroSchemaStore do |
| 2 | + @moduledoc """ |
| 3 | + A host process and a wrapper for :avro_schema_store produced tables. |
| 4 | + Used only in tests |
| 5 | +
|
| 6 | + See more: `Avrora.AvroSchemaStore` |
| 7 | +
|
| 8 | + ## Examples: |
| 9 | +
|
| 10 | + test "when we need test schema store creation" do |
| 11 | + {:ok, _} = start_link_supervised!(Support.AvroSchemaStore) |
| 12 | + stub(Avrora.ConfigMock, :ets_lib, fn -> Support.AvroSchemaStore end) |
| 13 | +
|
| 14 | + assert Support.AvroSchemaStore.count() == 0 |
| 15 | +
|
| 16 | + Support.AvroSchemaStore.new() |
| 17 | + assert Support.AvroSchemaStore.count() == 1 |
| 18 | + end |
| 19 | + """ |
| 20 | + |
| 21 | + @prefix "avrora__test" |
| 22 | + |
| 23 | + use GenServer |
| 24 | + |
| 25 | + def start_link(opts \\ []) do |
| 26 | + {name_opts, _} = Keyword.split(opts, [:name]) |
| 27 | + opts = Keyword.merge([name: __MODULE__], name_opts) |
| 28 | + |
| 29 | + GenServer.start_link(__MODULE__, [], opts) |
| 30 | + end |
| 31 | + |
| 32 | + @impl true |
| 33 | + def init(_state \\ []), do: {:ok, []} |
| 34 | + |
| 35 | + @impl true |
| 36 | + def handle_call({:new}, _from, state), |
| 37 | + do: {:reply, :avro_schema_store.new(name: String.to_atom("#{@prefix}-#{rand()}")), state} |
| 38 | + |
| 39 | + def handle_call({:count}, _from, state), |
| 40 | + do: {:reply, Enum.count(:ets.all(), &is_test_store/1), state} |
| 41 | + |
| 42 | + @doc """ |
| 43 | + Creates a new Erlang Term Store. |
| 44 | +
|
| 45 | + ## Examples: |
| 46 | +
|
| 47 | + iex> {:ok, _} = Support.AvroSchemaStore.start_link() |
| 48 | + iex> Support.AvroSchemaStore.new() |> :ets.info() |> Keyword.get(:size) |
| 49 | + 0 |
| 50 | + """ |
| 51 | + @spec new() :: reference() |
| 52 | + def new, do: GenServer.call(__MODULE__, {:new}) |
| 53 | + |
| 54 | + @doc """ |
| 55 | + Returns a number of `:ets` tables matching the test prefix. |
| 56 | +
|
| 57 | + ## Examples: |
| 58 | +
|
| 59 | + iex> {:ok, _} = Support.AvroSchemaStore.start_link() |
| 60 | + iex> Support.AvroSchemaStore.count() |
| 61 | + 0 |
| 62 | + iex> Support.AvroSchemaStore.new() |
| 63 | + iex> Support.AvroSchemaStore.count() |
| 64 | + 1 |
| 65 | + """ |
| 66 | + @spec count() :: non_neg_integer() |
| 67 | + def count, do: GenServer.call(__MODULE__, {:count}) |
| 68 | + |
| 69 | + defp rand, do: :rand.uniform(1_000_000) + System.os_time() |
| 70 | + defp is_test_store(id), do: !is_reference(id) && Atom.to_string(id) =~ @prefix |
| 71 | +end |
0 commit comments