Skip to content

Commit

Permalink
Ensure calling persist_and_close when terminated by supervisor.
Browse files Browse the repository at this point in the history
  • Loading branch information
jechol committed Oct 20, 2020
1 parent 18055b2 commit 2745615
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 12 deletions.
1 change: 1 addition & 0 deletions lib/ex_rated.ex
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ defmodule ExRated do

@doc false
def init(args) do
Process.flag(:trap_exit, true)
[
{:timeout, timeout},
{:cleanup_rate, cleanup_rate},
Expand Down
20 changes: 8 additions & 12 deletions test/ex_rated_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -80,36 +80,35 @@ defmodule ExRatedServerTest do
@tag persistent: false
test "data is not persisted on server stop", context do
assert {:ok, 1} = ExRated.check_rate("my-bucket", 10_000, 10)
ExRated.stop(context[:exrated_server])
:ok = ExUnit.Callbacks.stop_supervised(ExRated)
assert File.exists?(context[:exrated_table] |> to_string) == false
end

@tag persistent: true
test "data is persisted on server stop", context do
assert {:ok, 1} = ExRated.check_rate("my-bucket", 10_000, 10)
ExRated.stop(context[:exrated_server])
:ok = ExUnit.Callbacks.stop_supervised(ExRated)
assert File.exists?(context[:exrated_table] |> to_string)
end

@tag persistent: true
test "in memory data and on disk data are the same when persisted", context do
assert {:ok, 1} = ExRated.check_rate("my-bucket", 10_000, 10)
data = ExRated.inspect_bucket("my-bucket", 10_000, 10)
ExRated.stop(context[:exrated_server])
:ok = ExUnit.Callbacks.stop_supervised(ExRated)

# assert process is not running
assert Process.alive?(context[:exrated_server]) == false
refute Process.alive?(context[:exrated_server])

# restart server in persistent mode
{:ok, pid} = start_server(context[:exrated_table], true)
{:ok, _pid} = start_server(context[:exrated_table], true)

# assert it reloads the data from disk
# remove key #2 in data before comparison: it is a timestamp and it's never the same
volatile = data |> Tuple.delete_at(2)
persistent = ExRated.inspect_bucket("my-bucket", 10_000, 10) |> Tuple.delete_at(2)

assert volatile == persistent
ExRated.stop(pid)
end

test "bucket names can be any()" do
Expand All @@ -119,11 +118,8 @@ defmodule ExRatedServerTest do
end

defp start_server(_table, persistent) do
GenServer.start_link(ExRated, [
{:timeout, 10_000},
{:cleanup_rate,10_000},
{:persistent, persistent},
], [name: :ex_rated])
args = [{:timeout, 10_000}, {:cleanup_rate,10_000}, {:persistent, persistent}]
opts = [name: :ex_rated]
{:ok, _child} = ExUnit.Callbacks.start_supervised({ExRated, [args, opts]})
end

end

0 comments on commit 2745615

Please sign in to comment.