Skip to content

Instantly share code, notes, and snippets.

@ereshzealous
Last active August 4, 2021 06:26
Show Gist options
  • Select an option

  • Save ereshzealous/36c64d97c4b10596f658497a173e335e to your computer and use it in GitHub Desktop.

Select an option

Save ereshzealous/36c64d97c4b10596f658497a173e335e to your computer and use it in GitHub Desktop.
func TestTransferTxDeadlock(t *testing.T) {
store := NewStore(testDB)
sourceAccount := CreateRandomAccount(t)
targetAccount := CreateRandomAccount(t)
fmt.Println(">> before:", sourceAccount.Balance, targetAccount.Balance)
n := 10
amount := int64(10)
errs := make(chan error)
for i := 0; i < n; i++ {
sourceAccountID := sourceAccount.ID
targetAccountID := targetAccount.ID
if i%2 == 1 {
sourceAccountID = targetAccount.ID
sourceAccountID = sourceAccount.ID
}
go func() {
_, err := store.transferTx(context.Background(), AccountTransferTxParams{
SourceAccountID: sourceAccountID,
TargetAccountID: targetAccountID,
Amount: amount,
})
errs <- err
}()
}
for i := 0; i < n; i++ {
err := <-errs
require.NoError(t, err)
}
// check the final updated balance
updatedAccount1, err := store.GetAccountDetails(context.Background(), sourceAccount.ID)
require.NoError(t, err)
updatedAccount2, err := store.GetAccountDetails(context.Background(), targetAccount.ID)
require.NoError(t, err)
fmt.Println(">> after:", updatedAccount1.Balance, updatedAccount2.Balance)
require.Equal(t, sourceAccount.Balance, updatedAccount1.Balance)
require.Equal(t, targetAccount.Balance, updatedAccount2.Balance)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment