Skip to content

Commit

Permalink
Add test for race condition in community gardens
Browse files Browse the repository at this point in the history
If the `register` function uses `get` and `update` instead of
`get_and_update` concurrent operations results in non-unique ids.
  • Loading branch information
cshintov committed Sep 17, 2023
1 parent 2910f92 commit 33d8052
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions exercises/concept/community-garden/test/community_garden_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,24 @@ defmodule CommunityGardenTest do
assert {:ok, pid} = CommunityGarden.start()
assert {:not_found, "plot is unregistered"} = CommunityGarden.get_registration(pid, 1)
end

@tag task_id: 6
test "register multiple plots concurrently" do
{:ok, pid} = CommunityGarden.start()

# Spawn 25 processes that register a plot concurrently
for _ <- 1..25 do
Task.async(fn -> CommunityGarden.register(pid, "user") end)
end
|> Enum.map(&Task.await/1)
|> Enum.map(& &1.plot_id)

# Get the list of registered plot IDs
plot_ids =
CommunityGarden.list_registrations(pid)
|> Enum.map(& &1.plot_id)

# Assert that each plot ID is unique
assert Enum.uniq(plot_ids) == plot_ids
end
end

0 comments on commit 33d8052

Please sign in to comment.