From 77a1027ab037c254d2586935cffeb720fe1daba4 Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Sun, 13 Oct 2024 18:43:30 -0400 Subject: [PATCH] Failing concurrent test --- learn_go_with_tests/my_sync/go.mod | 3 ++ learn_go_with_tests/my_sync/my_sync.go | 13 ++++++ learn_go_with_tests/my_sync/my_sync_test.go | 44 +++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 learn_go_with_tests/my_sync/go.mod create mode 100644 learn_go_with_tests/my_sync/my_sync.go create mode 100644 learn_go_with_tests/my_sync/my_sync_test.go diff --git a/learn_go_with_tests/my_sync/go.mod b/learn_go_with_tests/my_sync/go.mod new file mode 100644 index 0000000..e52cb81 --- /dev/null +++ b/learn_go_with_tests/my_sync/go.mod @@ -0,0 +1,3 @@ +module my_sync + +go 1.23.1 diff --git a/learn_go_with_tests/my_sync/my_sync.go b/learn_go_with_tests/my_sync/my_sync.go new file mode 100644 index 0000000..d56aca6 --- /dev/null +++ b/learn_go_with_tests/my_sync/my_sync.go @@ -0,0 +1,13 @@ +package my_sync + +type Counter struct { + count int +} + +func (c *Counter) Inc() { + c.count++ +} + +func (c *Counter) Value() int { + return c.count +} diff --git a/learn_go_with_tests/my_sync/my_sync_test.go b/learn_go_with_tests/my_sync/my_sync_test.go new file mode 100644 index 0000000..f544c74 --- /dev/null +++ b/learn_go_with_tests/my_sync/my_sync_test.go @@ -0,0 +1,44 @@ +package my_sync + +import ( + "sync" + "testing" +) + +func assertCount(t testing.TB, got Counter, want int) { + t.Helper() + if got.Value() != want { + t.Errorf("got %d, want %d", got.Value(), want) + } +} + +func TestCounter(t *testing.T) { + t.Run("Incrementing the counter 3 times leaves it at 3", func(t *testing.T) { + counter := Counter{} + counter.Inc() + counter.Inc() + counter.Inc() + + assertCount(t, counter, 3) + + }) + + t.Run("it runs safely concurrently", func(t *testing.T) { + wantedCount := 1000 + counter := Counter{} + + var wg sync.WaitGroup + wg.Add(wantedCount) + + for i := 0; i < wantedCount; i++ { + go func() { + counter.Inc() + wg.Done() + }() + } + // blocking call to wait for all goroutines + wg.Wait() + + assertCount(t, counter, wantedCount) + }) +}