fix: race condition in tests

This commit is contained in:
Krzysztof Dryś 2024-04-02 16:21:34 +02:00
parent 7470368137
commit fab72d46c7
3 changed files with 13 additions and 5 deletions

View File

@ -19,7 +19,7 @@ jobs:
go-version: '1.22' go-version: '1.22'
- name: Unit Test - name: Unit Test
run: make unit-tests run: make unit-tests-ci
- name: e2e Test - name: e2e Test
run: make ci-e2e run: make ci-e2e

View File

@ -21,9 +21,13 @@ up: ## run all applications in stack
docker compose up -d docker compose up -d
.PHONY: unit-tests .PHONY: unit-tests
unit-tests: ## run unit tests without e2e-tests directory.. unit-tests: ## run unit tests without e2e-tests directory.
go test -race -count=1 `go list ./... | grep -v e2e-tests` go test -race -count=1 `go list ./... | grep -v e2e-tests`
.PHONY: unit-tests-ci
unit-tests-ci: ## run unit tests without e2e-tests directory (multiple times to find race conditions).
go test -race -count=50 -failfast `go list ./... | grep -v e2e-tests`
.PHONY: ci-e2e .PHONY: ci-e2e
ci-e2e: up ci-e2e: up
go run ./e2e-tests/scripts/wait-ready/main.go -addr=':80;:8081;:8082' go run ./e2e-tests/scripts/wait-ready/main.go -addr=':80;:8081;:8082'
@ -40,4 +44,4 @@ tests-e2e: ## run end to end tests
vendor-licenses: ## report vendor licenses vendor-licenses: ## report vendor licenses
go-licenses report ./cmd/api --template licenses.tpl > licenses.json 2> licenses-errors go-licenses report ./cmd/api --template licenses.tpl > licenses.json 2> licenses-errors

View File

@ -54,10 +54,15 @@ func TestCreateRemoveConcurrently(t *testing.T) {
hubs := &sync.Map{} hubs := &sync.Map{}
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
wg.Add(channelsNo * clientsPerChannel) // First we create `channelsNo` goroutines. Each of them creates `clientsPerChannel` sub-goroutines.
// This gives us `channelsNo*clientsPerChannel` sub go-routines and `channelsNo` parent goroutines.
// Each of them will call `wg.Done() once and we can't progress until all of them are done.
wg.Add(channelsNo*clientsPerChannel + channelsNo)
for i := 0; i < channelsNo; i++ { for i := 0; i < channelsNo; i++ {
channelID := fmt.Sprintf("channel-%d", i) channelID := fmt.Sprintf("channel-%d", i)
go func() { go func() {
defer wg.Done()
for j := 0; j < clientsPerChannel; j++ { for j := 0; j < clientsPerChannel; j++ {
c, h := hp.registerClient(channelID, &websocket.Conn{}) c, h := hp.registerClient(channelID, &websocket.Conn{})
hubs.Store(h, struct{}{}) hubs.Store(h, struct{}{})
@ -70,7 +75,6 @@ func TestCreateRemoveConcurrently(t *testing.T) {
hubs.Store(h, struct{}{}) hubs.Store(h, struct{}{})
}() }()
} }
wg.Wait() wg.Wait()
for c, hub := range hp.hubs { for c, hub := range hp.hubs {