user_subscription_lock_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package repository
  2. import (
  3. "context"
  4. "strings"
  5. "testing"
  6. "time"
  7. "github.com/DATA-DOG/go-sqlmock"
  8. dbent "github.com/Wei-Shaw/sub2api/ent"
  9. _ "github.com/Wei-Shaw/sub2api/ent/runtime"
  10. "github.com/Wei-Shaw/sub2api/ent/usersubscription"
  11. "github.com/stretchr/testify/require"
  12. "entgo.io/ent/dialect"
  13. entsql "entgo.io/ent/dialect/sql"
  14. )
  15. func TestUserSubscriptionGetByIDForUpdateLocksRow(t *testing.T) {
  16. var capturedSQL string
  17. db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(captureEntQueryMatcher{actual: &capturedSQL}))
  18. require.NoError(t, err)
  19. t.Cleanup(func() { _ = db.Close() })
  20. driver := entsql.OpenDB(dialect.Postgres, db)
  21. client := dbent.NewClient(dbent.Driver(driver))
  22. t.Cleanup(func() { _ = client.Close() })
  23. repo := NewUserSubscriptionRepository(client)
  24. now := time.Date(2026, 8, 2, 12, 0, 0, 0, time.UTC)
  25. mock.ExpectQuery("locked subscription").WillReturnRows(
  26. sqlmock.NewRows(usersubscription.Columns).AddRow(
  27. int64(7), now, now, nil, int64(11), int64(13), now, now.AddDate(0, 0, 30), "active",
  28. nil, nil, nil, 0.0, 0.0, 0.0, nil, now, "renewal",
  29. ),
  30. )
  31. sub, err := repo.GetByIDForUpdate(context.Background(), 7)
  32. require.NoError(t, err)
  33. require.Equal(t, int64(7), sub.ID)
  34. require.NoError(t, mock.ExpectationsWereMet())
  35. require.Contains(t, strings.ToUpper(normalizeSQLWhitespace(capturedSQL)), "FOR UPDATE")
  36. }