Skip to content

Commit

Permalink
fix: add unit test to reproduce the race condition issue
Browse files Browse the repository at this point in the history
  • Loading branch information
Muhammad Luthfi Fahlevi committed Feb 7, 2025
1 parent 7acbcda commit f05f073
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions internal/store/postgres/asset_repository_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/stretchr/testify/assert"

Check failure on line 7 in internal/store/postgres/asset_repository_test.go

View workflow job for this annotation

GitHub Actions / golangci

File is not `gci`-ed with --skip-generated -s standard -s default (gci)

Check failure on line 7 in internal/store/postgres/asset_repository_test.go

View workflow job for this annotation

GitHub Actions / golangci

File is not `gofumpt`-ed with `-extra` (gofumpt)
"os"
"sort"
"strconv"
"strings"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -1267,6 +1269,53 @@ func (r *AssetRepositoryTestSuite) TestUpsert() {
})
}

func (r *AssetRepositoryTestSuite) TestUpsertRaceCondition() {
r.Run("TestUpsertRaceCondition", func() {
ast := asset.Asset{
URN: "urn-u-3",
Type: "table",
Service: "bigquery",
URL: "https://sample-url-old.com",
UpdatedBy: r.users[0],
Version: "0.1",
}

id, err := r.repository.Upsert(r.ctx, &ast)
r.Require().NoError(err)
r.NotEmpty(id)
ast.ID = id

const numGoroutines = 10 // Number of concurrent upserts
var wg sync.WaitGroup
var mu sync.Mutex
results := make([]error, 0, numGoroutines)

// Concurrently upsert the object
for i := 0; i < numGoroutines; i++ {
wg.Add(1)
go func(index int) {
defer wg.Done()

localAst := ast
localAst.URL = fmt.Sprintf("https://sample-url-%d.com", index)
_, err := r.repository.Upsert(r.ctx, &localAst)

mu.Lock()
results = append(results, err)
mu.Unlock()
}(i)
}

wg.Wait()

// Check for errors
for i, err := range results {
fmt.Println("err", i, ": ", err)

Check failure on line 1313 in internal/store/postgres/asset_repository_test.go

View workflow job for this annotation

GitHub Actions / golangci

use of `fmt.Println` forbidden by pattern `^(fmt\.Print(|f|ln)|print|println)$` (forbidigo)
assert.NoError(r.T(), err, "Upsert should not fail under race conditions")
}
})
}

func (r *AssetRepositoryTestSuite) TestDeleteByID() {
r.Run("return error from client if any", func() {
err := r.repository.DeleteByID(r.ctx, "invalid-uuid")
Expand Down

0 comments on commit f05f073

Please sign in to comment.